Question

For a very large integer range, xrange (Python 2) should be used, which is renamed to range in Python 3. I assumed module six can provide a consistent why of writing.

But I found six.moves.builtins.range returns a list in Python 2 and an iterable non-list object in Python 3, just as the name range does.

Also, six.moves.builtins.xrange does not exist in Python 2.

Was I using the wrong function in six? Or does six simply not provide a solution for the range and xrange functions?

I know I can test sys.version[0] and rename the function accordingly. I was just looking for a "Don't Repeat Yourself" solution.

APPEND

As mentioned by mgilson:

>>> import six 
>>> six.moves.range
AttributeError: '_MovedItems' object has no attribute 'range'

Is it something related to the version of six, or is there no such thing as six.moves.range?

Was it helpful?

Solution

I believe you just want six.moves.range. Not, six.moves.builtins.range.

>>> # tested on python2.x..
>>> import six.moves as sm
>>> sm.range
<type 'xrange'>

The reason here is that six.moves.builtins is the version agnostic "builtins" module. That just gives you access to the builtins -- it doesn't actually change what any of the builtins are.

Typically, I don't feel the need to introduce the external dependency in cases like this. I usually just add something like this to the top of my source file:

try:
    xrange
except NameError:  # python3
    xrange = range
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top