blob: 11ae9606112ba53782d4bdd3cc050a14921d25b5 [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
36# Support for picking new-style objects
37
Guido van Rossum3926a632001-09-25 16:25:58 +000038def _reconstructor(cls, base, state):
Guido van Rossum698acf92001-09-25 19:46:05 +000039 obj = base.__new__(cls, state)
40 base.__init__(obj, state)
Guido van Rossum3926a632001-09-25 16:25:58 +000041 return obj
Guido van Rossum3926a632001-09-25 16:25:58 +000042
43_HEAPTYPE = 1<<9
44
45def _reduce(self):
46 for base in self.__class__.__mro__:
Guido van Rossum00fb0c92001-11-24 21:04:31 +000047 if hasattr(base, '__flags__') and not base.__flags__ & _HEAPTYPE:
Guido van Rossum3926a632001-09-25 16:25:58 +000048 break
49 else:
50 base = object # not really reachable
51 if base is object:
52 state = None
53 else:
Guido van Rossum2a6f5b32001-12-27 16:27:28 +000054 if base is self.__class__:
55 raise TypeError, "can't pickle %s objects" % base.__name__
Guido van Rossum3926a632001-09-25 16:25:58 +000056 state = base(self)
Guido van Rossum6cef6d52001-09-28 18:13:29 +000057 args = (self.__class__, base, state)
58 try:
Guido van Rossum00fb0c92001-11-24 21:04:31 +000059 getstate = self.__getstate__
Guido van Rossum6cef6d52001-09-28 18:13:29 +000060 except AttributeError:
Guido van Rossum3f50cdc2003-02-10 21:31:27 +000061 if getattr(self, "__slots__", None):
62 raise TypeError("a class that defines __slots__ without "
63 "defining __getstate__ cannot be pickled")
Guido van Rossum00fb0c92001-11-24 21:04:31 +000064 try:
65 dict = self.__dict__
66 except AttributeError:
67 dict = None
68 else:
69 dict = getstate()
Guido van Rossum6cef6d52001-09-28 18:13:29 +000070 if dict:
71 return _reconstructor, args, dict
72 else:
73 return _reconstructor, args
Guido van Rossum255f3ee2003-01-29 06:14:11 +000074
Guido van Rossum5aac4e62003-02-06 22:57:00 +000075# A better version of _reduce, used by copy and pickle protocol 2
76
77def __newobj__(cls, *args):
78 return cls.__new__(cls, *args)
79
80def _better_reduce(obj):
81 cls = obj.__class__
82 getnewargs = getattr(obj, "__getnewargs__", None)
83 if getnewargs:
84 args = getnewargs()
85 else:
86 args = ()
87 getstate = getattr(obj, "__getstate__", None)
88 if getstate:
Guido van Rossum3f50cdc2003-02-10 21:31:27 +000089 state = getstate()
90 else:
Guido van Rossum5aac4e62003-02-06 22:57:00 +000091 state = getattr(obj, "__dict__", None)
92 names = _slotnames(cls)
93 if names:
94 slots = {}
95 nil = []
96 for name in names:
97 value = getattr(obj, name, nil)
98 if value is not nil:
99 slots[name] = value
100 if slots:
101 state = (state, slots)
102 listitems = dictitems = None
103 if isinstance(obj, list):
104 listitems = iter(obj)
105 elif isinstance(obj, dict):
106 dictitems = obj.iteritems()
107 return __newobj__, (cls,) + args, state, listitems, dictitems
108
109def _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__:
134 names += [name for name in c.__dict__["__slots__"]
135 if name not in ("__dict__", "__weakref__")]
136
137 # Cache the outcome in the class if at all possible
138 try:
139 cls.__slotnames__ = names
140 except:
141 pass # But don't die if we can't
142
143 return names
144
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000145# A registry of extension codes. This is an ad-hoc compression
146# mechanism. Whenever a global reference to <module>, <name> is about
147# to be pickled, the (<module>, <name>) tuple is looked up here to see
148# if it is a registered extension code for it. Extension codes are
149# universal, so that the meaning of a pickle does not depend on
150# context. (There are also some codes reserved for local use that
151# don't have this restriction.) Codes are positive ints; 0 is
152# reserved.
153
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000154_extension_registry = {} # key -> code
155_inverted_registry = {} # code -> key
156_extension_cache = {} # code -> object
Tim Peters5b7da392003-02-04 00:21:07 +0000157# Don't ever rebind those names: cPickle grabs a reference to them when
158# it's initialized, and won't see a rebinding.
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000159
160def add_extension(module, name, code):
161 """Register an extension code."""
162 code = int(code)
Tim Peters2d629652003-02-04 05:06:17 +0000163 if not 1 <= code <= 0x7fffffff:
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000164 raise ValueError, "code out of range"
165 key = (module, name)
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000166 if (_extension_registry.get(key) == code and
167 _inverted_registry.get(code) == key):
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000168 return # Redundant registrations are benign
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000169 if key in _extension_registry:
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000170 raise ValueError("key %s is already registered with code %s" %
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000171 (key, _extension_registry[key]))
172 if code in _inverted_registry:
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000173 raise ValueError("code %s is already in use for key %s" %
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000174 (code, _inverted_registry[code]))
175 _extension_registry[key] = code
176 _inverted_registry[code] = key
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000177
178def remove_extension(module, name, code):
179 """Unregister an extension code. For testing only."""
180 key = (module, name)
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000181 if (_extension_registry.get(key) != code or
182 _inverted_registry.get(code) != key):
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000183 raise ValueError("key %s is not registered with code %s" %
184 (key, code))
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000185 del _extension_registry[key]
186 del _inverted_registry[code]
187 if code in _extension_cache:
188 del _extension_cache[code]
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000189
190def clear_extension_cache():
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000191 _extension_cache.clear()
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000192
193# Standard extension code assignments
194
195# Reserved ranges
196
197# First Last Count Purpose
198# 1 127 127 Reserved for Python standard library
Guido van Rossumcef9db62003-02-07 20:56:38 +0000199# 128 191 64 Reserved for Zope
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000200# 192 239 48 Reserved for 3rd parties
201# 240 255 16 Reserved for private use (will never be assigned)
202# 256 Inf Inf Reserved for future assignment
203
204# Extension codes are assigned by the Python Software Foundation.