[Python-Dev] string representation of range in 3.0

Nick Coghlan ncoghlan at gmail.com
Wed Apr 16 16:03:46 CEST 2008

Isaac Morland wrote:
> On Wed, 16 Apr 2008, Paul Moore wrote:
>> On 16/04/2008, Armin Rigo <arigo at tunes.org> wrote:
>>> What about the less confusing and more readily generalizable:
>>>   <range object 0, 1, ..., 9>
>>> It would also be helpful IMHO to use this kind of repr for most built-in
>>> iterators and iterables, instead of their mosty-useless default repr.
>> I quite like this. But as a non-beginner, I'll freely admit that my
>> intuitions are suspect :-)
> I like this too.  For iterators, though, would you always show the next 
> couple of elements?  The values "contained in" the iterator will change as 
> the iterator iterates.  Alternatively, the representation could be 
> "frozen" to reflect the values originally pending in the iterator, but 
> then the representation wouldn't show anything about the current state of 
> the iterator.

You can't write nice repr's for arbitrary iterators, or things like 
enumerate and friends that can operate on arbitrary iterator, because 
you have no way to get at the 'first few' and 'the last' value.

You can only have a nice representation like that for iterables like 
range which have random access to the underlying values. Note that range 
is NOT an iterator in Py3k as it has no __next__ method (the same hold 
trues for xrange in 2.x).

However, it would be really nice if collections.dict_keys, 
collections.dict_items and collections.dict_values could provide a nice 
repr implementation that was the rough equivalent of:

def full_repr(self):
   contents = ', '.join(map(repr, self))
   return "<%s: {%s}>" % (self.__class__.__name__, contents)

 >>> d = dict(a=1, b=2, c=3)
 >>> d
{'a': 1, 'c': 3, 'b': 2}
 >>> full_repr(d.keys())
"<dict_keys: {'a', 'c', 'b'}>"
 >>> full_repr(d.values())
'<dict_values: {1, 3, 2}>'
 >>> full_repr(d.items())
"<dict_items: {('a', 1), ('c', 3), ('b', 2)}>"


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

More information about the Python-Dev mailing list