Writing func_closure?
Fernando Perez
fperez.net at gmail.com
Wed Jun 8 11:31:11 EDT 2005
Michael Hoffman wrote:
> 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?
Oh, I was just trying to play a little trick inside a tight loop where I would
modify on the fly the function's closure to change a parameter. I can do it in
a million ways, but at creation time, the closure approach provides the
cleanest syntax. But at runtime, I have an algorithm that needs to modify
certain parameters many times, and the least-expensive way would be to be able
to write directly into the closure.
> 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
Ah, the docs have improved. I'm using 2.3.4, and the same page:
http://www.python.org/doc/2.3.4/ref/types.html
only says:
Of these, func_code, func_defaults, func_doc/__doc__, and func_dict/__dict__ may
be writable; the others can never be changed.
That's what led me to believe it could be done. Thanks for pointing me to the
2.4 docs, which are much less ambiguous.
> 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:
Yes, I knew of the new.function() approach, but the problem is that I don't know
how to make a fresh closure for it. I can reuse the closure from a different
function, but the docs don't say how to make a valid closure tuple. This is
the typical problem of the stdlib docs, which under-specify what is supposed to
go into a call and don't give at least a specific example.
Many thanks though, I'll probably end up using a less dirty hack :)
Cheers,
f
More information about the Python-list
mailing list