在 with 语句外使用 python 变量

using python variable outside with statement

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

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

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

变量范围仅适用于 functionmoduleclass 级别。如果您在同一个 function/module/class 中,则定义的所有变量都将在该 function/module/class 中可用,无论它是否在 withfor、[=17= 中定义], 等等块.

例如,这个:

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