free variables /cell objects question
Peter Otten
__peter__ at web.de
Tue Jan 23 07:02:49 EST 2007
gangesmaster wrote:
> why does CPython require to wrap the free variables if
> closure functions by a cell objects?
> why can't it just pass the object itself?
>
>>>> def f(x):
> ... def g():
> ... return x+2
> ... return g
> ...
>>>> g5 = f(5)
>>>> dis(g5)
> 3 0 LOAD_DEREF 0 (x)
> 3 LOAD_CONST 1 (2)
> 6 BINARY_ADD
> 7 RETURN_VALUE
>>>> dis(f)
> 2 0 LOAD_CLOSURE 0 (x)
> 3 BUILD_TUPLE 1
> 6 LOAD_CONST 1 (<code objec...
> 9 MAKE_CLOSURE 0
> 12 STORE_FAST 1 (g)
>
> 4 15 LOAD_FAST 1 (g)
> 18 RETURN_VALUE
>>>>
>
> i don't see why dereferencing is needed. why not just pass
> the object itself to the MAKE_CLOSURE? i.e.
>
> LOAD_FAST 0 (x)
> LOAD_CONST 1 (the code object)
> MAKE_CLOSURE 0
>
> what problem does the cell object solve?
If I understand you correctly:
def f(x):
def g():
return x + 2
x = 42
return g
assert f(0)() == 44
Peter
More information about the Python-list
mailing list