cell object dereferencing

Terry Reedy tjreedy at udel.edu
Wed Dec 10 10:38:35 EST 2003


"Jan Decaluwe" <jan at jandecaluwe.com> wrote in message
news:3FD6EA60.2000905 at jandecaluwe.com...
> Jan Decaluwe wrote:
> > Is there a way to dereference a cell object (that is, get
> > the object that it references to) in Python?
>
> I got the following response from Samuele Pedroni.:

> well you can ... use this hack (it's a huge hack but it is safe and does
the trick):

> def proto_acc(v=None):
>   def acc():
>     return v
>   return acc
> acc0 = proto_acc()

> import new
> make_acc = lambda cell: (new.function
(acc0.func_code,acc0.func_globals,'#cell_acc',acc0.func_defaults,(cell,)))
> def cell_deref(cell):
>   return make_acc(cell)()

Cute, Samuele.  If function.func_closure were writable (which it is not)
then I believe the last four lines could be condensed as the more readable

def cell_deref(cell):
    acc0.func_closure = (cell,)
    return acc0()

but since it is not, you instead make a new function that is a near copy of
acc0 but with (cell,) substituted as *its* func_closure.

Terry J. Reedy






More information about the Python-list mailing list