Skip to content

Commit 5814637

Browse files
authored
Add files via upload
1 parent f026fb2 commit 5814637

1 file changed

Lines changed: 89 additions & 0 deletions

File tree

thinkpython.py

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
import contextlib
2+
import io
3+
import re
4+
5+
from IPython.core.magic import register_cell_magic
6+
from IPython.core.magic_arguments import argument, magic_arguments, parse_argstring
7+
8+
9+
def traceback(mode):
10+
"""
11+
"""
12+
with contextlib.redirect_stdout(io.StringIO()):
13+
get_ipython().run_cell(f'%xmode {mode}')
14+
15+
16+
def extract_function_name(text):
17+
"""Find a function definition and return its name.
18+
19+
text: String
20+
21+
returns: String or None
22+
"""
23+
pattern = r"def\s+(\w+)\s*\("
24+
match = re.search(pattern, text)
25+
if match:
26+
func_name = match.group(1)
27+
return func_name
28+
else:
29+
return None
30+
31+
32+
@register_cell_magic
33+
def add_method_to(args, cell):
34+
35+
# get the name of the function defined in this cell
36+
func_name = extract_function_name(cell)
37+
if func_name is None:
38+
return f"This cell doesn't define any new functions."
39+
40+
# get the class we're adding it to
41+
namespace = get_ipython().user_ns
42+
class_name = args
43+
cls = namespace.get(class_name, None)
44+
if cls is None:
45+
return f"Class '{class_name}' not found."
46+
47+
# save the old version of the function if it was already defined
48+
old_func = namespace.get(func_name, None)
49+
if old_func is not None:
50+
del namespace[func_name]
51+
52+
# Execute the cell to define the function
53+
get_ipython().run_cell(cell)
54+
55+
# get the newly defined function
56+
new_func = namespace.get(func_name, None)
57+
if new_func is None:
58+
return f"This cell didn't define {func_name}."
59+
60+
# add the function to the class and remove it from the namespace
61+
setattr(cls, func_name, new_func)
62+
del namespace[func_name]
63+
64+
# restore the old function to the namespace
65+
if old_func is not None:
66+
namespace[func_name] = old_func
67+
68+
69+
@register_cell_magic
70+
def expect_error(line, cell):
71+
try:
72+
get_ipython().run_cell(cell)
73+
except Exception as e:
74+
get_ipython().run_cell('%tb')
75+
76+
77+
78+
@magic_arguments()
79+
@argument('exception', help='Type of exception to catch')
80+
@register_cell_magic
81+
def expect(line, cell):
82+
args = parse_argstring(expect, line)
83+
exception = eval(args.exception)
84+
try:
85+
get_ipython().run_cell(cell)
86+
except exception as e:
87+
get_ipython().run_cell("%tb")
88+
89+

0 commit comments

Comments
 (0)