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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With