块内的变量在块外仍然可见吗?

时间:2019-01-13 13:38:29

标签: python

我是python的新手,突然惊讶地发现变量在声明和分配的块外仍然可见。代码如下:

with open('data.txt', 'r') as file:
    text = file.readlines()
    # and when do I close the file?

for i in range(len(text)):  # still can access the text even after the block.
    print(text[i])

如何从块外部看到变量? 预先感谢。

1 个答案:

答案 0 :(得分:1)

Python没有块作用域,它具有函数作用域以保持清晰度,但它不对函数进行任何作用域。

使用块隐式调用__enter____exit__方法,并在离开它们时将关闭文件,但是在这种情况下,您正在访问text变量,该变量包含行列表不是文件。

如果未输入该块并且您引用了尚不存在的变量,则会发生此类代码的真正问题。

x = False
if x:
    y = True
if y:   # NameError: name 'y' is not defined
    print ('yay')

x = False
y = False
if x:
    y = True
if y:   # all good
    print ('yay')