blob: fcef409caba86fe5f5940ac9ba81063ad7a780d3 [file] [log] [blame]
Fred Drake78a6a362000-10-11 22:16:45 +00001"""Helper to provide extensibility for pickle/cPickle.
2
3This is only useful to add pickle support for extension types defined in
4C, not for instances of user-defined classes.
5"""
6
7from types import ClassType as _ClassType
Guido van Rossum72be3061997-05-20 18:03:22 +00008
Guido van Rossumcf356fd2003-01-31 20:34:07 +00009__all__ = ["pickle", "constructor",
10 "add_extension", "remove_extension", "clear_extension_cache"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000011
Guido van Rossum47065621997-04-09 17:44:11 +000012dispatch_table = {}
Guido van Rossum47065621997-04-09 17:44:11 +000013
Fred Drake78a6a362000-10-11 22:16:45 +000014def pickle(ob_type, pickle_function, constructor_ob=None):
15 if type(ob_type) is _ClassType:
16 raise TypeError("copy_reg is not intended for use with classes")
17
18 if not callable(pickle_function):
19 raise TypeError("reduction functions must be callable")
Guido van Rossum47065621997-04-09 17:44:11 +000020 dispatch_table[ob_type] = pickle_function
21
Guido van Rossum72be3061997-05-20 18:03:22 +000022 if constructor_ob is not None:
Guido van Rossum47065621997-04-09 17:44:11 +000023 constructor(constructor_ob)
24
25def constructor(object):
Fred Drake78a6a362000-10-11 22:16:45 +000026 if not callable(object):
27 raise TypeError("constructors must be callable")
Guido van Rossum47065621997-04-09 17:44:11 +000028
Guido van Rossum72be3061997-05-20 18:03:22 +000029# Example: provide pickling support for complex numbers.
Guido van Rossum47065621997-04-09 17:44:11 +000030
Guido van Rossum72be3061997-05-20 18:03:22 +000031def pickle_complex(c):
32 return complex, (c.real, c.imag)
33
34pickle(type(1j), pickle_complex, complex)
Guido van Rossum3926a632001-09-25 16:25:58 +000035
Guido van Rossum298e4212003-02-13 16:30:16 +000036# Support for pickling new-style objects
Guido van Rossum3926a632001-09-25 16:25:58 +000037
Guido van Rossum3926a632001-09-25 16:25:58 +000038def _reconstructor(cls, base, state):
Guido van Rossum298e4212003-02-13 16:30:16 +000039 if base is object:
40 obj = object.__new__(cls)
41 else:
42 obj = base.__new__(cls, state)
43 base.__init__(obj, state)
Guido van Rossum3926a632001-09-25 16:25:58 +000044 return obj
Guido van Rossum3926a632001-09-25 16:25:58 +000045
46_HEAPTYPE = 1<<9
47
48def _reduce(self):
49 for base in self.__class__.__mro__:
Guido van Rossum00fb0c92001-11-24 21:04:31 +000050 if hasattr(base, '__flags__') and not base.__flags__ & _HEAPTYPE:
Guido van Rossum3926a632001-09-25 16:25:58 +000051 break
52 else:
53 base = object # not really reachable
54 if base is object:
55 state = None
56 else:
Guido van Rossum2a6f5b32001-12-27 16:27:28 +000057 if base is self.__class__:
58 raise TypeError, "can't pickle %s objects" % base.__name__
Guido van Rossum3926a632001-09-25 16:25:58 +000059 state = base(self)
Guido van Rossum6cef6d52001-09-28 18:13:29 +000060 args = (self.__class__, base, state)
61 try:
Guido van Rossum00fb0c92001-11-24 21:04:31 +000062 getstate = self.__getstate__
Guido van Rossum6cef6d52001-09-28 18:13:29 +000063 except AttributeError:
Guido van Rossum3f50cdc2003-02-10 21:31:27 +000064 if getattr(self, "__slots__", None):
65 raise TypeError("a class that defines __slots__ without "
66 "defining __getstate__ cannot be pickled")
Guido van Rossum00fb0c92001-11-24 21:04:31 +000067 try:
68 dict = self.__dict__
69 except AttributeError:
70 dict = None
71 else:
72 dict = getstate()
Guido van Rossum6cef6d52001-09-28 18:13:29 +000073 if dict:
74 return _reconstructor, args, dict
75 else:
76 return _reconstructor, args
Guido van Rossum255f3ee2003-01-29 06:14:11 +000077
Guido van Rossum5aac4e62003-02-06 22:57:00 +000078# A better version of _reduce, used by copy and pickle protocol 2
79
80def __newobj__(cls, *args):
81 return cls.__new__(cls, *args)
82
83def _better_reduce(obj):
84 cls = obj.__class__
85 getnewargs = getattr(obj, "__getnewargs__", None)
86 if getnewargs:
87 args = getnewargs()
88 else:
89 args = ()
90 getstate = getattr(obj, "__getstate__", None)
91 if getstate:
Guido van Rossum3f50cdc2003-02-10 21:31:27 +000092 state = getstate()
93 else:
Guido van Rossum5aac4e62003-02-06 22:57:00 +000094 state = getattr(obj, "__dict__", None)
95 names = _slotnames(cls)
96 if names:
97 slots = {}
98 nil = []
99 for name in names:
100 value = getattr(obj, name, nil)
101 if value is not nil:
102 slots[name] = value
103 if slots:
104 state = (state, slots)
105 listitems = dictitems = None
106 if isinstance(obj, list):
107 listitems = iter(obj)
108 elif isinstance(obj, dict):
109 dictitems = obj.iteritems()
110 return __newobj__, (cls,) + args, state, listitems, dictitems
111
Guido van Rossumc53f0092003-02-18 22:05:12 +0000112# Extended reduce:
113
114def _reduce_ex(obj, proto=0):
115 obj_reduce = getattr(obj, "__reduce__", None)
Guido van Rossume6908832003-02-19 01:19:28 +0000116 # XXX This fails in test_copy.py line 61
117 if obj_reduce:
118 try:
119 if obj.__class__.__reduce__ is not object.__reduce__:
120 return obj_reduce()
121 except AttributeError:
122 pass
123 if proto < 2:
Guido van Rossumc53f0092003-02-18 22:05:12 +0000124 return _reduce(obj)
125 else:
126 return _better_reduce(obj)
127
Guido van Rossum5aac4e62003-02-06 22:57:00 +0000128def _slotnames(cls):
129 """Return a list of slot names for a given class.
130
131 This needs to find slots defined by the class and its bases, so we
132 can't simply return the __slots__ attribute. We must walk down
133 the Method Resolution Order and concatenate the __slots__ of each
134 class found there. (This assumes classes don't modify their
135 __slots__ attribute to misrepresent their slots after the class is
136 defined.)
137 """
138
139 # Get the value from a cache in the class if possible
140 names = cls.__dict__.get("__slotnames__")
141 if names is not None:
142 return names
143
144 # Not cached -- calculate the value
145 names = []
146 if not hasattr(cls, "__slots__"):
147 # This class has no slots
148 pass
149 else:
150 # Slots found -- gather slot names from all base classes
151 for c in cls.__mro__:
152 if "__slots__" in c.__dict__:
153 names += [name for name in c.__dict__["__slots__"]
154 if name not in ("__dict__", "__weakref__")]
155
156 # Cache the outcome in the class if at all possible
157 try:
158 cls.__slotnames__ = names
159 except:
160 pass # But don't die if we can't
161
162 return names
163
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000164# A registry of extension codes. This is an ad-hoc compression
165# mechanism. Whenever a global reference to <module>, <name> is about
166# to be pickled, the (<module>, <name>) tuple is looked up here to see
167# if it is a registered extension code for it. Extension codes are
168# universal, so that the meaning of a pickle does not depend on
169# context. (There are also some codes reserved for local use that
170# don't have this restriction.) Codes are positive ints; 0 is
171# reserved.
172
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000173_extension_registry = {} # key -> code
174_inverted_registry = {} # code -> key
175_extension_cache = {} # code -> object
Tim Peters5b7da392003-02-04 00:21:07 +0000176# Don't ever rebind those names: cPickle grabs a reference to them when
177# it's initialized, and won't see a rebinding.
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000178
179def add_extension(module, name, code):
180 """Register an extension code."""
181 code = int(code)
Tim Peters2d629652003-02-04 05:06:17 +0000182 if not 1 <= code <= 0x7fffffff:
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000183 raise ValueError, "code out of range"
184 key = (module, name)
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000185 if (_extension_registry.get(key) == code and
186 _inverted_registry.get(code) == key):
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000187 return # Redundant registrations are benign
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000188 if key in _extension_registry:
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000189 raise ValueError("key %s is already registered with code %s" %
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000190 (key, _extension_registry[key]))
191 if code in _inverted_registry:
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000192 raise ValueError("code %s is already in use for key %s" %
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000193 (code, _inverted_registry[code]))
194 _extension_registry[key] = code
195 _inverted_registry[code] = key
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000196
197def remove_extension(module, name, code):
198 """Unregister an extension code. For testing only."""
199 key = (module, name)
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000200 if (_extension_registry.get(key) != code or
201 _inverted_registry.get(code) != key):
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000202 raise ValueError("key %s is not registered with code %s" %
203 (key, code))
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000204 del _extension_registry[key]
205 del _inverted_registry[code]
206 if code in _extension_cache:
207 del _extension_cache[code]
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000208
209def clear_extension_cache():
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000210 _extension_cache.clear()
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000211
212# Standard extension code assignments
213
214# Reserved ranges
215
216# First Last Count Purpose
217# 1 127 127 Reserved for Python standard library
Guido van Rossumcef9db62003-02-07 20:56:38 +0000218# 128 191 64 Reserved for Zope
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000219# 192 239 48 Reserved for 3rd parties
220# 240 255 16 Reserved for private use (will never be assigned)
221# 256 Inf Inf Reserved for future assignment
222
223# Extension codes are assigned by the Python Software Foundation.