Python AST:几个语义不清楚,例如 expr_context
除了 ast
文档之外,还有关于 ast
模块?
特别是,我想知道 expr_context
(及其所有可能的值)到底意味着什么。
另外,Assign
和 AugAssign
之间有什么区别?
另外,在对局部变量进行赋值时,是否可以引用真实的 Python 对象而不是其名称?我正在自己构建一个 AST,并且我有一些想要在 AST 中访问的 Python 对象。另一种方法是为它们引入一些虚拟临时变量名称,并将该虚拟变量名称添加到稍后编译的函数的 globals() 范围中,但这对我来说似乎有点糟糕(缓慢且hacky)。
Is there any more than the ast
documentation about the ast
module?
Esp., I am wondering what expr_context
(and all its possible values) exactly means.
Also, what is the difference between Assign
and AugAssign
?
Also, it is possible to reference to a real Python object instead of its name when doing an assignment to a local variable? I am building an AST myself and I have some Python objects which I want to access to in the AST. The alternative would be to introduce some dummy temp var name for them and add that dummy var name to the globals()
scope for the later compiled function but that seems somewhat bad (slow and hacky) to me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会尝试自己回答。
经过更多测试和猜测:
expr_context
是定义Name
的位置,例如,如果它位于左侧的赋值中(Store
,AugStore
),右侧(Load
、AugLoad
),在del
中(Del
>) 或在参数列表中,例如 fromFunctionDef
或Lambda
(Param
)。AugAssign
就像a = a; b.
。Assign
只是一个简单的a = b
。我还没有找到一种方法来引用真正的 Python 对象,而且似乎也没有。
I'll try to answer it myself.
After some more testing and guessing:
expr_context
is where theName
is defined, e.g. if it is in an assignment on the left side (Store
,AugStore
), right side (Load
,AugLoad
), in adel
(Del
) or in an argument list like fromFunctionDef
orLambda
(Param
).AugAssign
is likea = a <op> b
.Assign
is just a simplea = b
.I haven't found a way to reference to a real Python object and it seems like there is none.
您可以使用 Str(s=) 或 Num(n=) 将真实的 Python 对象“走私”到 AST 中。例如,下面通过替换字符串直接传递函数对象。
注意:我在 Python 2.7 中检查了这一点。我不确定是否可以保证这对于早期或更高版本都适用。
You can 'smuggle' a real Python object into the AST by use of Str(s=) or Num(n=). For example, the following passes a function object directly by replacing a string.
Note: I checked this in Python 2.7. I'm not sure whether there is a guarantee that this will hold true for earlier or later versions.