最近我在浏览CPython源代码,具体来说是在编译过程中查看类的符号表项。
我遇到了typedef struct _symtable_entry
结构的以下条目:
[-- other entries --]
unsigned ste_needs_class_closure : 1; /* for class scopes, true if a
closure over __class__
should be created */
[-- other entries --]
我真的不太理解它,也找不到一个设置 ste_needs_class_closure == 1
的Python代码示例。除了其他失败的尝试之外,我尝试了以下方法:
class foo:
y = 30
def __init__(self):
self.x = 50
def foobar(self):
def barfoo():
print(self.x)
print(y)
return barfoo
尽管代码可以执行,但在执行期间,ste_needs_class_closure
的值为0
而不是我希望的1
。
实际更改此值的函数是drop_class_free
,但这并没有什么帮助。不幸的是,它也没有任何评论来补充说明。
它实际上是在analyze_block
中使用的,并带有以下评论:
/* Check if any local variables must be converted to cell variables */
我可以理解这个概念,但找不到相关的例子。
我尝试搜索了Python 3.4的更新日志,这是该成员首次出现的版本,但没有找到任何相关的参考。
所以,有谁能解释一下闭包覆盖 __class__是什么意思?也就是说,在什么情况下类的局部变量会被转换为单元格变量?理想情况下,一个在执行过程中能够看到这种行为的实际例子将会非常好。