blob: 356db6f083e39cc671278aaae97cd5d2c2274483 [file] [log] [blame]
Guido van Rossum99603b02007-07-20 00:22:32 +00001"""Helper to provide extensibility for pickle.
Fred Drake78a6a362000-10-11 22:16:45 +00002
3This is only useful to add pickle support for extension types defined in
4C, not for instances of user-defined classes.
5"""
6
Guido van Rossumcf356fd2003-01-31 20:34:07 +00007__all__ = ["pickle", "constructor",
8 "add_extension", "remove_extension", "clear_extension_cache"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +00009
Guido van Rossum47065621997-04-09 17:44:11 +000010dispatch_table = {}
Guido van Rossum47065621997-04-09 17:44:11 +000011
Fred Drake78a6a362000-10-11 22:16:45 +000012def pickle(ob_type, pickle_function, constructor_ob=None):
Florent Xicluna5d1155c2011-10-28 14:45:05 +020013 if not callable(pickle_function):
Fred Drake78a6a362000-10-11 22:16:45 +000014 raise TypeError("reduction functions must be callable")
Guido van Rossum47065621997-04-09 17:44:11 +000015 dispatch_table[ob_type] = pickle_function
16
Jeremy Hyltonf8ecde52003-06-27 16:58:43 +000017 # 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
Guido van Rossum47065621997-04-09 17:44:11 +000022def constructor(object):
Florent Xicluna5d1155c2011-10-28 14:45:05 +020023 if not callable(object):
Fred Drake78a6a362000-10-11 22:16:45 +000024 raise TypeError("constructors must be callable")
Guido van Rossum47065621997-04-09 17:44:11 +000025
Guido van Rossum0dd32e22007-04-11 05:40:58 +000026# Example: provide pickling support for complex numbers.
Guido van Rossum47065621997-04-09 17:44:11 +000027
Guido van Rossum0dd32e22007-04-11 05:40:58 +000028try:
29 complex
30except NameError:
31 pass
32else:
Guido van Rossum72be3061997-05-20 18:03:22 +000033
Guido van Rossum0dd32e22007-04-11 05:40:58 +000034 def pickle_complex(c):
35 return complex, (c.real, c.imag)
36
37 pickle(complex, pickle_complex, complex)
Guido van Rossum3926a632001-09-25 16:25:58 +000038
Miss Islington (bot)0aea99e2021-07-24 12:35:33 -070039def pickle_union(obj):
40 import functools, operator
41 return functools.reduce, (operator.or_, obj.__args__)
42
43pickle(type(int | str), pickle_union)
44
Guido van Rossum298e4212003-02-13 16:30:16 +000045# Support for pickling new-style objects
Guido van Rossum3926a632001-09-25 16:25:58 +000046
Guido van Rossum3926a632001-09-25 16:25:58 +000047def _reconstructor(cls, base, state):
Guido van Rossum298e4212003-02-13 16:30:16 +000048 if base is object:
49 obj = object.__new__(cls)
50 else:
51 obj = base.__new__(cls, state)
Guido van Rossumd8faa362007-04-27 19:54:29 +000052 if base.__init__ != object.__init__:
53 base.__init__(obj, state)
Guido van Rossum3926a632001-09-25 16:25:58 +000054 return obj
Guido van Rossum3926a632001-09-25 16:25:58 +000055
56_HEAPTYPE = 1<<9
Serhiy Storchaka8cd1dba2020-10-24 21:14:23 +030057_new_type = type(int.__new__)
Guido van Rossum3926a632001-09-25 16:25:58 +000058
Guido van Rossumbe532422003-02-21 22:20:31 +000059# Python code for object.__reduce_ex__ for protocols 0 and 1
60
61def _reduce_ex(self, proto):
62 assert proto < 2
Serhiy Storchaka0353b4e2018-10-31 02:28:07 +020063 cls = self.__class__
64 for base in cls.__mro__:
Guido van Rossum00fb0c92001-11-24 21:04:31 +000065 if hasattr(base, '__flags__') and not base.__flags__ & _HEAPTYPE:
Guido van Rossum3926a632001-09-25 16:25:58 +000066 break
Serhiy Storchaka8cd1dba2020-10-24 21:14:23 +030067 new = base.__new__
68 if isinstance(new, _new_type) and new.__self__ is base:
69 break
Guido van Rossum3926a632001-09-25 16:25:58 +000070 else:
71 base = object # not really reachable
72 if base is object:
73 state = None
74 else:
Serhiy Storchaka0353b4e2018-10-31 02:28:07 +020075 if base is cls:
76 raise TypeError(f"cannot pickle {cls.__name__!r} object")
Guido van Rossum3926a632001-09-25 16:25:58 +000077 state = base(self)
Serhiy Storchaka0353b4e2018-10-31 02:28:07 +020078 args = (cls, base, state)
Guido van Rossum6cef6d52001-09-28 18:13:29 +000079 try:
Guido van Rossum00fb0c92001-11-24 21:04:31 +000080 getstate = self.__getstate__
Guido van Rossum6cef6d52001-09-28 18:13:29 +000081 except AttributeError:
Guido van Rossum3f50cdc2003-02-10 21:31:27 +000082 if getattr(self, "__slots__", None):
Serhiy Storchaka0353b4e2018-10-31 02:28:07 +020083 raise TypeError(f"cannot pickle {cls.__name__!r} object: "
84 f"a class that defines __slots__ without "
85 f"defining __getstate__ cannot be pickled "
86 f"with protocol {proto}") from None
Guido van Rossum00fb0c92001-11-24 21:04:31 +000087 try:
88 dict = self.__dict__
89 except AttributeError:
90 dict = None
91 else:
92 dict = getstate()
Guido van Rossum6cef6d52001-09-28 18:13:29 +000093 if dict:
94 return _reconstructor, args, dict
95 else:
96 return _reconstructor, args
Guido van Rossum255f3ee2003-01-29 06:14:11 +000097
Guido van Rossumbe532422003-02-21 22:20:31 +000098# Helper for __reduce_ex__ protocol 2
Guido van Rossum5aac4e62003-02-06 22:57:00 +000099
100def __newobj__(cls, *args):
101 return cls.__new__(cls, *args)
102
Antoine Pitrouc9dc4a22013-11-23 18:59:12 +0100103def __newobj_ex__(cls, args, kwargs):
104 """Used by pickle protocol 4, instead of __newobj__ to allow classes with
105 keyword-only arguments to be pickled correctly.
106 """
107 return cls.__new__(cls, *args, **kwargs)
108
Guido van Rossum5aac4e62003-02-06 22:57:00 +0000109def _slotnames(cls):
110 """Return a list of slot names for a given class.
111
112 This needs to find slots defined by the class and its bases, so we
113 can't simply return the __slots__ attribute. We must walk down
114 the Method Resolution Order and concatenate the __slots__ of each
115 class found there. (This assumes classes don't modify their
116 __slots__ attribute to misrepresent their slots after the class is
117 defined.)
118 """
119
120 # Get the value from a cache in the class if possible
121 names = cls.__dict__.get("__slotnames__")
122 if names is not None:
123 return names
124
125 # Not cached -- calculate the value
126 names = []
127 if not hasattr(cls, "__slots__"):
128 # This class has no slots
129 pass
130 else:
131 # Slots found -- gather slot names from all base classes
132 for c in cls.__mro__:
133 if "__slots__" in c.__dict__:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000134 slots = c.__dict__['__slots__']
135 # if class has a single slot, it can be given as a string
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000136 if isinstance(slots, str):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000137 slots = (slots,)
138 for name in slots:
139 # special descriptors
140 if name in ("__dict__", "__weakref__"):
141 continue
142 # mangled names
143 elif name.startswith('__') and not name.endswith('__'):
Shane Harveyc4c98662017-08-04 01:45:00 -0700144 stripped = c.__name__.lstrip('_')
145 if stripped:
146 names.append('_%s%s' % (stripped, name))
147 else:
148 names.append(name)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000149 else:
150 names.append(name)
Guido van Rossum5aac4e62003-02-06 22:57:00 +0000151
152 # Cache the outcome in the class if at all possible
153 try:
154 cls.__slotnames__ = names
155 except:
156 pass # But don't die if we can't
157
158 return names
159
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000160# A registry of extension codes. This is an ad-hoc compression
161# mechanism. Whenever a global reference to <module>, <name> is about
162# to be pickled, the (<module>, <name>) tuple is looked up here to see
163# if it is a registered extension code for it. Extension codes are
164# universal, so that the meaning of a pickle does not depend on
165# context. (There are also some codes reserved for local use that
166# don't have this restriction.) Codes are positive ints; 0 is
167# reserved.
168
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000169_extension_registry = {} # key -> code
170_inverted_registry = {} # code -> key
171_extension_cache = {} # code -> object
Guido van Rossum99603b02007-07-20 00:22:32 +0000172# Don't ever rebind those names: pickling grabs a reference to them when
Tim Peters5b7da392003-02-04 00:21:07 +0000173# it's initialized, and won't see a rebinding.
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000174
175def add_extension(module, name, code):
176 """Register an extension code."""
177 code = int(code)
Tim Peters2d629652003-02-04 05:06:17 +0000178 if not 1 <= code <= 0x7fffffff:
Collin Winterce36ad82007-08-30 01:19:48 +0000179 raise ValueError("code out of range")
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000180 key = (module, name)
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000181 if (_extension_registry.get(key) == code and
182 _inverted_registry.get(code) == key):
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000183 return # Redundant registrations are benign
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000184 if key in _extension_registry:
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000185 raise ValueError("key %s is already registered with code %s" %
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000186 (key, _extension_registry[key]))
187 if code in _inverted_registry:
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000188 raise ValueError("code %s is already in use for key %s" %
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000189 (code, _inverted_registry[code]))
190 _extension_registry[key] = code
191 _inverted_registry[code] = key
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000192
193def remove_extension(module, name, code):
194 """Unregister an extension code. For testing only."""
195 key = (module, name)
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000196 if (_extension_registry.get(key) != code or
197 _inverted_registry.get(code) != key):
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000198 raise ValueError("key %s is not registered with code %s" %
199 (key, code))
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000200 del _extension_registry[key]
201 del _inverted_registry[code]
202 if code in _extension_cache:
203 del _extension_cache[code]
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000204
205def clear_extension_cache():
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000206 _extension_cache.clear()
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000207
208# Standard extension code assignments
209
210# Reserved ranges
211
212# First Last Count Purpose
213# 1 127 127 Reserved for Python standard library
Guido van Rossumcef9db62003-02-07 20:56:38 +0000214# 128 191 64 Reserved for Zope
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000215# 192 239 48 Reserved for 3rd parties
216# 240 255 16 Reserved for private use (will never be assigned)
217# 256 Inf Inf Reserved for future assignment
218
219# Extension codes are assigned by the Python Software Foundation.