deb*_*ish 3 python abstract-syntax-tree
我试图了解执行python代码的过程。假设源具有函数定义。使用ast.parse(),我将其解析为一个ast,它将包含该FunctionDef节点类的实例。该节点实例不是可调用的,并且与函数对象不同。如何从这个ast创建具有所有dunder属性的函数对象?
您(据我所知)不能像FunctionDef一样编译任意的单个AST节点。您可以做的是将整个代码段编译为一个模块,在提供的名称空间中执行它,然后访问其内容,包括函数。这是一个例子:
import ast
txt = """
def foo(x, y=2):
z = x*y + 3
print("z is", z)
return z**2
"""
tree = ast.parse(txt, mode='exec')
code = compile(tree, filename='blah', mode='exec')
namespace = {}
exec(code, namespace)
Run Code Online (Sandbox Code Playgroud)
Now namespace is the equivalent of the __dict__ of a module containing the given code. You can access and call the function:
>>> namespace['foo']
<function foo at 0x00000000023A2B70>
>>> namespace['foo'](2, 3)
z is 9
81
Run Code Online (Sandbox Code Playgroud)
Note that if this is all you want to do, there's no need to use ast at all. You can just compile the source string directly with compile(tree, filename='blah', mode='exec'). And in fact there's no need to even involve compile, since you can just exec the source string directly with exec(txt, namespace). If your goal is just to get the final function object out, you don't really need access to the internal parse and compile steps; just exec the whole thing in a namespace and then grab the function from there.
| 归档时间: |
|
| 查看次数: |
869 次 |
| 最近记录: |