Created
July 7, 2013 21:35
-
-
Save shtaxxx/5945076 to your computer and use it in GitHub Desktop.
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 ast | |
import inspect | |
import sys | |
def create_func_from_ast(targ, arg_globals=globals()): | |
source = "def __target_func__(*args, **kw): return True\n" | |
func_ast = ast.parse(source) | |
func_ast.body[0].body[0].value = targ | |
func_ast = ast.fix_missing_locations(func_ast) | |
code = compile(func_ast, '<string>', 'exec') | |
locals = {} | |
eval(code, arg_globals, locals) | |
return locals['__target_func__'] | |
def eval_ast(targ, arg_globals=globals(), arg_locals=locals()): | |
if not isinstance(targ, ast.Expression): | |
targ = ast.Expression(targ) | |
targ = ast.fix_missing_locations(targ) | |
code = compile(targ, '<string>', 'eval') | |
return eval(code, arg_globals, arg_locals) | |
class Test(): | |
def __init__(self): | |
print("created Class Test") | |
t = ast.Call(func=ast.Name(id='Test', ctx=ast.Load()), args=[], keywords=[], | |
starargs=None, kwargs=None) | |
func = create_func_from_ast( t ) | |
a = func() | |
print(a) | |
b = eval_ast(t) | |
print(b) | |
c = 10 | |
t = ast.BinOp(ast.Name('c', ast.Load()), ast.Add(), ast.Num(2)) | |
print( eval_ast(t) ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment