| 1 |
"""Helper to provide extensibility for pickle. |
| 2 |
|
| 3 |
This is only useful to add pickle support for extension types defined in |
| 4 |
C, not for instances of user-defined classes. |
| 5 |
""" |
| 6 |
|
| 7 |
__all__ = ["pickle", "constructor", |
| 8 |
"add_extension", "remove_extension", "clear_extension_cache"] |
| 9 |
|
| 10 |
dispatch_table = {} |
| 11 |
|
| 12 |
def pickle(ob_type, pickle_function, constructor_ob=None): |
| 13 |
if not callable(pickle_function): |
| 14 |
raise TypeError("reduction functions must be callable") |
| 15 |
dispatch_table[ob_type] = pickle_function |
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
if constructor_ob is not None: |
| 20 |
constructor(constructor_ob) |
| 21 |
|
| 22 |
def constructor(object): |
| 23 |
if not callable(object): |
| 24 |
raise TypeError("constructors must be callable") |
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
try: |
| 29 |
complex |
| 30 |
except NameError: |
| 31 |
pass |
| 32 |
else: |
| 33 |
|
| 34 |
def pickle_complex(c): |
| 35 |
return complex, (c.real, c.imag) |
| 36 |
|
| 37 |
pickle(complex, pickle_complex, complex) |
| 38 |
|
| 39 |
def pickle_union(obj): |
| 40 |
import functools, operator |
| 41 |
return functools.reduce, (operator.or_, obj.__args__) |
| 42 |
|
| 43 |
pickle(type(int | str), pickle_union) |
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
def _reconstructor(cls, base, state): |
| 48 |
if base is object: |
| 49 |
obj = object.__new__(cls) |
| 50 |
else: |
| 51 |
obj = base.__new__(cls, state) |
| 52 |
if base.__init__ != object.__init__: |
| 53 |
base.__init__(obj, state) |
| 54 |
return obj |
| 55 |
|
| 56 |
_HEAPTYPE = 1<<9 |
| 57 |
_new_type = type(int.__new__) |
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
def _reduce_ex(self, proto): |
| 62 |
assert proto < 2 |
| 63 |
cls = self.__class__ |
| 64 |
for base in cls.__mro__: |
| 65 |
if hasattr(base, '__flags__') and not base.__flags__ & _HEAPTYPE: |
| 66 |
break |
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
else: |
| 75 |
base = object |
| 76 |
if base is object: |
| 77 |
state = None |
| 78 |
else: |
| 79 |
if base is cls: |
| 80 |
raise TypeError(f"cannot pickle {cls.__name__!r} object") |
| 81 |
state = base(self) |
| 82 |
args = (cls, base, state) |
| 83 |
try: |
| 84 |
getstate = self.__getstate__ |
| 85 |
except AttributeError: |
| 86 |
if getattr(self, "__slots__", None): |
| 87 |
raise TypeError(f"cannot pickle {cls.__name__!r} object: " |
| 88 |
f"a class that defines __slots__ without " |
| 89 |
f"defining __getstate__ cannot be pickled " |
| 90 |
f"with protocol {proto}") from None |
| 91 |
try: |
| 92 |
dict = self.__dict__ |
| 93 |
except AttributeError: |
| 94 |
dict = None |
| 95 |
else: |
| 96 |
if (type(self).__getstate__ is object.__getstate__ and |
| 97 |
getattr(self, "__slots__", None)): |
| 98 |
raise TypeError("a class that defines __slots__ without " |
| 99 |
"defining __getstate__ cannot be pickled") |
| 100 |
dict = getstate() |
| 101 |
if dict: |
| 102 |
return _reconstructor, args, dict |
| 103 |
else: |
| 104 |
return _reconstructor, args |
| 105 |
|
| 106 |
|
| 107 |
|
| 108 |
def __newobj__(cls, *args): |
| 109 |
return cls.__new__(cls, *args) |
| 110 |
|
| 111 |
def __newobj_ex__(cls, args, kwargs): |
| 112 |
"""Used by pickle protocol 4, instead of __newobj__ to allow classes with |
| 113 |
keyword-only arguments to be pickled correctly. |
| 114 |
""" |
| 115 |
return cls.__new__(cls, *args, **kwargs) |
| 116 |
|
| 117 |
def _slotnames(cls): |
| 118 |
"""Return a list of slot names for a given class. |
| 119 |
|
| 120 |
This needs to find slots defined by the class and its bases, so we |
| 121 |
can't simply return the __slots__ attribute. We must walk down |
| 122 |
the Method Resolution Order and concatenate the __slots__ of each |
| 123 |
class found there. (This assumes classes don't modify their |
| 124 |
__slots__ attribute to misrepresent their slots after the class is |
| 125 |
defined.) |
| 126 |
""" |
| 127 |
|
| 128 |
|
| 129 |
names = cls.__dict__.get("__slotnames__") |
| 130 |
if names is not None: |
| 131 |
return names |
| 132 |
|
| 133 |
|
| 134 |
names = [] |
| 135 |
if not hasattr(cls, "__slots__"): |
| 136 |
|
| 137 |
pass |
| 138 |
else: |
| 139 |
|
| 140 |
for c in cls.__mro__: |
| 141 |
if "__slots__" in c.__dict__: |
| 142 |
slots = c.__dict__['__slots__'] |
| 143 |
|
| 144 |
if isinstance(slots, str): |
| 145 |
slots = (slots,) |
| 146 |
for name in slots: |
| 147 |
|
| 148 |
if name in ("__dict__", "__weakref__"): |
| 149 |
continue |
| 150 |
|
| 151 |
elif name.startswith('__') and not name.endswith('__'): |
| 152 |
stripped = c.__name__.lstrip('_') |
| 153 |
if stripped: |
| 154 |
names.append('_%s%s' % (stripped, name)) |
| 155 |
else: |
| 156 |
names.append(name) |
| 157 |
else: |
| 158 |
names.append(name) |
| 159 |
|
| 160 |
|
| 161 |
try: |
| 162 |
cls.__slotnames__ = names |
| 163 |
except: |
| 164 |
pass |
| 165 |
|
| 166 |
return names |
| 167 |
|
| 168 |
|
| 169 |
|
| 170 |
|
| 171 |
|
| 172 |
|
| 173 |
|
| 174 |
|
| 175 |
|
| 176 |
|
| 177 |
_extension_registry = {} |
| 178 |
_inverted_registry = {} |
| 179 |
_extension_cache = {} |
| 180 |
|
| 181 |
|
| 182 |
|
| 183 |
def add_extension(module, name, code): |
| 184 |
"""Register an extension code.""" |
| 185 |
code = int(code) |
| 186 |
if not 1 <= code <= 0x7fffffff: |
| 187 |
raise ValueError("code out of range") |
| 188 |
key = (module, name) |
| 189 |
if (_extension_registry.get(key) == code and |
| 190 |
_inverted_registry.get(code) == key): |
| 191 |
return |
| 192 |
if key in _extension_registry: |
| 193 |
raise ValueError("key %s is already registered with code %s" % |
| 194 |
(key, _extension_registry[key])) |
| 195 |
if code in _inverted_registry: |
| 196 |
raise ValueError("code %s is already in use for key %s" % |
| 197 |
(code, _inverted_registry[code])) |
| 198 |
_extension_registry[key] = code |
| 199 |
_inverted_registry[code] = key |
| 200 |
|
| 201 |
def remove_extension(module, name, code): |
| 202 |
"""Unregister an extension code. For testing only.""" |
| 203 |
key = (module, name) |
| 204 |
if (_extension_registry.get(key) != code or |
| 205 |
_inverted_registry.get(code) != key): |
| 206 |
raise ValueError("key %s is not registered with code %s" % |
| 207 |
(key, code)) |
| 208 |
del _extension_registry[key] |
| 209 |
del _inverted_registry[code] |
| 210 |
if code in _extension_cache: |
| 211 |
del _extension_cache[code] |
| 212 |
|
| 213 |
def clear_extension_cache(): |
| 214 |
_extension_cache.clear() |
| 215 |
|
| 216 |
|
| 217 |
|
| 218 |
|
| 219 |
|
| 220 |
|
| 221 |
|
| 222 |
|
| 223 |
|
| 224 |
|
| 225 |
|
| 226 |
|
| 227 |
|
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
|
| 232 |
class K: |
| 233 |
def __init__(self, value): |
| 234 |
self.value = value |
| 235 |
|
| 236 |
def __reduce__(self): |
| 237 |
|
| 238 |
return K, (self.value,) |
| 239 |
|
| 240 |
|