python - 在 with 语句外使用 python 变量

标签 python with-statement

在 Python 脚本中,我遇到了一个在 with 语句内定义的变量,但在语句外使用了该变量,例如以下示例中的 file:

with open(fname, 'r') as file:
    pass
print(file.mode)

凭直觉,我会说 file 不应该存在于 with 语句之外,这只是偶然发生的。不过,我无法在 Python 文档中找到关于这是否可行的结论性声明。这种类型的语句是否可以安全使用(也适用于 future 的 python 版本),还是应该避免使用?在 Python 文档中指向此信息的指针也会非常有帮助。

最佳答案

变量范围仅适用于函数模块级别。如果您在同一个函数/模块/类中,则定义的所有变量都将在该函数/模块/类中可用,无论它是否在 withforif 等 block 。

例如,这个:

for x in range(1):
    y = 1
print(y)

与使用 with 语句的示例一样有效(尽管毫无意义)。

但是,您必须小心,因为如果从未输入代码块,那么在您的代码块中定义的变量可能实际上并未定义,如本例所示:

try:
    with open('filedoesnotexist', 'r') as file:
        pass
except:
    pass # just to emphasize point

print(file.mode)

Traceback (most recent call last):
  File "<pyshell#43>", line 1, in <module>
    file.mode
NameError: name 'file' is not defined

Good description of LEGB rule of thumb for variable scope

关于python - 在 with 语句外使用 python 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44437694/

相关文章:

python - 如何将列表中的所有元素划分在一起

python - 在 Python 'with' 语句中重用多个上下文

python - 理解上下文管理器类中返回 self 的目的

python - 通过 SWIG 在 python 函数中使用 GList 数据类型

python - lambda 函数闭包捕获了什么?

python - 如何使用 python 3 对文件执行上下文菜单操作

python - 为什么 __getattr__ 不能与 __exit__ 一起使用?

python - 使用 with - python 打开超过 1 个文件

Python条件 "With"锁设计

Python AES解密例程(代码帮助)