Python __closure__ variables and cells

Studying some of the solutions in my previous question about the inner workings of the Python domain, I learned about the __closure__ attribute. Python seems to use this attribute to access variables defined in the outer scope from within a nested function.

We see this in action by doing the following:

 def foo(): x = 5 def bar(): print(x) print(*(cell.cell_contents for cell in bar.__closure__)) bar() foo() 

Shown here are two private values ​​of 5 and the function bar itself.

I do not understand how this works, since the __closure__ attribute contains only a set of cells in which nested values ​​are stored. But there is no information about the names of nested variables - (i.e. Cells are stored in tuple , not dict ). So how does Python know the names of the variables that were enclosed?

+4
source share
1 answer

Compiled python-based code uses indexes; variables are tied to an index in the cell structure.

 >>> def foo(): ... x = 5 ... def bar(): ... return x ... return bar ... >>> bar = foo() >>> import dis >>> dis.dis(bar) 4 0 LOAD_DEREF 0 (x) 3 RETURN_VALUE 

The LOAD_DEREF confirms the first cell value.

+8
source

Source: https://habr.com/ru/post/1432507/


All Articles