Writing func_closure?

Fernando Perez fperez.net at gmail.com
Wed Jun 8 03:47:13 EDT 2005


Hi all,

by reading through the docs, the func_closure attribute of function objects is
listed as writable.  Yet, nowhere does it say _how_ to write to it.  I am
trying to do a run-time modification of a function's closure, where I want to
modify the value of one of the variables in the closure.  But the closure
appears as a tuple of 'cell' objects:

In [21]: def wrap(x):
   ....:     def f(y):
   ....:         return x+y
   ....:     return f
   ....:

In [22]: f1=wrap('hello')

In [23]: f1.func_closure
Out[23]: (<cell at 0x4168bcd4: str object at 0x41bc0080>,)

My question is, how can I create one of these cell objects to stuff into the
closure (I want to do this from pure Python, not C extensions).

The docs mention this as 'possible', but don't provide a single example (though
they don't really specify if it can be done in python or only in C).  The 'new'
module is equally useless, since new.function() comes without any examples:

In [25]: new.function?
Type:           type
Base Class:     <type 'type'>
String Form:    <type 'function'>
Namespace:      Interactive
Docstring:
    function(code, globals[, name[, argdefs[, closure]]])

    Create a function object from a code object and a dictionary.
    The optional name string overrides the name from the code object.
    The optional argdefs tuple specifies the default argument values.
    The optional closure tuple supplies the bindings for free variables.

See that last line?  Nowhere does it say what how the closure tuple is supposed
to be constructed.  I tried a bunch of things, and none of my shot-in-the-dark
attempts got me anywhere.

Any help on this would be much appreciated.

Best,

f




More information about the Python-list mailing list