Changing an AST

Fredrik Lundh fredrik at pythonware.com
Mon Oct 10 07:13:31 EDT 2005


"beza1e1" <andreas.zwinkau at googlemail.com> wrote:

> I have such a statement as string: "distance = x**2 + y**2"
> x and y are undefined, so it is no executable Python code, but it is
> parseable. Now i'd like traverse through the AST and change Name('x')
> for the value i have elsewhere. And finally let Python resolve the
> computation.

you can use the parser class for this purpose:

    http://www.effbot.org/librarybook/parser.htm

instead of manipulating the parse tree, you can use the AST to identify
the variables, create a dictionary with the current values, and use exec
or eval to evaluate it.

or you can use a regular expression to dig out all variable names.

or you can compile the expression and analyze the code object to find
the variable names, and use the dictionary/exec approach:

    >>> expr = compile("distance = x**2 + y**2", "", "exec")
    >>> expr.co_varnames
    ('distance',)
    >>> list(set(expr.co_names)  - set(expr.co_varnames))
    ['y', 'x']
    >>> context = {"x": 10, "y": 20}
    >>> exec expr in context
    >>> context["distance"]
    500

(the regular expression approach is probably the only one that's
guaranteed to work on all python implementations)

</F>






More information about the Python-list mailing list