[Python-ideas] A nice __repr__ for the ast.* classes?

Guido van Rossum guido at python.org
Wed May 1 03:21:12 CEST 2013


But do you really want it to print the entire parse tree even if it
represents several pages of code?

On Tue, Apr 30, 2013 at 6:12 PM, Haoyi Li <haoyi.sg at gmail.com> wrote:
> Wouldn't it be nice if this
>
>>>> import ast
>>>> print repr(ast.parse("(1 + 1)").body[0].value)
> <_ast.BinOp object at 0x0000000001E94B38>
>
> printed something more useful?
>
>>>> print repr(ast.parse("(1 + 1)").body[0].value)
> BinOp(left=Num(n=1), op=Add(), right=Num(n=1))
>
> I've been doing some work on macropy, which uses the ast.* classes
> extensively, and it's annoying that we have to resort to dirty-tricks like
> monkey-patching the AST classes (for CPython 2.7) or even monkey-patching
> __builtin__.repr (to get it working on PyPy) just to get
>
>     eval(repr(my_ast)) == my_ast
>
> to hold true. And a perfectly good solution already exists in the ast.dump()
> method, too! (It would also be nice if "==" did a structural comparison on
> the ast.* classes too, but that's a different issue).
>
> -Haoyi
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>



-- 
--Guido van Rossum (python.org/~guido)



More information about the Python-ideas mailing list