blob: db1715092c5dcd0eb1e1a22c0957ee04851b6076 [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
Guido van Rossum8bc09652008-02-21 18:18:37 +000018 if not hasattr(pickle_function, '__call__'):
Fred Drake78a6a362000-10-11 22:16:45 +000019 raise TypeError("reduction functions must be callable")
Guido van Rossum47065621997-04-09 17:44:11 +000020 dispatch_table[ob_type] = pickle_function
21
Jeremy Hyltonf8ecde52003-06-27 16:58:43 +000022 # The constructor_ob function is a vestige of safe for unpickling.
23 # There is no reason for the caller to pass it anymore.
24 if constructor_ob is not None:
25 constructor(constructor_ob)
26
Guido van Rossum47065621997-04-09 17:44:11 +000027def constructor(object):
Guido van Rossum8bc09652008-02-21 18:18:37 +000028 if not hasattr(object, '__call__'):
Fred Drake78a6a362000-10-11 22:16:45 +000029 raise TypeError("constructors must be callable")
Guido van Rossum47065621997-04-09 17:44:11 +000030
Guido van Rossum72be3061997-05-20 18:03:22 +000031# Example: provide pickling support for complex numbers.
Guido van Rossum47065621997-04-09 17:44:11 +000032
Martin v. Löwis502ba462003-06-07 20:10:54 +000033try:
34 complex
35except NameError:
36 pass
37else:
Guido van Rossum72be3061997-05-20 18:03:22 +000038
Martin v. Löwis502ba462003-06-07 20:10:54 +000039 def pickle_complex(c):
40 return complex, (c.real, c.imag)
41
42 pickle(complex, pickle_complex, complex)
Guido van Rossum3926a632001-09-25 16:25:58 +000043
Guido van Rossum298e4212003-02-13 16:30:16 +000044# Support for pickling new-style objects
Guido van Rossum3926a632001-09-25 16:25:58 +000045
Guido van Rossum3926a632001-09-25 16:25:58 +000046def _reconstructor(cls, base, state):
Guido van Rossum298e4212003-02-13 16:30:16 +000047 if base is object:
48 obj = object.__new__(cls)
49 else:
50 obj = base.__new__(cls, state)
Guido van Rossumab8802a2007-04-02 23:55:37 +000051 if base.__init__ != object.__init__:
52 base.__init__(obj, state)
Guido van Rossum3926a632001-09-25 16:25:58 +000053 return obj
Guido van Rossum3926a632001-09-25 16:25:58 +000054
55_HEAPTYPE = 1<<9
56
Guido van Rossumbe532422003-02-21 22:20:31 +000057# Python code for object.__reduce_ex__ for protocols 0 and 1
58
59def _reduce_ex(self, proto):
60 assert proto < 2
Guido van Rossum3926a632001-09-25 16:25:58 +000061 for base in self.__class__.__mro__:
Guido van Rossum00fb0c92001-11-24 21:04:31 +000062 if hasattr(base, '__flags__') and not base.__flags__ & _HEAPTYPE:
Guido van Rossum3926a632001-09-25 16:25:58 +000063 break
64 else:
65 base = object # not really reachable
66 if base is object:
67 state = None
68 else:
Guido van Rossum2a6f5b32001-12-27 16:27:28 +000069 if base is self.__class__:
70 raise TypeError, "can't pickle %s objects" % base.__name__
Guido van Rossum3926a632001-09-25 16:25:58 +000071 state = base(self)
Guido van Rossum6cef6d52001-09-28 18:13:29 +000072 args = (self.__class__, base, state)
73 try:
Guido van Rossum00fb0c92001-11-24 21:04:31 +000074 getstate = self.__getstate__
Guido van Rossum6cef6d52001-09-28 18:13:29 +000075 except AttributeError:
Guido van Rossum3f50cdc2003-02-10 21:31:27 +000076 if getattr(self, "__slots__", None):
77 raise TypeError("a class that defines __slots__ without "
78 "defining __getstate__ cannot be pickled")
Guido van Rossum00fb0c92001-11-24 21:04:31 +000079 try:
80 dict = self.__dict__
81 except AttributeError:
82 dict = None
83 else:
84 dict = getstate()
Guido van Rossum6cef6d52001-09-28 18:13:29 +000085 if dict:
86 return _reconstructor, args, dict
87 else:
88 return _reconstructor, args
Guido van Rossum255f3ee2003-01-29 06:14:11 +000089
Guido van Rossumbe532422003-02-21 22:20:31 +000090# Helper for __reduce_ex__ protocol 2
Guido van Rossum5aac4e62003-02-06 22:57:00 +000091
92def __newobj__(cls, *args):
93 return cls.__new__(cls, *args)
94
Guido van Rossum5aac4e62003-02-06 22:57:00 +000095def _slotnames(cls):
96 """Return a list of slot names for a given class.
97
98 This needs to find slots defined by the class and its bases, so we
99 can't simply return the __slots__ attribute. We must walk down
100 the Method Resolution Order and concatenate the __slots__ of each
101 class found there. (This assumes classes don't modify their
102 __slots__ attribute to misrepresent their slots after the class is
103 defined.)
104 """
105
106 # Get the value from a cache in the class if possible
107 names = cls.__dict__.get("__slotnames__")
108 if names is not None:
109 return names
110
111 # Not cached -- calculate the value
112 names = []
113 if not hasattr(cls, "__slots__"):
114 # This class has no slots
115 pass
116 else:
117 # Slots found -- gather slot names from all base classes
118 for c in cls.__mro__:
119 if "__slots__" in c.__dict__:
Georg Brandl22ec80b2006-03-31 18:25:44 +0000120 slots = c.__dict__['__slots__']
121 # if class has a single slot, it can be given as a string
122 if isinstance(slots, basestring):
123 slots = (slots,)
124 for name in slots:
125 # special descriptors
126 if name in ("__dict__", "__weakref__"):
127 continue
128 # mangled names
129 elif name.startswith('__') and not name.endswith('__'):
130 names.append('_%s%s' % (c.__name__, name))
131 else:
132 names.append(name)
Guido van Rossum5aac4e62003-02-06 22:57:00 +0000133
134 # Cache the outcome in the class if at all possible
135 try:
136 cls.__slotnames__ = names
137 except:
138 pass # But don't die if we can't
139
140 return names
141
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000142# A registry of extension codes. This is an ad-hoc compression
143# mechanism. Whenever a global reference to <module>, <name> is about
144# to be pickled, the (<module>, <name>) tuple is looked up here to see
145# if it is a registered extension code for it. Extension codes are
146# universal, so that the meaning of a pickle does not depend on
147# context. (There are also some codes reserved for local use that
148# don't have this restriction.) Codes are positive ints; 0 is
149# reserved.
150
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000151_extension_registry = {} # key -> code
152_inverted_registry = {} # code -> key
153_extension_cache = {} # code -> object
Tim Peters5b7da392003-02-04 00:21:07 +0000154# Don't ever rebind those names: cPickle grabs a reference to them when
155# it's initialized, and won't see a rebinding.
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000156
157def add_extension(module, name, code):
158 """Register an extension code."""
159 code = int(code)
Tim Peters2d629652003-02-04 05:06:17 +0000160 if not 1 <= code <= 0x7fffffff:
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000161 raise ValueError, "code out of range"
162 key = (module, name)
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000163 if (_extension_registry.get(key) == code and
164 _inverted_registry.get(code) == key):
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000165 return # Redundant registrations are benign
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000166 if key in _extension_registry:
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000167 raise ValueError("key %s is already registered with code %s" %
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000168 (key, _extension_registry[key]))
169 if code in _inverted_registry:
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000170 raise ValueError("code %s is already in use for key %s" %
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000171 (code, _inverted_registry[code]))
172 _extension_registry[key] = code
173 _inverted_registry[code] = key
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000174
175def remove_extension(module, name, code):
176 """Unregister an extension code. For testing only."""
177 key = (module, name)
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000178 if (_extension_registry.get(key) != code or
179 _inverted_registry.get(code) != key):
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000180 raise ValueError("key %s is not registered with code %s" %
181 (key, code))
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000182 del _extension_registry[key]
183 del _inverted_registry[code]
184 if code in _extension_cache:
185 del _extension_cache[code]
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000186
187def clear_extension_cache():
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000188 _extension_cache.clear()
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000189
190# Standard extension code assignments
191
192# Reserved ranges
193
194# First Last Count Purpose
195# 1 127 127 Reserved for Python standard library
Guido van Rossumcef9db62003-02-07 20:56:38 +0000196# 128 191 64 Reserved for Zope
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000197# 192 239 48 Reserved for 3rd parties
198# 240 255 16 Reserved for private use (will never be assigned)
199# 256 Inf Inf Reserved for future assignment
200
201# Extension codes are assigned by the Python Software Foundation.