[Python-Dev] xrange identity crisis

Raymond Hettinger python@rcn.com
Tue, 4 Jun 2002 16:57:58 -0400


Xrange was given its own tp_iter slot and now runs as fast a range.  In
single pass timings, it runs faster.  In multiple passes, range is still
quicker because it only has to create the PyNumbers once.

Being immutable, xrange had the advantage that it could serve as its own
iterator and did not require the extra code needed for list iterators and
dict iterators.


Raymond Hettinger


----- Original Message -----
From: "Oren Tirosh" <oren-py-d@hishome.net>
To: <python-dev@python.org>
Sent: Tuesday, June 04, 2002 4:08 PM
Subject: [Python-Dev] xrange identity crisis


> It seems that the xrange object in the current CVS can't make up its mind
> whether it's an iterator or an iterable:
>
> >>> iterables = ["", (), [], {}, file('/dev/null'), xrange(10)]
> >>> iterators = [iter(x) for x in iterables]
> >>> for x in iterables + iterators:
> ...    print hasattr(x, 'next'), x is iter(x), type(x)
> ...
> False False <type 'str'>
> False False <type 'tuple'>
> False False <type 'list'>
> False False <type 'dict'>
> False False <type 'file'>
> True  False <type 'xrange'>
> True  True  <type 'iterator'>
> True  True  <type 'iterator'>
> True  True  <type 'listiterator'>
> True  True  <type 'dictionary-iterator'>
> True  True  <type 'xreadlines.xreadlines'>
> True  False <type 'xrange'>
>
> Generally, iterables don't have a next() method and return a new object
> each time they are iter()ed. Iterators do have a next() method and return
> themselves on iter(). xrange is a strange hybrid.
>
> In Python 2.2.0/1 xrange behaved just like the other iterables:
> >>> iterables = ["", (), [], {}, file('/dev/null'), xrange(10)]
> >>> iterators = [iter(x) for x in iterables]
> >>> for x in iterables + iterators:
> ...    print hasattr(x, 'next'), x is iter(x), type(x)
> ...
> 0 0 <type 'str'>
> 0 0 <type 'tuple'>
> 0 0 <type 'list'>
> 0 0 <type 'dict'>
> 0 0 <type 'file'>
> 0 0 <type 'xrange'>
> 1 1 <type 'iterator'>
> 1 1 <type 'iterator'>
> 1 1 <type 'iterator'>
> 1 1 <type 'dictionary-iterator'>
> 1 1 <type 'xreadlines.xreadlines'>
> 1 1 <type 'iterator'>
>
> What's the rationale behind this change?
>
> Oren
>
>
> _______________________________________________
> Python-Dev mailing list
> Python-Dev@python.org
> http://mail.python.org/mailman/listinfo/python-dev
>