Last active
November 12, 2020 16:47
-
-
Save medecau/971aaaef3985a8cd4f43d1c721181640 to your computer and use it in GitHub Desktop.
Interpret python code and update the caller's locals
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
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