问题
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
?
回答1:
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
来源:https://stackoverflow.com/questions/22086804/six-moves-builtins-range-is-not-consistent-in-python-2-and-python-3