[Python-ideas] make __closure__ writable

Mark Shannon mark at hotpy.org
Fri Mar 16 20:24:32 CET 2012


Yury Selivanov wrote:
> On 2012-03-16, at 2:57 PM, Yury Selivanov wrote:
> 
>> Decorators can be nested, and what you can do in this case is to
>> find the most inner-wrapped function by traversing the '__wrapped__'
>> attributes (and check that the function you found is the actual
>> original function).  After that you can play with its attributes,
>> but you can't simply substitute the function object, as the inner
>> decorator won't use it.  So sometimes you have to work with the
>> function object without a way of substituting it.
> 
> And that applies to the situations where decorators are not enough
> and you have to work on the opcode level.

Which you can do with a decorator.

Would this do what you want?

def f_with_new_closure(f, closure):
     return types.FunctionType(f.__code__,
                               f.__globals__,
                               f.__name__,
                               f.__defaults__,
                               closure)


Cheers,
Mark.




More information about the Python-ideas mailing list