在 Python 脚本中,我遇到了一个在 with
语句内定义的变量,但在语句外使用了该变量,例如以下示例中的 file
:
with open(fname, 'r') as file:
pass
print(file.mode)
凭直觉,我会说 file
不应该存在于 with
语句之外,这只是偶然发生的。不过,我无法在 Python 文档中找到关于这是否可行的结论性声明。这种类型的语句是否可以安全使用(也适用于 future 的 python 版本),还是应该避免使用?在 Python 文档中指向此信息的指针也会非常有帮助。
最佳答案
变量范围仅适用于函数
、模块
和类
级别。如果您在同一个函数/模块/类中,则定义的所有变量都将在该函数/模块/类中可用,无论它是否在 with
、for
、if
等 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
关于python - 在 with 语句外使用 python 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44437694/