blob: c9c34c3eac6667c8a88b414585b8208f52c96c0f [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
Guido van Rossumd4b920c2003-02-04 01:54:49 +000081_extension_registry = {} # key -> code
82_inverted_registry = {} # code -> key
83_extension_cache = {} # code -> object
Tim Peters5b7da392003-02-04 00:21:07 +000084# Don't ever rebind those names: cPickle grabs a reference to them when
85# it's initialized, and won't see a rebinding.
Guido van Rossum255f3ee2003-01-29 06:14:11 +000086
87def add_extension(module, name, code):
88 """Register an extension code."""
89 code = int(code)
Tim Peters2d629652003-02-04 05:06:17 +000090 if not 1 <= code <= 0x7fffffff:
Guido van Rossum255f3ee2003-01-29 06:14:11 +000091 raise ValueError, "code out of range"
92 key = (module, name)
Guido van Rossumd4b920c2003-02-04 01:54:49 +000093 if (_extension_registry.get(key) == code and
94 _inverted_registry.get(code) == key):
Guido van Rossum255f3ee2003-01-29 06:14:11 +000095 return # Redundant registrations are benign
Guido van Rossumd4b920c2003-02-04 01:54:49 +000096 if key in _extension_registry:
Guido van Rossum255f3ee2003-01-29 06:14:11 +000097 raise ValueError("key %s is already registered with code %s" %
Guido van Rossumd4b920c2003-02-04 01:54:49 +000098 (key, _extension_registry[key]))
99 if code in _inverted_registry:
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000100 raise ValueError("code %s is already in use for key %s" %
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000101 (code, _inverted_registry[code]))
102 _extension_registry[key] = code
103 _inverted_registry[code] = key
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000104
105def remove_extension(module, name, code):
106 """Unregister an extension code. For testing only."""
107 key = (module, name)
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000108 if (_extension_registry.get(key) != code or
109 _inverted_registry.get(code) != key):
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000110 raise ValueError("key %s is not registered with code %s" %
111 (key, code))
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000112 del _extension_registry[key]
113 del _inverted_registry[code]
114 if code in _extension_cache:
115 del _extension_cache[code]
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000116
117def clear_extension_cache():
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000118 _extension_cache.clear()
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000119
120# Standard extension code assignments
121
122# Reserved ranges
123
124# First Last Count Purpose
125# 1 127 127 Reserved for Python standard library
126# 128 191 64 Reserved for Zope 3
127# 192 239 48 Reserved for 3rd parties
128# 240 255 16 Reserved for private use (will never be assigned)
129# 256 Inf Inf Reserved for future assignment
130
131# Extension codes are assigned by the Python Software Foundation.