NameError:全局名称"xrange"未在Python 3中定义 [英] NameError: global name 'xrange' is not defined in Python 3
问题描述
运行python程序时出现错误:
I am getting an error when running a python program:
Traceback (most recent call last):
File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 110, in <module>
File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 27, in __init__
File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\class\inventory.py", line 17, in __init__
builtins.NameError: global name 'xrange' is not defined
游戏来自此处.
什么原因导致此错误?
推荐答案
您正尝试使用Python 3运行Python 2代码库. range()
在Python 3中.
You are trying to run a Python 2 codebase with Python 3. xrange()
was renamed to range()
in Python 3.
改为使用Python 2运行游戏.除非您知道自己在做什么,否则不要尝试移植它,很有可能除了xrange()
还是range()
之外,还会有更多问题.
Run the game with Python 2 instead. Don't try to port it unless you know what you are doing, most likely there will be more problems beyond xrange()
vs. range()
.
作为记录,您看到的不是语法错误,而是运行时异常.
For the record, what you are seeing is not a syntax error but a runtime exception instead.
如果您确实知道自己在做什么,并且正在积极地使Python 2代码库与Python 3兼容,则可以通过在模块中添加全局名称作为range
的别名来桥接代码. (考虑到您可能 必须用list(range(...))
更新Python 2代码库中任何现有的range()
使用,以确保您仍然在Python 3中获得列表对象):
If you do know what your are doing and are actively making a Python 2 codebase compatible with Python 3, you can bridge the code by adding the global name to your module as an alias for range
. (Take into account that you may have to update any existing range()
use in the Python 2 codebase with list(range(...))
to ensure you still get a list object in Python 3):
try:
# Python 2
xrange
except NameError:
# Python 3, xrange is now named range
xrange = range
# Python 2 code that uses xrange(...) unchanged, and any
# range(...) replaced with list(range(...))
或在代码库中将所有对xrange(...)
的使用替换为range(...)
,然后使用其他填充片使Python 3语法与Python 2兼容:
or replace all uses of xrange(...)
with range(...)
in the codebase and then use a different shim to make the Python 3 syntax compatible with Python 2:
try:
# Python 2 forward compatibility
range = xrange
except NameError:
pass
# Python 2 code transformed from range(...) -> list(range(...)) and
# xrange(...) -> range(...).
从长远来看,对于希望仅与Python 3兼容的代码库而言,后者是更可取的,然后在可能的情况下使用Python 3语法会更容易.
The latter is preferable for codebases that want to aim to be Python 3 compatible only in the long run, it is easier to then just use Python 3 syntax whenever possible.
这篇关于NameError:全局名称"xrange"未在Python 3中定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!