python符号可以在同一范围内是全局和局部的

2024-04-24 11:39:37 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑这个函数:

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' ...>

Tags: path函数inislocaldef符号function
1条回答
网友
1楼 · 发布于 2024-04-24 11:39:37

出于某种原因,symtabledefines{}作为检查符号的任何绑定操作是否发生在范围内(或注释,在此阶段与注释赋值集中在一起):

def is_local(self):
    return bool(self.__flags & DEF_BOUND)

而不是检查符号是否实际是本地的

def is_local(self):
    return bool(self.__scope in (LOCAL, CELL))

我不知道为什么。这可能是个bug。我认为这样的模块没有多大用处-it took over a year在任何人之前noticed添加//操作符会破坏旧的parser模块,因此我可以很容易地看到这一点

相关问题 更多 >