copyreg.py 7.0 KB

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