Instance methods cannot be automatically pickled in both Python 2 and Python 3.
I need to parse instance methods with Python 3, and I ported the Stephen Betarad code example to Python 3:
import copyreg
import types
def _pickle_method(method):
func_name = method.__func__.__name__
obj = method.__self__
cls = method.__self__.__class__
return _unpickle_method, (func_name, obj, cls)
def _unpickle_method(func_name, obj, cls):
for cls in cls.mro():
try:
func = cls.__dict__[func_name]
except KeyError:
pass
else:
break
return func.__get__(obj, cls)
copyreg.pickle(types.MethodType, _pickle_method, _unpickle_method)
Is this method a false proof for instance sorting methods? Or can some things go horribly wrong? I tested it with some class layouts and everything seems to work.
If all else fails, why is it impossible to use standard pickle instance methods in Python 3?
source
share