copyreg.py 7.1 KB

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