【发布时间】:2020-07-17 07:07:17
【问题描述】:
考虑这个函数:
def content(path):
global file # not useful but valid
with open(path) as file:
return file.read()
在生成符号表(使用模块symtable)并在函数content 的范围内检查符号file 时,它同时是全局和局部的。调用此函数后,全局名称file 将绑定到文件对象。所以我想知道为什么函数范围内的符号file也被认为是本地符号?
这里是重现行为的代码(将其放在一个文件中,例如名为global_and_local.py):
import symtable
def content(path):
global file
with open(path) as file:
return file.read()
symtable_root = symtable.symtable(content(__file__), __file__, "exec")
symtable_function = symtable_root.get_children()[0]
symbol_file = symtable_function.lookup('file')
print("symbol 'file' in function scope: is_global() =", symbol_file.is_global())
print("symbol 'file' in function scope: is_local() =", symbol_file.is_local())
print("global scope: file =", file)
生成以下输出:
symbol 'file' in function scope: is_global() = True
symbol 'file' in function scope: is_local() = True
global scope: file = <_io.TextIOWrapper name='global_and_local.py' ...>
【问题讨论】:
标签: python global-variables symbols