Python AST: several semantics unclear, e.g. expr_context

旧时模样 提交于 2021-02-19 02:04:59

问题


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.


回答1:


I'll try to answer it myself.

After some more testing and guessing:

expr_context is where the Name is defined, e.g. if it is in an assignment on the left side (Store, AugStore), right side (Load, AugLoad), in a del (Del) or in an argument list like from FunctionDef or Lambda (Param).

AugAssign is like a = a <op> b. Assign is just a simple a = b.

I haven't found a way to reference to a real Python object and it seems like there is none.




回答2:


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.

import ast

data = '''
x = '1234'
x()
'''
def testfunc():
    print "inside test function"
tree = compile(data, '<string>', 'exec', ast.PyCF_ONLY_AST)

class ModVisitor(ast.NodeVisitor):
    def visit(self, node):
        if isinstance(node, ast.Str):
            node.s = testfunc
        self.generic_visit(node)

ModVisitor().visit(tree)

code = compile(tree, '<string>', 'exec')
exec code # prints "inside test function"

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.



来源:https://stackoverflow.com/questions/6679171/python-ast-several-semantics-unclear-e-g-expr-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!