0

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>>
12
  • 1
    Have you seen this very similar question?: stackoverflow.com/questions/9470403/pickling-class-method Feb 20, 2015 at 0:24
  • 2
    I'm the dill author. Why stick with pickle when dill can pickle all of your items? Feb 20, 2015 at 3:47
  • 1
    If it is because you want to use multiprocessing, then you can just use my fork of multiprocessing called pathos.multiprocessing. It uses the dill serializer, so you can send any of your items in a map function. For example, see: stackoverflow.com/questions/1816958/… Feb 20, 2015 at 3:48
  • @MikeMcKerns I feel that dill is too big to solve this problem (loading cost + wasted memory) - I can pick some code from dill and use but not want load all since only some function is required - I think that will be 1% of 100%.
    – Chameleon
    Feb 20, 2015 at 8:28
  • @paintedcones I read answer but not found useful - I found some better answers but without solving problem of @staticmethod.
    – Chameleon
    Feb 20, 2015 at 8:34

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.