[issue9276] pickle should support methods

Alexander Belopolsky report at bugs.python.org
Mon Aug 2 01:55:18 CEST 2010


Alexander Belopolsky <belopolsky at users.sourceforge.net> added the comment:

Not a proposed solution, but food for thought.  Methods do have __reduce_ex__ method which works with protocol 3:

>>> class X:
...   def f(self):
...      pass

>>> X.f.__reduce_ex__(3)
(<function __newobj__ at 0x100579288>, (<class 'function'>,), {}, None, None)

This result is useless for several reasons:

1.  <class 'function'> cannot be pickled because although it's name suggests a builtin, it is only available as types.FunctionType.

2. If we define builtins.function, X.f can be pickled

>>> import builtins, types
>>> builtins.function = types.FunctionType
>>> pickle.dumps(X.f)
b'\x80\x03cbuiltins\nfunction\nq\x00)\x81q\x01}q\x02b.'

but the result is useless:

>>> pickle.loads(_)
Traceback (most recent call last):
 ..
 File "Lib/pickle.py", line 1317, in loads
    encoding=encoding, errors=errors).load()
TypeError: Required argument 'code' (pos 1) not found


I think the approach of pickling the name of the function as is done in the Twisted link above is the only reasonable one and is consistent with the way module level functions are pickled.

----------
nosy: +belopolsky
versions: +Python 3.2

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue9276>
_______________________________________


More information about the Python-bugs-list mailing list