blob: f4661edf4137600fb65599dff269b4be89e1dc50 [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
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):
Fred Drake78a6a362000-10-11 22:16:45 +000013 if not callable(pickle_function):
14 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):
Fred Drake78a6a362000-10-11 22:16:45 +000023 if not callable(object):
24 raise TypeError("constructors must be callable")
Guido van Rossum47065621997-04-09 17:44:11 +000025
Guido van Rossum72be3061997-05-20 18:03:22 +000026# Example: provide pickling support for complex numbers.
Guido van Rossum47065621997-04-09 17:44:11 +000027
Martin v. Löwis502ba462003-06-07 20:10:54 +000028try:
29 complex
30except NameError:
31 pass
32else:
Guido van Rossum72be3061997-05-20 18:03:22 +000033
Martin v. Löwis502ba462003-06-07 20:10:54 +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
Guido van Rossum298e4212003-02-13 16:30:16 +000039# Support for pickling new-style objects
Guido van Rossum3926a632001-09-25 16:25:58 +000040
Guido van Rossum3926a632001-09-25 16:25:58 +000041def _reconstructor(cls, base, state):
Guido van Rossum298e4212003-02-13 16:30:16 +000042 if base is object:
43 obj = object.__new__(cls)
44 else:
45 obj = base.__new__(cls, state)
46 base.__init__(obj, state)
Guido van Rossum3926a632001-09-25 16:25:58 +000047 return obj
Guido van Rossum3926a632001-09-25 16:25:58 +000048
49_HEAPTYPE = 1<<9
50
Guido van Rossumbe532422003-02-21 22:20:31 +000051# Python code for object.__reduce_ex__ for protocols 0 and 1
52
53def _reduce_ex(self, proto):
54 assert proto < 2
Guido van Rossum3926a632001-09-25 16:25:58 +000055 for base in self.__class__.__mro__:
Guido van Rossum00fb0c92001-11-24 21:04:31 +000056 if hasattr(base, '__flags__') and not base.__flags__ & _HEAPTYPE:
Guido van Rossum3926a632001-09-25 16:25:58 +000057 break
58 else:
59 base = object # not really reachable
60 if base is object:
61 state = None
62 else:
Guido van Rossum2a6f5b32001-12-27 16:27:28 +000063 if base is self.__class__:
64 raise TypeError, "can't pickle %s objects" % base.__name__
Guido van Rossum3926a632001-09-25 16:25:58 +000065 state = base(self)
Guido van Rossum6cef6d52001-09-28 18:13:29 +000066 args = (self.__class__, base, state)
67 try:
Guido van Rossum00fb0c92001-11-24 21:04:31 +000068 getstate = self.__getstate__
Guido van Rossum6cef6d52001-09-28 18:13:29 +000069 except AttributeError:
Guido van Rossum3f50cdc2003-02-10 21:31:27 +000070 if getattr(self, "__slots__", None):
71 raise TypeError("a class that defines __slots__ without "
72 "defining __getstate__ cannot be pickled")
Guido van Rossum00fb0c92001-11-24 21:04:31 +000073 try:
74 dict = self.__dict__
75 except AttributeError:
76 dict = None
77 else:
78 dict = getstate()
Guido van Rossum6cef6d52001-09-28 18:13:29 +000079 if dict:
80 return _reconstructor, args, dict
81 else:
82 return _reconstructor, args
Guido van Rossum255f3ee2003-01-29 06:14:11 +000083
Guido van Rossumbe532422003-02-21 22:20:31 +000084# Helper for __reduce_ex__ protocol 2
Guido van Rossum5aac4e62003-02-06 22:57:00 +000085
86def __newobj__(cls, *args):
87 return cls.__new__(cls, *args)
88
Guido van Rossum5aac4e62003-02-06 22:57:00 +000089def _slotnames(cls):
90 """Return a list of slot names for a given class.
91
92 This needs to find slots defined by the class and its bases, so we
93 can't simply return the __slots__ attribute. We must walk down
94 the Method Resolution Order and concatenate the __slots__ of each
95 class found there. (This assumes classes don't modify their
96 __slots__ attribute to misrepresent their slots after the class is
97 defined.)
98 """
99
100 # Get the value from a cache in the class if possible
101 names = cls.__dict__.get("__slotnames__")
102 if names is not None:
103 return names
104
105 # Not cached -- calculate the value
106 names = []
107 if not hasattr(cls, "__slots__"):
108 # This class has no slots
109 pass
110 else:
111 # Slots found -- gather slot names from all base classes
112 for c in cls.__mro__:
113 if "__slots__" in c.__dict__:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000114 slots = c.__dict__['__slots__']
115 # if class has a single slot, it can be given as a string
116 if isinstance(slots, basestring):
117 slots = (slots,)
118 for name in slots:
119 # special descriptors
120 if name in ("__dict__", "__weakref__"):
121 continue
122 # mangled names
123 elif name.startswith('__') and not name.endswith('__'):
124 names.append('_%s%s' % (c.__name__, name))
125 else:
126 names.append(name)
Guido van Rossum5aac4e62003-02-06 22:57:00 +0000127
128 # Cache the outcome in the class if at all possible
129 try:
130 cls.__slotnames__ = names
131 except:
132 pass # But don't die if we can't
133
134 return names
135
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000136# A registry of extension codes. This is an ad-hoc compression
137# mechanism. Whenever a global reference to <module>, <name> is about
138# to be pickled, the (<module>, <name>) tuple is looked up here to see
139# if it is a registered extension code for it. Extension codes are
140# universal, so that the meaning of a pickle does not depend on
141# context. (There are also some codes reserved for local use that
142# don't have this restriction.) Codes are positive ints; 0 is
143# reserved.
144
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000145_extension_registry = {} # key -> code
146_inverted_registry = {} # code -> key
147_extension_cache = {} # code -> object
Tim Peters5b7da392003-02-04 00:21:07 +0000148# Don't ever rebind those names: cPickle grabs a reference to them when
149# it's initialized, and won't see a rebinding.
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000150
151def add_extension(module, name, code):
152 """Register an extension code."""
153 code = int(code)
Tim Peters2d629652003-02-04 05:06:17 +0000154 if not 1 <= code <= 0x7fffffff:
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000155 raise ValueError, "code out of range"
156 key = (module, name)
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000157 if (_extension_registry.get(key) == code and
158 _inverted_registry.get(code) == key):
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000159 return # Redundant registrations are benign
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000160 if key in _extension_registry:
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000161 raise ValueError("key %s is already registered with code %s" %
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000162 (key, _extension_registry[key]))
163 if code in _inverted_registry:
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000164 raise ValueError("code %s is already in use for key %s" %
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000165 (code, _inverted_registry[code]))
166 _extension_registry[key] = code
167 _inverted_registry[code] = key
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000168
169def remove_extension(module, name, code):
170 """Unregister an extension code. For testing only."""
171 key = (module, name)
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000172 if (_extension_registry.get(key) != code or
173 _inverted_registry.get(code) != key):
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000174 raise ValueError("key %s is not registered with code %s" %
175 (key, code))
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000176 del _extension_registry[key]
177 del _inverted_registry[code]
178 if code in _extension_cache:
179 del _extension_cache[code]
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000180
181def clear_extension_cache():
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000182 _extension_cache.clear()
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000183
184# Standard extension code assignments
185
186# Reserved ranges
187
188# First Last Count Purpose
189# 1 127 127 Reserved for Python standard library
Guido van Rossumcef9db62003-02-07 20:56:38 +0000190# 128 191 64 Reserved for Zope
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000191# 192 239 48 Reserved for 3rd parties
192# 240 255 16 Reserved for private use (will never be assigned)
193# 256 Inf Inf Reserved for future assignment
194
195# Extension codes are assigned by the Python Software Foundation.