[Python-Dev] xrange vs generators

Tim Peters tim@digicool.com
Mon, 25 Jun 2001 11:39:47 -0400


[Thomas Heller]
> I _was_ using xrange as sets representing (potentially large)
> ranges of ints.
> Example:
>
> positive = xrange(1, sys.maxint)
>
> if num in positive:
>    ...
> I didt follow the iterators discussion: would this
> continue to work?

[Guido]
> No, it would break.

"x in y" works with any iterable y in 2.2, incl. generators.  So e.g.

>>> def xr(n):
...     i = 0
...     while i < n:
...         yield i
...         i += 1
...
>>> 1 in xr(10)
1
>>> 9 in xr(10)
1
>>> 10 in xr(10)
0
>>>

However, there's no __contains__ method here, so in the last case it
actually did 10 compares.  0 in xr(sys.maxint) is very quick, but I'm still
waiting for -1 in xr(sys.maxint) to complete <wink>.

> And I see another breakage too:

This would also apply to Thomas's example of giving a name to an xrange
object, if implemented via generator:

>>> small = xr(5)
>>> 2 in small
1
>>> 2 in small
0
>>>

> ...
> This is too bad; I really wish that xrange() could die or be limited
> entirely to for loops.  I wonder if we could put warnings on xrange()
> uses beyond the most basic...?

Hmm.  I'd rather not endure the resulting complaints without a strong
rationale for deprecating it.  One that strikes close to my heart:  there's
more code in 2.2 to support xrange than there is to support generators!  But
users don't care about that.