blob: 2bff142b57e894706b94917c92e27a69d7a761c9 [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 Rossum00fb0c92001-11-24 21:04:31 +000061 try:
62 dict = self.__dict__
63 except AttributeError:
64 dict = None
65 else:
66 dict = getstate()
Guido van Rossum6cef6d52001-09-28 18:13:29 +000067 if dict:
68 return _reconstructor, args, dict
69 else:
70 return _reconstructor, args
Guido van Rossum255f3ee2003-01-29 06:14:11 +000071
72# A registry of extension codes. This is an ad-hoc compression
73# mechanism. Whenever a global reference to <module>, <name> is about
74# to be pickled, the (<module>, <name>) tuple is looked up here to see
75# if it is a registered extension code for it. Extension codes are
76# universal, so that the meaning of a pickle does not depend on
77# context. (There are also some codes reserved for local use that
78# don't have this restriction.) Codes are positive ints; 0 is
79# reserved.
80
81extension_registry = {} # key -> code
82inverted_registry = {} # code -> key
83extension_cache = {} # code -> object
84
85def add_extension(module, name, code):
86 """Register an extension code."""
87 code = int(code)
88 if not 1 <= code < 0x7fffffff:
89 raise ValueError, "code out of range"
90 key = (module, name)
91 if (extension_registry.get(key) == code and
92 inverted_registry.get(code) == key):
93 return # Redundant registrations are benign
94 if key in extension_registry:
95 raise ValueError("key %s is already registered with code %s" %
96 (key, extension_registry[key]))
97 if code in inverted_registry:
98 raise ValueError("code %s is already in use for key %s" %
99 (code, inverted_registry[code]))
100 extension_registry[key] = code
101 inverted_registry[code] = key
102
103def remove_extension(module, name, code):
104 """Unregister an extension code. For testing only."""
105 key = (module, name)
106 if (extension_registry.get(key) != code or
107 inverted_registry.get(code) != key):
108 raise ValueError("key %s is not registered with code %s" %
109 (key, code))
110 del extension_registry[key]
111 del inverted_registry[code]
112 if code in extension_cache:
113 del extension_cache[code]
114
115def clear_extension_cache():
116 extension_cache.clear()
117
118# Standard extension code assignments
119
120# Reserved ranges
121
122# First Last Count Purpose
123# 1 127 127 Reserved for Python standard library
124# 128 191 64 Reserved for Zope 3
125# 192 239 48 Reserved for 3rd parties
126# 240 255 16 Reserved for private use (will never be assigned)
127# 256 Inf Inf Reserved for future assignment
128
129# Extension codes are assigned by the Python Software Foundation.