Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

six.moves.builtins.range is not consistent in Python 2 and Python 3

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?

like image 697
Frozen Flame Avatar asked Dec 11 '22 07:12

Frozen Flame


1 Answers

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
like image 156
mgilson Avatar answered Apr 28 '23 12:04

mgilson