Writing func_closure?

Michael Hoffman cam.ac.uk at mh391.invalid
Wed Jun 8 10:37:26 CEST 2005


Fernando Perez wrote:

 > 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.

Out of curiosity, why?

> 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).

 >>> f1.func_closure[0].__class__()
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
TypeError: cannot create 'cell' instances

Hmmm, that didn't work so well.

 >>> f1.func_closure = f1.func_closure
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
TypeError: readonly attribute

Closer inspection of the docs <http://docs.python.org/ref/types.html> 
reveals that it is not writable after all. Therefore the only way I can 
see to do it without writing an extension is to generate some dummy 
function and copy the func_closure attribute from it. Luckily, you have 
already produced a factory for such a function:

 >>> f1(" there")\
'hello there'
 >>> _f2 = wrap("howdy")
 >>> f1 = new.function(f1.func_code, f1.func_globals, f1.func_name, 
f1.func_defaults, _f2.func_closure)
 >>> f1(" there")
'howdy there'

Mix-and-match functions! What will they think of next?
-- 
Michael Hoffman



More information about the Python-list mailing list