Skip to content

Instantly share code, notes, and snippets.

@Elizaveta239
Created January 12, 2017 20:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Elizaveta239/a7e2e32f7f40d71c70ac2811d5ed8660 to your computer and use it in GitHub Desktop.
Save Elizaveta239/a7e2e32f7f40d71c70ac2811d5ed8660 to your computer and use it in GitHub Desktop.
import dis
import inspect
def trace():
print("hello!")
def insert_code(code_to_modify, lines_to_insert, before_line):
lines = inspect.getsourcelines(code_to_modify)[0]
line_for_break = lines[before_line]
spaces = line_for_break[:len(line_for_break)-len(line_for_break.lstrip())]
lines_insert_indent = []
for line in lines_to_insert:
lines_insert_indent.append(spaces + line)
new_lines = lines[1:before_line] + lines_insert_indent + lines[before_line:]
res = "".join(new_lines)
print(res)
return compile(res, '<string>', 'exec')
my_func = """def foo():
trace()
a = 1
b = 2
"""
code = compile(my_func, '<string>', 'exec')
dis.dis(code)
loc_dict = {}
res = eval(code, {}, loc_dict)
print(loc_dict)
new_frame_obj = list(loc_dict.values())[0]
new_code = new_frame_obj.__code__
dis.dis(new_code)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment