Last active
March 11, 2022 12:29
-
-
Save jkbjh/6176fcb4c4d87edbcfdfb15788b263a5 to your computer and use it in GitHub Desktop.
interactive python dark magic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Dark magic for interactive python.""" | |
import builtins | |
import time | |
def ipy_here(leak_variables=True): | |
import IPython | |
import inspect | |
parent_frame = inspect.currentframe().f_back | |
z = dict(parent_frame.f_globals) | |
z.update(parent_frame.f_locals) | |
import IPython | |
print("starting with frame %s" % (parent_frame,)) | |
IPython.start_ipython(argv=[], user_ns=z) | |
if leak_variables: | |
parent_frame.f_locals.update(z) | |
import ctypes | |
ctypes.pythonapi.PyFrame_FastToLocals(ctypes.py_object(parent_frame)) | |
parent_frame.f_locals.update(z) | |
ctypes.pythonapi.PyFrame_LocalsToFast( | |
ctypes.py_object(parent_frame), ctypes.c_int(0) | |
) | |
parent_frame.f_back.f_locals.update(z) | |
time.sleep(0.5) # allow some time for killing | |
# continue here DBG AOEU | |
def check_global_vars(func): | |
import inspect | |
cv = inspect.getclosurevars(func) | |
bad_closure = [] | |
def check_thing(thing): | |
return ( | |
inspect.isfunction(thing) | |
or inspect.ismodule(i) | |
or inspect.isclass(i) | |
or inspect.isroutine(i) | |
) | |
for k, i in cv.globals.items(): | |
if not check_thing(i): | |
bad_closure.append((k, type(i))) | |
for k, i in cv.nonlocals.items(): | |
if not check_thing(i): | |
bad_closure.append((k, type(i))) | |
if bad_closure: | |
raise RuntimeError("Bad closure: %r" % (bad_closure)) | |
return func | |
builtins.ipy_here = ipy_here |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment