Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 991
Albert Avatar asked Jul 13 '11 12:07

Albert


2 Answers

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.

like image 196
Albert Avatar answered Nov 02 '22 23:11

Albert


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.

like image 43
wump Avatar answered Nov 02 '22 21:11

wump