eval 

Send to Kindle
home » snippets » python » eval



Snippets

# exec
import ast
code_string = "..."
filename = "<stdin>"
env = globals().copy()
mode = "exec" # or "eval"

parse_tree = ast.parse(code_string, filename=filename, mode=mode)

# Transform parse tree as you please.  Then,
code_obj = compile(parse_tree, filename, mode)

# And either
exec code_obj in env, env
# or
result = eval(code_obj, env, env)
# based on mode.