What are python closures realy like?

Klaas mike.klaas at gmail.com
Wed Dec 6 14:09:20 EST 2006


Michele Simionato wrote:

> I believe decorators are in large part responsible for that. A callable
> object does not work
> as a method unless you define a custom __get__, so in decorator
> programming it is
> often easier to use a closure. OTOH closures a not optimal if you want
> persistency
> (you cannot pickle a closure) so in that case I use a callable object
> instead.

Note that it isn't necessary to write the descriptor yourself.  The
'new' module takes care of it:

In [1]: class A(object):
   ...:     pass
In [2]: a = A()
In [3]: class Method(object):
   ...:     def __call__(mself, oself):
   ...:         print mself, oself
In [4]: import new
In [5]: a.method = new.instancemethod(Method(), a, A)
In [6]: a.method()
<__main__.Method object at 0xb7ab7f6c> <__main__.A object at
0xb7ab79ec>

-Mike




More information about the Python-list mailing list