How to pickle Python class method types? It is not implemented in standard library. I found that I can use some third party modules like dill
but how to do it with pickle only.
I prepared some test code to make this question simple:
import pickle
class Thing(object):
@staticmethod
def static_method():
print Thing.static_method.__name__
@classmethod
def class_method(cls):
print cls.class_method.__name__
def object_method(self):
print self.object_method.__name__
def main():
items = [Thing,
Thing(),
Thing.static_method,
Thing.class_method,
Thing.object_method,
Thing().object_method]
for i, item in enumerate(items):
try:
pickle.loads(pickle.dumps(item))
except Exception as ex:
print i, ex, item
if __name__ == '__main__':
main()
How to deal with default lack of pickle support for methods in Python 2.7?
2 Can't pickle <function static_method at 0x025614F0>: it's not found as __main__.static_method <function static_method at 0x025614F0>
3 can't pickle instancemethod objects <bound method type.class_method of <class '__main__.Thing'>>
4 can't pickle instancemethod objects <unbound method Thing.object_method>
5 can't pickle instancemethod objects <bound method Thing.object_method of <__main__.Thing object at 0x024F71D0>>