Why can't you pickle instancemethods?

Gabriel Genellina gagsl-py at yahoo.com.ar
Fri Oct 20 18:59:06 EDT 2006


At Friday 20/10/2006 18:33, Chris wrote:

>Why can pickle serialize references to functions, but not methods?

Because all references must be globally accessible.

>Pickling a function serializes the function name, but pickling a
>staticmethod, classmethod, or instancemethod generates an error. In
>these cases, pickle knows the instance or class, and the method, so
>what's the problem? Pickle doesn't serialize code objects, so why can't
>it serialize the name as it does for functions? Is this one of those
>features that's feasible, but not useful, so no one's ever gotten
>around to implementing it?

Well, it's not so common to take a method from one class and glue it 
into an *instance* of another class...
(Note that if you copy&paste a method from one *class* into another 
*class*, pickle works OK, as long as in the unpickling environment 
you rebuild your classes the same way)

For static methods there is no way you can retrieve a globally usable 
name (like 'Functions.somefunc' in your example) - at least I don't 
know how to do it, they appear to have lost any reference to the 
defining class.
For class methods you can build such reference using im_self and 
im_func.func_name
For instance methods use im_class and im_func.func_name
Then define your own __getstate__ and __setstate__.


-- 
Gabriel Genellina
Softlab SRL 

__________________________________________________
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis! 
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar



More information about the Python-list mailing list