free variables /cell objects question

gangesmaster tomerfiliba at gmail.com
Tue Jan 23 12:45:31 CET 2007


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? 


-tomer




More information about the Python-list mailing list