Is this the correct method for sorting instances? If so, why is it not in Python 3?

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?

+5
source share
2 answers

python 3.5.0, . . , , , --: -)

import pickle
import sys

class Foo:

    @staticmethod
    def my_func():
        return 'Foo.my_func'


class Bar:
    pass

if __name__ == '__main__':
    if len(sys.argv) > 1 and sys.argv[1] == 'restore':
        print('loading pickle')
        with open('test.pickle', 'rb') as fp:
            restored = pickle.load(fp)
            print(restored.baz())
    else:
        print('saving pickle')
        b = Bar()
        b.baz = Foo.my_func

        with open('test.pickle', 'w+b') as fp:
            p = pickle.dump(b, fp)

(test) ~/test $python test.py

(test) ~/test $python test.py restore

Foo.my_func

0

( ), dill...

>>> import dill
>>> 
>>> class Foo:
...   def bar(self, x):
...     return self.y + x
...   def zap(self, y):
...     self.y = y
...   y = 1
... 
>>> f = Foo()
>>> f.zap(4)
>>> f.monty = 'python'
>>> 
>>> _f = dill.dumps(f)
>>> del Foo
>>> del f
>>> f = dill.loads(_f)
>>> f.monty
'python'
>>> f.y
4
>>> 
>>> _b = dill.dumps(f.bar)
>>> del f
>>> bar = dill.loads(_b)
>>> bar(4)
8
>>> 

dill , , ... , python . dill , . , , dill: https://github.com/uqfoundation/dill

. : fooobar.com/questions/22713/...

0

All Articles