Guido van Rossum | 99603b0 | 2007-07-20 00:22:32 +0000 | [diff] [blame] | 1 | """Helper to provide extensibility for pickle. |
Fred Drake | 78a6a36 | 2000-10-11 22:16:45 +0000 | [diff] [blame] | 2 | |
| 3 | This is only useful to add pickle support for extension types defined in |
| 4 | C, not for instances of user-defined classes. |
| 5 | """ |
| 6 | |
Guido van Rossum | cf356fd | 2003-01-31 20:34:07 +0000 | [diff] [blame] | 7 | __all__ = ["pickle", "constructor", |
| 8 | "add_extension", "remove_extension", "clear_extension_cache"] |
Skip Montanaro | e99d5ea | 2001-01-20 19:54:20 +0000 | [diff] [blame] | 9 | |
Guido van Rossum | 4706562 | 1997-04-09 17:44:11 +0000 | [diff] [blame] | 10 | dispatch_table = {} |
Guido van Rossum | 4706562 | 1997-04-09 17:44:11 +0000 | [diff] [blame] | 11 | |
Fred Drake | 78a6a36 | 2000-10-11 22:16:45 +0000 | [diff] [blame] | 12 | def pickle(ob_type, pickle_function, constructor_ob=None): |
Florent Xicluna | 5d1155c | 2011-10-28 14:45:05 +0200 | [diff] [blame] | 13 | if not callable(pickle_function): |
Fred Drake | 78a6a36 | 2000-10-11 22:16:45 +0000 | [diff] [blame] | 14 | raise TypeError("reduction functions must be callable") |
Guido van Rossum | 4706562 | 1997-04-09 17:44:11 +0000 | [diff] [blame] | 15 | dispatch_table[ob_type] = pickle_function |
| 16 | |
Jeremy Hylton | f8ecde5 | 2003-06-27 16:58:43 +0000 | [diff] [blame] | 17 | # 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 Rossum | 4706562 | 1997-04-09 17:44:11 +0000 | [diff] [blame] | 22 | def constructor(object): |
Florent Xicluna | 5d1155c | 2011-10-28 14:45:05 +0200 | [diff] [blame] | 23 | if not callable(object): |
Fred Drake | 78a6a36 | 2000-10-11 22:16:45 +0000 | [diff] [blame] | 24 | raise TypeError("constructors must be callable") |
Guido van Rossum | 4706562 | 1997-04-09 17:44:11 +0000 | [diff] [blame] | 25 | |
Guido van Rossum | 0dd32e2 | 2007-04-11 05:40:58 +0000 | [diff] [blame] | 26 | # Example: provide pickling support for complex numbers. |
Guido van Rossum | 4706562 | 1997-04-09 17:44:11 +0000 | [diff] [blame] | 27 | |
Guido van Rossum | 0dd32e2 | 2007-04-11 05:40:58 +0000 | [diff] [blame] | 28 | try: |
| 29 | complex |
| 30 | except NameError: |
| 31 | pass |
| 32 | else: |
Guido van Rossum | 72be306 | 1997-05-20 18:03:22 +0000 | [diff] [blame] | 33 | |
Guido van Rossum | 0dd32e2 | 2007-04-11 05:40:58 +0000 | [diff] [blame] | 34 | def pickle_complex(c): |
| 35 | return complex, (c.real, c.imag) |
| 36 | |
| 37 | pickle(complex, pickle_complex, complex) |
Guido van Rossum | 3926a63 | 2001-09-25 16:25:58 +0000 | [diff] [blame] | 38 | |
Guido van Rossum | 298e421 | 2003-02-13 16:30:16 +0000 | [diff] [blame] | 39 | # Support for pickling new-style objects |
Guido van Rossum | 3926a63 | 2001-09-25 16:25:58 +0000 | [diff] [blame] | 40 | |
Guido van Rossum | 3926a63 | 2001-09-25 16:25:58 +0000 | [diff] [blame] | 41 | def _reconstructor(cls, base, state): |
Guido van Rossum | 298e421 | 2003-02-13 16:30:16 +0000 | [diff] [blame] | 42 | if base is object: |
| 43 | obj = object.__new__(cls) |
| 44 | else: |
| 45 | obj = base.__new__(cls, state) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 46 | if base.__init__ != object.__init__: |
| 47 | base.__init__(obj, state) |
Guido van Rossum | 3926a63 | 2001-09-25 16:25:58 +0000 | [diff] [blame] | 48 | return obj |
Guido van Rossum | 3926a63 | 2001-09-25 16:25:58 +0000 | [diff] [blame] | 49 | |
| 50 | _HEAPTYPE = 1<<9 |
| 51 | |
Guido van Rossum | be53242 | 2003-02-21 22:20:31 +0000 | [diff] [blame] | 52 | # Python code for object.__reduce_ex__ for protocols 0 and 1 |
| 53 | |
| 54 | def _reduce_ex(self, proto): |
| 55 | assert proto < 2 |
Guido van Rossum | 3926a63 | 2001-09-25 16:25:58 +0000 | [diff] [blame] | 56 | for base in self.__class__.__mro__: |
Guido van Rossum | 00fb0c9 | 2001-11-24 21:04:31 +0000 | [diff] [blame] | 57 | if hasattr(base, '__flags__') and not base.__flags__ & _HEAPTYPE: |
Guido van Rossum | 3926a63 | 2001-09-25 16:25:58 +0000 | [diff] [blame] | 58 | break |
| 59 | else: |
| 60 | base = object # not really reachable |
| 61 | if base is object: |
| 62 | state = None |
| 63 | else: |
Guido van Rossum | 2a6f5b3 | 2001-12-27 16:27:28 +0000 | [diff] [blame] | 64 | if base is self.__class__: |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 65 | raise TypeError("can't pickle %s objects" % base.__name__) |
Guido van Rossum | 3926a63 | 2001-09-25 16:25:58 +0000 | [diff] [blame] | 66 | state = base(self) |
Guido van Rossum | 6cef6d5 | 2001-09-28 18:13:29 +0000 | [diff] [blame] | 67 | args = (self.__class__, base, state) |
| 68 | try: |
Guido van Rossum | 00fb0c9 | 2001-11-24 21:04:31 +0000 | [diff] [blame] | 69 | getstate = self.__getstate__ |
Guido van Rossum | 6cef6d5 | 2001-09-28 18:13:29 +0000 | [diff] [blame] | 70 | except AttributeError: |
Guido van Rossum | 3f50cdc | 2003-02-10 21:31:27 +0000 | [diff] [blame] | 71 | if getattr(self, "__slots__", None): |
| 72 | raise TypeError("a class that defines __slots__ without " |
| 73 | "defining __getstate__ cannot be pickled") |
Guido van Rossum | 00fb0c9 | 2001-11-24 21:04:31 +0000 | [diff] [blame] | 74 | try: |
| 75 | dict = self.__dict__ |
| 76 | except AttributeError: |
| 77 | dict = None |
| 78 | else: |
| 79 | dict = getstate() |
Guido van Rossum | 6cef6d5 | 2001-09-28 18:13:29 +0000 | [diff] [blame] | 80 | if dict: |
| 81 | return _reconstructor, args, dict |
| 82 | else: |
| 83 | return _reconstructor, args |
Guido van Rossum | 255f3ee | 2003-01-29 06:14:11 +0000 | [diff] [blame] | 84 | |
Guido van Rossum | be53242 | 2003-02-21 22:20:31 +0000 | [diff] [blame] | 85 | # Helper for __reduce_ex__ protocol 2 |
Guido van Rossum | 5aac4e6 | 2003-02-06 22:57:00 +0000 | [diff] [blame] | 86 | |
| 87 | def __newobj__(cls, *args): |
| 88 | return cls.__new__(cls, *args) |
| 89 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 90 | def __newobj_ex__(cls, args, kwargs): |
| 91 | """Used by pickle protocol 4, instead of __newobj__ to allow classes with |
| 92 | keyword-only arguments to be pickled correctly. |
| 93 | """ |
| 94 | return cls.__new__(cls, *args, **kwargs) |
| 95 | |
Guido van Rossum | 5aac4e6 | 2003-02-06 22:57:00 +0000 | [diff] [blame] | 96 | def _slotnames(cls): |
| 97 | """Return a list of slot names for a given class. |
| 98 | |
| 99 | This needs to find slots defined by the class and its bases, so we |
| 100 | can't simply return the __slots__ attribute. We must walk down |
| 101 | the Method Resolution Order and concatenate the __slots__ of each |
| 102 | class found there. (This assumes classes don't modify their |
| 103 | __slots__ attribute to misrepresent their slots after the class is |
| 104 | defined.) |
| 105 | """ |
| 106 | |
| 107 | # Get the value from a cache in the class if possible |
| 108 | names = cls.__dict__.get("__slotnames__") |
| 109 | if names is not None: |
| 110 | return names |
| 111 | |
| 112 | # Not cached -- calculate the value |
| 113 | names = [] |
| 114 | if not hasattr(cls, "__slots__"): |
| 115 | # This class has no slots |
| 116 | pass |
| 117 | else: |
| 118 | # Slots found -- gather slot names from all base classes |
| 119 | for c in cls.__mro__: |
| 120 | if "__slots__" in c.__dict__: |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 121 | slots = c.__dict__['__slots__'] |
| 122 | # if class has a single slot, it can be given as a string |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 123 | if isinstance(slots, str): |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 124 | slots = (slots,) |
| 125 | for name in slots: |
| 126 | # special descriptors |
| 127 | if name in ("__dict__", "__weakref__"): |
| 128 | continue |
| 129 | # mangled names |
| 130 | elif name.startswith('__') and not name.endswith('__'): |
| 131 | names.append('_%s%s' % (c.__name__, name)) |
| 132 | else: |
| 133 | names.append(name) |
Guido van Rossum | 5aac4e6 | 2003-02-06 22:57:00 +0000 | [diff] [blame] | 134 | |
| 135 | # Cache the outcome in the class if at all possible |
| 136 | try: |
| 137 | cls.__slotnames__ = names |
| 138 | except: |
| 139 | pass # But don't die if we can't |
| 140 | |
| 141 | return names |
| 142 | |
Guido van Rossum | 255f3ee | 2003-01-29 06:14:11 +0000 | [diff] [blame] | 143 | # A registry of extension codes. This is an ad-hoc compression |
| 144 | # mechanism. Whenever a global reference to <module>, <name> is about |
| 145 | # to be pickled, the (<module>, <name>) tuple is looked up here to see |
| 146 | # if it is a registered extension code for it. Extension codes are |
| 147 | # universal, so that the meaning of a pickle does not depend on |
| 148 | # context. (There are also some codes reserved for local use that |
| 149 | # don't have this restriction.) Codes are positive ints; 0 is |
| 150 | # reserved. |
| 151 | |
Guido van Rossum | d4b920c | 2003-02-04 01:54:49 +0000 | [diff] [blame] | 152 | _extension_registry = {} # key -> code |
| 153 | _inverted_registry = {} # code -> key |
| 154 | _extension_cache = {} # code -> object |
Guido van Rossum | 99603b0 | 2007-07-20 00:22:32 +0000 | [diff] [blame] | 155 | # Don't ever rebind those names: pickling grabs a reference to them when |
Tim Peters | 5b7da39 | 2003-02-04 00:21:07 +0000 | [diff] [blame] | 156 | # it's initialized, and won't see a rebinding. |
Guido van Rossum | 255f3ee | 2003-01-29 06:14:11 +0000 | [diff] [blame] | 157 | |
| 158 | def add_extension(module, name, code): |
| 159 | """Register an extension code.""" |
| 160 | code = int(code) |
Tim Peters | 2d62965 | 2003-02-04 05:06:17 +0000 | [diff] [blame] | 161 | if not 1 <= code <= 0x7fffffff: |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 162 | raise ValueError("code out of range") |
Guido van Rossum | 255f3ee | 2003-01-29 06:14:11 +0000 | [diff] [blame] | 163 | key = (module, name) |
Guido van Rossum | d4b920c | 2003-02-04 01:54:49 +0000 | [diff] [blame] | 164 | if (_extension_registry.get(key) == code and |
| 165 | _inverted_registry.get(code) == key): |
Guido van Rossum | 255f3ee | 2003-01-29 06:14:11 +0000 | [diff] [blame] | 166 | return # Redundant registrations are benign |
Guido van Rossum | d4b920c | 2003-02-04 01:54:49 +0000 | [diff] [blame] | 167 | if key in _extension_registry: |
Guido van Rossum | 255f3ee | 2003-01-29 06:14:11 +0000 | [diff] [blame] | 168 | raise ValueError("key %s is already registered with code %s" % |
Guido van Rossum | d4b920c | 2003-02-04 01:54:49 +0000 | [diff] [blame] | 169 | (key, _extension_registry[key])) |
| 170 | if code in _inverted_registry: |
Guido van Rossum | 255f3ee | 2003-01-29 06:14:11 +0000 | [diff] [blame] | 171 | raise ValueError("code %s is already in use for key %s" % |
Guido van Rossum | d4b920c | 2003-02-04 01:54:49 +0000 | [diff] [blame] | 172 | (code, _inverted_registry[code])) |
| 173 | _extension_registry[key] = code |
| 174 | _inverted_registry[code] = key |
Guido van Rossum | 255f3ee | 2003-01-29 06:14:11 +0000 | [diff] [blame] | 175 | |
| 176 | def remove_extension(module, name, code): |
| 177 | """Unregister an extension code. For testing only.""" |
| 178 | key = (module, name) |
Guido van Rossum | d4b920c | 2003-02-04 01:54:49 +0000 | [diff] [blame] | 179 | if (_extension_registry.get(key) != code or |
| 180 | _inverted_registry.get(code) != key): |
Guido van Rossum | 255f3ee | 2003-01-29 06:14:11 +0000 | [diff] [blame] | 181 | raise ValueError("key %s is not registered with code %s" % |
| 182 | (key, code)) |
Guido van Rossum | d4b920c | 2003-02-04 01:54:49 +0000 | [diff] [blame] | 183 | del _extension_registry[key] |
| 184 | del _inverted_registry[code] |
| 185 | if code in _extension_cache: |
| 186 | del _extension_cache[code] |
Guido van Rossum | 255f3ee | 2003-01-29 06:14:11 +0000 | [diff] [blame] | 187 | |
| 188 | def clear_extension_cache(): |
Guido van Rossum | d4b920c | 2003-02-04 01:54:49 +0000 | [diff] [blame] | 189 | _extension_cache.clear() |
Guido van Rossum | 255f3ee | 2003-01-29 06:14:11 +0000 | [diff] [blame] | 190 | |
| 191 | # Standard extension code assignments |
| 192 | |
| 193 | # Reserved ranges |
| 194 | |
| 195 | # First Last Count Purpose |
| 196 | # 1 127 127 Reserved for Python standard library |
Guido van Rossum | cef9db6 | 2003-02-07 20:56:38 +0000 | [diff] [blame] | 197 | # 128 191 64 Reserved for Zope |
Guido van Rossum | 255f3ee | 2003-01-29 06:14:11 +0000 | [diff] [blame] | 198 | # 192 239 48 Reserved for 3rd parties |
| 199 | # 240 255 16 Reserved for private use (will never be assigned) |
| 200 | # 256 Inf Inf Reserved for future assignment |
| 201 | |
| 202 | # Extension codes are assigned by the Python Software Foundation. |