six.moves.builtins.range在Python 2和Python 3中不一致 [英] six.moves.builtins.range is not consistent in Python 2 and Python 3
问题描述
对于很大的整数范围,应使用xrange
(Python 2),在Python 3中将其重命名为range
.我认为模块six
可以提供一致的编写原因.
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.
但是我发现six.moves.builtins.range
在Python 2中返回一个列表,在Python 3中返回一个可迭代的非列表对象,就像名称range
一样.
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.
此外,six.moves.builtins.xrange
在Python 2中不存在.
Also, six.moves.builtins.xrange
does not exist in Python 2.
我在six
中使用了错误的功能吗?还是六个根本不提供range
和xrange
函数的解决方案?
Was I using the wrong function in six
? Or does six simply not provide a solution for the range
and xrange
functions?
我知道我可以测试sys.version[0]
并相应地重命名该功能.我只是在寻找不要重复自己"的解决方案.
I know I can test sys.version[0]
and rename the function accordingly. I was just looking for a "Don't Repeat Yourself" solution.
如吉尔森所言:
>>> import six
>>> six.moves.range
AttributeError: '_MovedItems' object has no attribute 'range'
是与six
的版本有关的东西,还是没有six.moves.range
这样的东西?
Is it something related to the version of six
, or is there no such thing as six.moves.range
?
推荐答案
我相信您只想要six.moves.range
.不是,six.moves.builtins.range
.
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'>
此处的原因是six.moves.builtins
是与版本无关的内置"模块.这仅使您可以访问内置函数-实际上并不会更改任何内置函数 .
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
这篇关于six.moves.builtins.range在Python 2和Python 3中不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!