Skip to content

Instantly share code, notes, and snippets.

@medecau
Last active November 12, 2020 16:47
Show Gist options
  • Save medecau/971aaaef3985a8cd4f43d1c721181640 to your computer and use it in GitHub Desktop.
Save medecau/971aaaef3985a8cd4f43d1c721181640 to your computer and use it in GitHub Desktop.
Interpret python code and update the caller's locals
import inspect
def interpret(src):
"""Compile and execute provided code as if it was local to the caller"""
# get a decent name
try:
name = __file__
except NameError:
name = __name__
# attemt to access callers frame
frame = inspect.currentframe()
if frame.f_back:
frame = frame.f_back
# get the locals
_locals = frame.f_locals
# compile and execute
code = compile(src, name, "exec")
exec(code, globals(), _locals)
src = """
def a(x,y):
return x*y
"""
interpret(src)
print(a, a(3, 4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment