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