[issue24002] Add un-parse function to ast

Larry Hastings report at bugs.python.org
Sun Apr 19 20:17:36 CEST 2015


Larry Hastings added the comment:

There is!  compile() will do it, though the docstring doesn't mention it. (The full documentation does.)

The following function meets both my use cases:

    def eval_ast_expr(node, symbols=None, *, filename='-'):
        """
        Takes an ast.Expr node.  Compiles and evaluates it.
        Returns the result of the expression.

        symbols represents the globals dict the expression
        should see.  (There's no equivalent for "locals" here.)
        """

        if not isinstance(node, ast.Expr):
            raise RuntimeError(
                "eval_ast_expr: node must be of type ast.Expr")

        if symbols == None:
            symbols = globals()

        a = ast.Expression(node.value)
        co = compile(a, filename, 'eval')
        fn = types.FunctionType(co, symbols)
        return fn()

I am therefore closing this bug.  It still seems like a nice-to-have but I'll let somebody else do it when *they* have a use case.

----------
resolution:  -> later
stage: needs patch -> resolved
status: open -> closed

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue24002>
_______________________________________


More information about the Python-bugs-list mailing list