Python AST: Several semantics are unclear, for example. expr_context

Is there more astdocumentation about the module ast?

Esp., I wonder what expr_context(and all its possible meanings) exactly means.

Also, what is the difference between Assignand AugAssign?

Also, when assigning a local variable, can you refer to a real Python object instead of a name? I create an AST myself, and I have some Python objects that I want to access in an AST. An alternative would be to introduce some kind of dummy temp var name for them and add that dummy var name to the scope globals()for a later compiled function, but this seems a bit bad (slow and hacked) for me.

+5
source share
2 answers

I will try to answer it myself.

After some testing and guessing:

expr_contextlocated where Namedefined, for example. if it is in the task on the left side ( Store, AugStore), the right side ( Load, AugLoad), in del( del) or in the list of arguments, for example, from FunctionDefor Lambda( Param).

AugAssignsimilar to a = a <op> b. Assignis just plain a = b.

I have not found a way to reference a real Python object, and it seems to be missing.

+9
source

You can drag and drop a real Python object into AST using Str (s =) or Num (n =). For example, the following passes an object to a function directly, 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"

. Python 2.7. , , .

+3

All Articles