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

Nick Coghlan ncoghlan at gmail.com
Wed May 1 05:51:36 CEST 2013


On Wed, May 1, 2013 at 11:35 AM, Haoyi Li <haoyi.sg at gmail.com> wrote:
> Isn't that the distinction between repr() and str()? That repr() is
> generally (to a greater extent) meant to return eval()-able code, while
> str() is just something nice to look at.

The stronger distinction is that repr() is ideally never ambiguous
about the corresponding value, while str() might be. For example:

>>> "1"
'1'
>>> 1
1
>>> str("1")
'1'
>>> str(1)
'1'

That desire for an unambiguous repr for each value is why CPython
defaults to using "<TYPE at ADDRESS>"

Having repr support eval is certainly nice when practical, but it's
far from a requirement. Even the desire for a unique repr-per-value
isn't a guarantee, since some types *do* impose a size limit.

> I don't think the # of pages it outputs should really matter, if the thing
> you are printing really is that big. It won't be much bigger than printing
> big lists or dicts, and we happily let those cause the terminal to scroll
> for minutes at a time if we accidentally print them. The default behavior
> (e.g. when you print() it or string-interpolate it) would still give you
> something short and nice to look at. Presumably when someone called repr()
> instead of str(), he was hoping for some sort of eval()-able code snippet.

In this particular case, I'm also inclined to favour the approach of
using ast.dump as the repr for AST nodes. Call it +0.

Adding support for depth limiting and peer node limiting to ast.dump
(with missing nodes replaced with "...") would also be neat.

Cheers,
Nick.

--
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list