gpt4 book ai didi

python - 即使在理解范围之后,列表理解也会重新绑定(bind)名称。这是正确的吗?

转载 作者:IT老高 更新时间:2023-10-28 21:05:48 25 4
gpt4 key购买 nike

理解显示与范围界定不同寻常的交互。这是预期的行为吗?

x = "original value"
squares = [x**2 for x in range(5)]
print(x) # Prints 4 in Python 2!

冒着提示的风险,这是一个残酷的错误来源。当我编写新代码时,我只是偶尔会发现由于重新绑定(bind)而出现的非常奇怪的错误——即使现在我知道这是一个问题。我需要制定一个规则,比如“总是在列表推导中用下划线开头临时变量”,但即使这样也不是万无一失的。有这种随机定时炸弹等待的事实否定了列表推导的所有“易用性”。

最佳答案

列表推导在 Python 2 中泄漏了循环控制变量,但在 Python 3 中没有。这里是 Guido van Rossum(Python 的创建者)explaining这背后的历史:

We also made another change in Python 3, to improve equivalence between list comprehensions and generator expressions. In Python 2, the list comprehension "leaks" the loop control variable into the surrounding scope:

x = 'before'
a = [x for x in 1, 2, 3]
print x # this prints '3', not 'before'

This was an artifact of the original implementation of list comprehensions; it was one of Python's "dirty little secrets" for years. It started out as an intentional compromise to make list comprehensions blindingly fast, and while it was not a common pitfall for beginners, it definitely stung people occasionally. For generator expressions we could not do this. Generator expressions are implemented using generators, whose execution requires a separate execution frame. Thus, generator expressions (especially if they iterate over a short sequence) were less efficient than list comprehensions.

However, in Python 3, we decided to fix the "dirty little secret" of list comprehensions by using the same implementation strategy as for generator expressions. Thus, in Python 3, the above example (after modification to use print(x) :-) will print 'before', proving that the 'x' in the list comprehension temporarily shadows but does not override the 'x' in the surrounding scope.

关于python - 即使在理解范围之后,列表理解也会重新绑定(bind)名称。这是正确的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4198906/

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