Debian Codegraph @

lib-python/3/copyreg.py

raw symbols SCIP
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 # The constructor_ob function is a vestige of safe for unpickling.
18 # There is no reason for the caller to pass it anymore.
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 # Example: provide pickling support for complex numbers.
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 # Support for pickling new-style objects
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 # Python code for object.__reduce_ex__ for protocols 0 and 1
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 # XXX PyPy: the following new code cannot work on PyPy. removing it
68 # breaks a single test, test_newobj_overridden_new in pickletester.py
69 # (as opposed to breaking all of pickling), comment it out until we
70 # find an actual solution
71 #new = base.__new__
72 #if isinstance(new, _new_type) and new.__self__ is base:
73 # break
74 else:
75 base = object # not really reachable
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 # Helper for __reduce_ex__ protocol 2
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 # Get the value from a cache in the class if possible
129 names = cls.__dict__.get("__slotnames__")
130 if names is not None:
131 return names
132
133 # Not cached -- calculate the value
134 names = []
135 if not hasattr(cls, "__slots__"):
136 # This class has no slots
137 pass
138 else:
139 # Slots found -- gather slot names from all base classes
140 for c in cls.__mro__:
141 if "__slots__" in c.__dict__:
142 slots = c.__dict__['__slots__']
143 # if class has a single slot, it can be given as a string
144 if isinstance(slots, str):
145 slots = (slots,)
146 for name in slots:
147 # special descriptors
148 if name in ("__dict__", "__weakref__"):
149 continue
150 # mangled names
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 # Cache the outcome in the class if at all possible
161 try:
162 cls.__slotnames__ = names
163 except:
164 pass # But don't die if we can't
165
166 return names
167
168 # A registry of extension codes. This is an ad-hoc compression
169 # mechanism. Whenever a global reference to <module>, <name> is about
170 # to be pickled, the (<module>, <name>) tuple is looked up here to see
171 # if it is a registered extension code for it. Extension codes are
172 # universal, so that the meaning of a pickle does not depend on
173 # context. (There are also some codes reserved for local use that
174 # don't have this restriction.) Codes are positive ints; 0 is
175 # reserved.
176
177 _extension_registry = {} # key -> code
178 _inverted_registry = {} # code -> key
179 _extension_cache = {} # code -> object
180 # Don't ever rebind those names: pickling grabs a reference to them when
181 # it's initialized, and won't see a rebinding.
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 # Redundant registrations are benign
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 # Standard extension code assignments
217
218 # Reserved ranges
219
220 # First Last Count Purpose
221 # 1 127 127 Reserved for Python standard library
222 # 128 191 64 Reserved for Zope
223 # 192 239 48 Reserved for 3rd parties
224 # 240 255 16 Reserved for private use (will never be assigned)
225 # 256 Inf Inf Reserved for future assignment
226
227 # Extension codes are assigned by the Python Software Foundation.
228
229 # PYPY: Used in tests. We hide it here so it can be imported in the
230 # untranslated tests and found as copyreg.K
231 # Hashable immutable key object containing unheshable mutable data.
232 class K:
233 def __init__(self, value):
234 self.value = value
235
236 def __reduce__(self):
237 # Shouldn't support the recursion itself
238 return K, (self.value,)
239
240