[Python-Dev] xrange identity crisis

Oren Tirosh oren-py-d@hishome.net
Wed, 5 Jun 2002 00:42:52 +0300


On Tue, Jun 04, 2002 at 04:01:24PM -0500, Jeff Epler wrote:
> On Tue, Jun 04, 2002 at 04:08:08PM -0400, Oren Tirosh wrote:
> > It seems that the xrange object in the current CVS can't make up its mind 
> > whether it's an iterator or an iterable:
> 
> In 2.2, xrange had no "next" method, so it got wrapped by a generic
> iterator object.  It was desirable for performance to have xrange also
> act as an iterator.

I understand the performance issue. But it is possible to improve the 
performance of iterating over xranges without creating this unholy chimera.

>>> type([]), type(iter([]))
(<type 'list'>, <type 'listiterator'>)

   ... lists have a listiterator

>>> type({}), type(iter({}))
(<type 'dict'>, <type 'dictionary-iterator'>)

   ... dictionaries have a dictionary-iterator

>>> type(xrange(10)), type(iter(xrange(10)))
(<type 'xrange'>, <type 'xrange'>)

   ... why shouldn't an xrange have an xrangeiterator? 

It's the only way to make xrange behave consistently with other iterables.  
 
> However, the following code would give different results if 'iter(x)
> is x' for xrange objects:
>     x = xrange(5)
>     for a in x:
> 	for b in x:
> 	    print a,b

xrange currently is currently stuck halfway between an iterable and an 
iterator.  If it was made 100% iterator you would be right, it would
break this code.  What I'm saying is that it should be 100% iterable.

I know it works just fine the way it is.  But I see a lot of confusion on 
the python list around the semantics of iterators and this behavior might 
make it just a little bit worse.

	Oren