abc.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. # Copyright 2007 Google, Inc. All Rights Reserved.
  2. # Licensed to PSF under a Contributor Agreement.
  3. """Abstract Base Classes (ABCs) according to PEP 3119."""
  4. from _weakrefset import WeakSet
  5. def abstractmethod(funcobj):
  6. """A decorator indicating abstract methods.
  7. Requires that the metaclass is ABCMeta or derived from it. A
  8. class that has a metaclass derived from ABCMeta cannot be
  9. instantiated unless all of its abstract methods are overridden.
  10. The abstract methods can be called using any of the normal
  11. 'super' call mechanisms.
  12. Usage:
  13. class C(metaclass=ABCMeta):
  14. @abstractmethod
  15. def my_abstract_method(self, ...):
  16. ...
  17. """
  18. funcobj.__isabstractmethod__ = True
  19. return funcobj
  20. class abstractclassmethod(classmethod):
  21. """
  22. A decorator indicating abstract classmethods.
  23. Similar to abstractmethod.
  24. Usage:
  25. class C(metaclass=ABCMeta):
  26. @abstractclassmethod
  27. def my_abstract_classmethod(cls, ...):
  28. ...
  29. 'abstractclassmethod' is deprecated. Use 'classmethod' with
  30. 'abstractmethod' instead.
  31. """
  32. __isabstractmethod__ = True
  33. def __init__(self, callable):
  34. callable.__isabstractmethod__ = True
  35. super().__init__(callable)
  36. class abstractstaticmethod(staticmethod):
  37. """
  38. A decorator indicating abstract staticmethods.
  39. Similar to abstractmethod.
  40. Usage:
  41. class C(metaclass=ABCMeta):
  42. @abstractstaticmethod
  43. def my_abstract_staticmethod(...):
  44. ...
  45. 'abstractstaticmethod' is deprecated. Use 'staticmethod' with
  46. 'abstractmethod' instead.
  47. """
  48. __isabstractmethod__ = True
  49. def __init__(self, callable):
  50. callable.__isabstractmethod__ = True
  51. super().__init__(callable)
  52. class abstractproperty(property):
  53. """
  54. A decorator indicating abstract properties.
  55. Requires that the metaclass is ABCMeta or derived from it. A
  56. class that has a metaclass derived from ABCMeta cannot be
  57. instantiated unless all of its abstract properties are overridden.
  58. The abstract properties can be called using any of the normal
  59. 'super' call mechanisms.
  60. Usage:
  61. class C(metaclass=ABCMeta):
  62. @abstractproperty
  63. def my_abstract_property(self):
  64. ...
  65. This defines a read-only property; you can also define a read-write
  66. abstract property using the 'long' form of property declaration:
  67. class C(metaclass=ABCMeta):
  68. def getx(self): ...
  69. def setx(self, value): ...
  70. x = abstractproperty(getx, setx)
  71. 'abstractproperty' is deprecated. Use 'property' with 'abstractmethod'
  72. instead.
  73. """
  74. __isabstractmethod__ = True
  75. class ABCMeta(type):
  76. """Metaclass for defining Abstract Base Classes (ABCs).
  77. Use this metaclass to create an ABC. An ABC can be subclassed
  78. directly, and then acts as a mix-in class. You can also register
  79. unrelated concrete classes (even built-in classes) and unrelated
  80. ABCs as 'virtual subclasses' -- these and their descendants will
  81. be considered subclasses of the registering ABC by the built-in
  82. issubclass() function, but the registering ABC won't show up in
  83. their MRO (Method Resolution Order) nor will method
  84. implementations defined by the registering ABC be callable (not
  85. even via super()).
  86. """
  87. # A global counter that is incremented each time a class is
  88. # registered as a virtual subclass of anything. It forces the
  89. # negative cache to be cleared before its next use.
  90. # Note: this counter is private. Use `abc.get_cache_token()` for
  91. # external code.
  92. _abc_invalidation_counter = 0
  93. def __new__(mcls, name, bases, namespace):
  94. cls = super().__new__(mcls, name, bases, namespace)
  95. # Compute set of abstract method names
  96. abstracts = {name
  97. for name, value in namespace.items()
  98. if getattr(value, "__isabstractmethod__", False)}
  99. for base in bases:
  100. for name in getattr(base, "__abstractmethods__", set()):
  101. value = getattr(cls, name, None)
  102. if getattr(value, "__isabstractmethod__", False):
  103. abstracts.add(name)
  104. cls.__abstractmethods__ = frozenset(abstracts)
  105. # Set up inheritance registry
  106. cls._abc_registry = WeakSet()
  107. cls._abc_cache = WeakSet()
  108. cls._abc_negative_cache = WeakSet()
  109. cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter
  110. return cls
  111. def register(cls, subclass):
  112. """Register a virtual subclass of an ABC.
  113. Returns the subclass, to allow usage as a class decorator.
  114. """
  115. if not isinstance(subclass, type):
  116. raise TypeError("Can only register classes")
  117. if issubclass(subclass, cls):
  118. return subclass # Already a subclass
  119. # Subtle: test for cycles *after* testing for "already a subclass";
  120. # this means we allow X.register(X) and interpret it as a no-op.
  121. if issubclass(cls, subclass):
  122. # This would create a cycle, which is bad for the algorithm below
  123. raise RuntimeError("Refusing to create an inheritance cycle")
  124. cls._abc_registry.add(subclass)
  125. ABCMeta._abc_invalidation_counter += 1 # Invalidate negative cache
  126. return subclass
  127. def _dump_registry(cls, file=None):
  128. """Debug helper to print the ABC registry."""
  129. print("Class: %s.%s" % (cls.__module__, cls.__qualname__), file=file)
  130. print("Inv.counter: %s" % ABCMeta._abc_invalidation_counter, file=file)
  131. for name in sorted(cls.__dict__.keys()):
  132. if name.startswith("_abc_"):
  133. value = getattr(cls, name)
  134. print("%s: %r" % (name, value), file=file)
  135. def __instancecheck__(cls, instance):
  136. """Override for isinstance(instance, cls)."""
  137. # Inline the cache checking
  138. subclass = instance.__class__
  139. if subclass in cls._abc_cache:
  140. return True
  141. subtype = type(instance)
  142. if subtype is subclass:
  143. if (cls._abc_negative_cache_version ==
  144. ABCMeta._abc_invalidation_counter and
  145. subclass in cls._abc_negative_cache):
  146. return False
  147. # Fall back to the subclass check.
  148. return cls.__subclasscheck__(subclass)
  149. return any(cls.__subclasscheck__(c) for c in {subclass, subtype})
  150. def __subclasscheck__(cls, subclass):
  151. """Override for issubclass(subclass, cls)."""
  152. # Check cache
  153. if subclass in cls._abc_cache:
  154. return True
  155. # Check negative cache; may have to invalidate
  156. if cls._abc_negative_cache_version < ABCMeta._abc_invalidation_counter:
  157. # Invalidate the negative cache
  158. cls._abc_negative_cache = WeakSet()
  159. cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter
  160. elif subclass in cls._abc_negative_cache:
  161. return False
  162. # Check the subclass hook
  163. ok = cls.__subclasshook__(subclass)
  164. if ok is not NotImplemented:
  165. assert isinstance(ok, bool)
  166. if ok:
  167. cls._abc_cache.add(subclass)
  168. else:
  169. cls._abc_negative_cache.add(subclass)
  170. return ok
  171. # Check if it's a direct subclass
  172. if cls in getattr(subclass, '__mro__', ()):
  173. cls._abc_cache.add(subclass)
  174. return True
  175. # Check if it's a subclass of a registered class (recursive)
  176. for rcls in cls._abc_registry:
  177. if issubclass(subclass, rcls):
  178. cls._abc_cache.add(subclass)
  179. return True
  180. # Check if it's a subclass of a subclass (recursive)
  181. for scls in cls.__subclasses__():
  182. if issubclass(subclass, scls):
  183. cls._abc_cache.add(subclass)
  184. return True
  185. # No dice; update negative cache
  186. cls._abc_negative_cache.add(subclass)
  187. return False
  188. class ABC(metaclass=ABCMeta):
  189. """Helper class that provides a standard way to create an ABC using
  190. inheritance.
  191. """
  192. pass
  193. def get_cache_token():
  194. """Returns the current ABC cache token.
  195. The token is an opaque object (supporting equality testing) identifying the
  196. current version of the ABC cache for virtual subclasses. The token changes
  197. with every call to ``register()`` on any ABC.
  198. """
  199. return ABCMeta._abc_invalidation_counter