gpt4 book ai didi

python - 为什么 pdb 为列表理解的 "if"子句中引用的变量提供 NameError?

转载 作者:行者123 更新时间:2023-12-03 23:06:33 28 4
gpt4 key购买 nike

为什么会这样 NameError发生?

(为了便于阅读,插入提示前的空白行。)

$ python3
Python 3.4.10 (default, Oct 4 2019, 19:39:58)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-23)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> import pdb

>>> def blah():
... foo = "ab"
... pdb.set_trace()
...

>>> blah()
--Return--
> <stdin>(3)blah()->None

(Pdb) [bar for bar in "ac" if bar in foo]
*** NameError: name 'foo' is not defined

以下所有工作正常:
(Pdb) foo
'ab'

(Pdb) [bar for bar in foo]
['a', 'b']

(Pdb) [bar for bar in "ac" if bar in "ab"]
['a']


因此,对于 if 中引用的变量,这是一个特别的问题。子句,而不是循环变量本身。

python 3.6.9 (default, Apr 18 2020, 01:56:04) 中也可以看到与上述相同的行为.

但是在 python 2(2.6.6 或 2.7.17)中,使用与上面相同的命令,我得到:
(Pdb) [bar for bar in "ac" if bar in foo]
['a']

最佳答案

List comprehensions in Python3 are evaluated with a separate scope, similar to functions.只有第一个可迭代对象 ( for ... in iterable ) 是从外部注入(inject)的,所有其他名称都绑定(bind)为全局变量或闭包。 However, closures are resolved at compile time – they only work when lexically defined in the outer scope containing a name.
将此与定义“内部”函数进行比较,该函数显示相同的行为:

-> pdb.set_trace()
(Pdb) foo
'ab'
(Pdb) def bar(): return foo
(Pdb) bar()
*** NameError: name 'foo' is not defined
在 PDB session 中,执行范围在 blah 内。 ,但词法范围在外面。这类似于在其父函数内部或外部定义“内部”函数/理解:
# lexically scoped `foo` as closure
def blah():
foo = 3
def bar(): # !!! Define new scope inside blah
print(foo)
bar() # execute bar inside blah

# `foo` not in scope
def bar(): # !!! Define new scope outside blah
print(foo)

def blah():
foo = 3
bar() # execute bar inside blah

6.2.4. Displays for lists, sets and dictionaries

[...]

However, aside from the iterable expression in the leftmost forclause, the comprehension is executed in a separate implicitly nestedscope. This ensures that names assigned to in the target list don’t“leak” into the enclosing scope.

4.2.2. Resolution of names

[...]

When a name is used in a code block, it is resolved using the nearestenclosing scope. The set of all such scopes visible to a code block iscalled the block’s environment.

关于python - 为什么 pdb 为列表理解的 "if"子句中引用的变量提供 NameError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62340886/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com