嵌套理解中的NameError [英] NameError in nested comprehensions
问题描述
我在文件中有此代码
class Sudoku(dict):
COLUMNS = [
{(x, y) for y in xrange(9)} for x in xrange(9)
]
当我运行python broken.py
时,我得到了回溯:
When I run python broken.py
, I get the traceback:
Traceback (most recent call last):
File "U:\broken.py", line 1, in <module>
class Sudoku(dict):
File "U:\broken.py", line 3, in Sudoku
{(x, y) for y in xrange(9)} for x in xrange(9)
File "U:\broken.py", line 3, in <setcomp>
{(x, y) for y in xrange(9)} for x in xrange(9)
NameError: global name 'x' is not defined
[Finished in 0.1s with exit code 1]
我真的没有在这里看到问题. x
不是在理解中定义的吗?
I don't really see the problem here. Isn't x
defined in the comprehension?
奇怪的是,当直接粘贴到python解释器中时,它似乎如何执行而没有错误...
What's stranger is how this seems to execute without an error when pasted directly into the python interpreter...
编辑:如果我使用列表推导而不是集合推导,则此方法有效
EDIT: This works if I use a list comprehension rather than a set comprehension
推荐答案
我在此处.在python 2.7.5中,这是仍然被破坏的.
I've filed a bug here. This is still broken by design in python 2.7.5.
来自错误报告:
在Python 2中,列表推导式没有自己的作用域,因此初始示例中的
x
位于类作用域内.但是,集合理解确实具有其自身的范围.根据设计,在类范围内定义的变量对该类内部的内部范围不可见.
In Python 2, list comprehensions don't have their own scope, so the
x
in your initial example lives at class scope. However, the set comprehension does have its own scope. By design, a variable defined at class scope is not visible to inner scopes inside that class.
在Python 3中,这是有效的,因为列表理解具有其自身的范围.
In Python 3, this works because the list comprehension has its own scope.
这篇关于嵌套理解中的NameError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!