I recently switched to the CPython source code, especially looking at the compilation of the symbol table entry for the class.
I came across the following entry for the typedef struct _symtable_entry structure typedef struct _symtable_entry :
[-- other entries --] unsigned ste_needs_class_closure : 1; [-- other entries --]
I really can't figure it out and can't find a python code example that actually sets ste_needs_class_closure == 1 . Among other unsuccessful attempts, I tried the following:
class foo: y = 30 def __init__(self): self.x = 50 def foobar(self): def barfoo(): print(self.x) print(y) return barfoo
But even if it executes, the value of ste_needs_class_closure at runtime is 0 , not 1 , as I hoped it would be.
The function that actually changes this value is drop_class_free , which helps a little. Unfortunately, he also has no comments to supplement him.
It is actually used in analyze_block with a comment:
/* Check if any local variables must be converted to cell variables */
What I can understand as a concept, but I can not find an example where this happens.
I tried to find the change log for Python 3.4 , the version in which this member first appeared, but no links to it were found.
So, can anyone explain what is meant by closure over __class __ , that is, when local class variables are converted to cell variables? Ideally, the example that actually makes this behavior visible at runtime would be great.