Abstract Syntax Tree conundrum
Andrew Dalke
adalke at mindspring.com
Sat Jan 3 13:25:24 EST 2004
Lonnie Princehouse:
> The compiler's AST implementation seems better for (1), but I can't
> for the life of me figure out how to compile it into a code object,
Does this help?
>>> a
Traceback (most recent call last):
File "<pyshell#20>", line 1, in -toplevel-
a
NameError: name 'a' is not defined
>>> import compiler
>>> compiler.parse("a=3+4")
Module(None, Stmt([Assign([AssName('a', 'OP_ASSIGN')], Add((Const(3),
Const(4))))]))
>>> x=_
>>> x.filename = "<string>"
>>> compiler.pycodegen.ModuleCodeGenerator(x).getCode()
<code object <module> at 00A28360, file "<string>", line 1>
>>> c = _
>>> exec c
>>> a
7
>>>
The compiler module is somewhat cumbersome (eg, the need to force
a 'filename' attribute above) and woefully underdocumented, but much
better to use than the results of the parser structure.
> and there's not even an apparent way to convert it back into source (I
> suppose I could write a function to do this, but it seems like there
> should be a better way).
That one I don't know about. decompyle seems like your best bet.
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list