[英]NameError: global name is not defined in genexpr in python
This: 这个:
import os
class A(object):
os_sep = os.sep
_silentSkipsStart = {u'a dir%s' % os_sep}
def _refreshBasic(self,os_sep=os_sep, skips_start=tuple(
x.replace(os_sep, u'') for x in _silentSkipsStart)):
pass
Fails with: 失败:
Traceback (most recent call last):
File "C:/Users/MrD/.PyCharm50/config/scratches/scratch", line 3, in <module>
class A(object):
File "C:/Users/MrD/.PyCharm50/config/scratches/scratch", line 9, in A
x.replace(os_sep, u'') for x in _silentSkipsStart)):
File "C:/Users/MrD/.PyCharm50/config/scratches/scratch", line 9, in <genexpr>
x.replace(os_sep, u'') for x in _silentSkipsStart)):
NameError: global name 'os_sep' is not defined
I guess that bringing os_sep = os.sep
to global scope should cure that (and I probably should from a design point of view) - but here I am not getting python scoping rules: why is os_sep
resolved alright in the other cases and not in genexpr
? 我猜想将
os_sep = os.sep
引入全局范围应该可以解决这一问题(从设计的角度来看,我应该可以解决)-但在这里我没有得到python范围规则:为什么在其他情况下os_sep
可以os_sep
解决而在genexpr
?
Well as explained to the answer linked in the comments by @PadraicCunningham: 正如@PadraicCunningham的评论中链接的答案所解释的那样:
The scope of names defined in a class block is limited to the class block;
在类块中定义的名称范围仅限于该类块。 it does not extend to the code blocks of methods – this includes comprehensions and generator expressions since they are implemented using a function scope
它没有扩展到方法的代码块–这包括理解和生成器表达式,因为它们是使用函数范围实现的
That is for python 3 - for python 2 list comprehensions would work - but the comprehension variable would leak into class scope - so this would leak x: 那是针对python 3的-对于python 2 列表的理解是可行的 -但comprehension变量将泄漏到类范围内-因此这将泄漏x:
def _refreshBasic(self,os_sep=os_sep, skips_start=tuple(
[x.replace(os_sep, u'') for x in _silentSkipsStart])):
pass
So I went with: 所以我去了:
import os
os_sep = os.sep
class A(object):
_silentSkipsStart = {u'a dir%s' % os_sep}
def _refreshBasic(self,os_sep=os_sep, skips_start=tuple(
x.replace(os_sep, u'') for x in _silentSkipsStart)):
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.