[Python-Dev] More imformative iterator representations

Robert Brewer fumanchu at amor.org
Tue Apr 6 22:00:31 EDT 2004

Raymond Hettinger wrote:
> Armin's note reminded me that the only thing I do not like about using
> iterators is not being able to see their contents at the interactive
> prompt.  So, I posted an idea about changing the print part of the
> read-eval-print loop to display more information:
> >>> enumerate('abcdefgh') 
> <enumerate object at 0x401a102c:  (0, 'a') (1, 'b') (2, 'c') ...>
> There a couple of problems with the approach.  One is how to 
> identify an
> iterator object -- the presence of __iter__() and next() is a good but
> not perfect indicator.

Oh, I don't know. The Library Ref makes it pretty clear:

"The iterator objects themselves are required to support the following
two methods, which together form the iterator protocol: 
__iter__() ...
next() "

If not perfect, it's still a reasonable assumption. Since there's no
Iterator superclass from which to inherit, you're going to have to
rewrite each repr by hand anyway, and therefore can decide each one
independently. Are there reasonable iterator objects which don't follow
the "iterator protocol"?

> An alternative to the read-eval-print approach is providing a custom
> __repr__() method for the builtin iterators.


> Q:  Are there any other candidate output formats?
> A:  Yes, we could add length information for a more mathematical style
> output:
>     reversed(['h', 'g', 'f', ... to 8 objects])

The very presence of __len__ might be a strong argument for providing
the new repr, and its absence an indicator to avoid such.

Robert Brewer
Amor Ministries
fumanchu at amor.org

More information about the Python-Dev mailing list