File: pickle.py

package info (click to toggle)
python-kafka 2.0.2-9
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,740 kB
  • sloc: python: 20,457; makefile: 210; sh: 76
file content (35 lines) | stat: -rw-r--r-- 920 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from __future__ import absolute_import

try:
    import copyreg  # pylint: disable=import-error
except ImportError:
    import copy_reg as copyreg  # pylint: disable=import-error

import types


def _pickle_method(method):
    try:
        func_name = method.__func__.__name__
        obj = method.__self__
        cls = method.__self__.__class__
    except AttributeError:
        func_name = method.im_func.__name__
        obj = method.im_self
        cls = method.im_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)

# https://bytes.com/topic/python/answers/552476-why-cant-you-pickle-instancemethods
copyreg.pickle(types.MethodType, _pickle_method, _unpickle_method)