如何在Python的块语句中设置变量的可见性?

huangapple go评论61阅读模式
英文:

how to make variable visibility in block statement in Python?

问题

如何实现以下效果:

# 没有名为 `i` 的变量
for i in range(1):
    pass
print(i)  # 为什么
我不想在 `for` 语句完成后使 `i` 可访问

但我不想手动使用 `del i`。
英文:

How to achieve an effect like :

#there is no variable named `i`
for i in range(1):
    pass
print(i) #why 

I don't want to make i visitable after the for statement finished.

But I don't want to use del i manually.

答案1

得分: 1

这只是Python设计的一部分。for 循环在每次迭代中将值赋给 i,就好像它执行了 i = next(some_iterator) 一样。就像任何其他赋值一样,i 变量将一直存在,直到它被重新绑定到其他内容,或者直到您使用 del i 将其删除。

在Python中,变量(通常情况下)不受限于单个代码块,只有函数(以及由它们构建而成的一些其他语言结构,如推导和生成器表达式)才有自己的作用域。这与其他编程语言不同,其他编程语言具有更广泛的词法作用域形式,其中每个代码块都可以具有自己的作用域。(唯一的例外是异常处理代码,except SomeExeptionType as e,在代码块结束后,e 变量将被删除,以帮助避免异常回溯和堆栈帧之间的引用循环。)

如果您想确保不会泄漏任何变量,将所有代码放入单独的函数中。局部变量永远不会泄漏到其函数之外。

def do_a_loop():
    for i in range(1):
        pass
    # i 仍然在此处定义,但仅在函数体结束之前

do_a_loop()
print(i)  # 这将引发错误,因为 i 未定义为全局变量
英文:

This is just part of Python's design. A for loop assigns to i on each iteration, just as if it did i = next(some_iterator). Just like any other assignment, the i variable persists until it gets rebound to something else, or until you remove it with del i.

Variables in Python are not (usually) limited to a single block, only functions (and a few other language constructs built out of them, like comprehensions and generator expressions) have their own scopes in that way. This is different than other programming languages that have a more expansive form of lexical scoping, where each block can have its own scope. (The one exception is exception handling code, except SomeExeptionType as e, where the e variable gets deleted after the end of the block, to help avoid reference loops between exception tracebacks and stack frames.)

If you want to be sure you don't leak any variables, put all your code into separate functions. Local variables will never leak outside of their function.

def do_a_loop():
    for i in range(1):
        pass
    # i is still defined here, but only until the end of the function body

do_a_loop()
print(i)     # this will raise, as i is not defined as a global variable

huangapple
  • 本文由 发表于 2023年3月1日 13:08:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75599785.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定