考虑这个函数:
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' ...>
出于某种原因,}作为检查符号的任何绑定操作是否发生在范围内(或注释,在此阶段与注释赋值集中在一起):
symtable
defines{而不是检查符号是否实际是本地的
我不知道为什么。这可能是个bug。我认为这样的模块没有多大用处-it took over a year在任何人之前noticed添加
//
操作符会破坏旧的parser
模块,因此我可以很容易地看到这一点相关问题 更多 >
编程相关推荐