What is xrange?
steve+comp.lang.python at pearwood.info
Sat Jul 30 07:36:41 EDT 2011
Brian Blais wrote:
> On Jul 29, 2011, at 9:22 PM, Steven D'Aprano wrote:
>> Billy Mays wrote:
>>> Is xrange not a generator? I know it doesn't return a tuple or list, so
>>> what exactly is it?
>> xrange pre-dates generators by approximately forever. It returns a
>> special "xrange object", which generates values suitable for use in
>> for-loops using the old __getitem__ protocol.
> interesting...I never really thought about this. Is there a reason that
> it wasn't reimplemented when generators came out? Is there a use-case for
> the current implementation that wouldn't work as a generator?
It certainly couldn't be re-implemented before Python 3, because that would
change the behaviour and therefore break people's code that expected to be
able to treat xrange objects as sequences.
And now that Python 3.2 is out, and 3.3 is being worked on, it can't be
changed now either, for the same reason. There was a very narrow window of
opportunity for the functionality to be changed, and it was missed.
Probably because nobody thought about it, but if it had been proposed to
change xrange into an iterator, I'm pretty confident that the suggestion
would have been rejected. xrange objects might be lazily generated, but
they're also sequence types: you can get their length, and you can index
them. (However you can't slice them.) Iterators are not sequence types:
they aren't indexable and you can't get their length.
So why bother *taking away* functionality from xrange just to make it a less
powerful and more restricted iterator? It works fine just the way it is,
there's no need to change it.
It isn't like the Python developers are sitting around bored, looking for
things to do. They are overworked with far too much to do and not enough
manpower or time to do it. There are a huge number of much more important
bug fixes and features that haven't been dealt with for them to bother with
something like this.
More information about the Python-list