/Lib/abc.py

http://unladen-swallow.googlecode.com/ · Python · 174 lines · 149 code · 4 blank · 21 comment · 2 complexity · eaea1d9cdac060576c6cf1ebdadd5f6f MD5 · raw file

  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. def abstractmethod(funcobj):
  5. """A decorator indicating abstract methods.
  6. Requires that the metaclass is ABCMeta or derived from it. A
  7. class that has a metaclass derived from ABCMeta cannot be
  8. instantiated unless all of its abstract methods are overridden.
  9. The abstract methods can be called using any of the normal
  10. 'super' call mechanisms.
  11. Usage:
  12. class C:
  13. __metaclass__ = ABCMeta
  14. @abstractmethod
  15. def my_abstract_method(self, ...):
  16. ...
  17. """
  18. funcobj.__isabstractmethod__ = True
  19. return funcobj
  20. class abstractproperty(property):
  21. """A decorator indicating abstract properties.
  22. Requires that the metaclass is ABCMeta or derived from it. A
  23. class that has a metaclass derived from ABCMeta cannot be
  24. instantiated unless all of its abstract properties are overridden.
  25. The abstract properties can be called using any of the normal
  26. 'super' call mechanisms.
  27. Usage:
  28. class C:
  29. __metaclass__ = ABCMeta
  30. @abstractproperty
  31. def my_abstract_property(self):
  32. ...
  33. This defines a read-only property; you can also define a read-write
  34. abstract property using the 'long' form of property declaration:
  35. class C:
  36. __metaclass__ = ABCMeta
  37. def getx(self): ...
  38. def setx(self, value): ...
  39. x = abstractproperty(getx, setx)
  40. """
  41. __isabstractmethod__ = True
  42. class ABCMeta(type):
  43. """Metaclass for defining Abstract Base Classes (ABCs).
  44. Use this metaclass to create an ABC. An ABC can be subclassed
  45. directly, and then acts as a mix-in class. You can also register
  46. unrelated concrete classes (even built-in classes) and unrelated
  47. ABCs as 'virtual subclasses' -- these and their descendants will
  48. be considered subclasses of the registering ABC by the built-in
  49. issubclass() function, but the registering ABC won't show up in
  50. their MRO (Method Resolution Order) nor will method
  51. implementations defined by the registering ABC be callable (not
  52. even via super()).
  53. """
  54. # A global counter that is incremented each time a class is
  55. # registered as a virtual subclass of anything. It forces the
  56. # negative cache to be cleared before its next use.
  57. _abc_invalidation_counter = 0
  58. def __new__(mcls, name, bases, namespace):
  59. cls = super(ABCMeta, mcls).__new__(mcls, name, bases, namespace)
  60. # Compute set of abstract method names
  61. abstracts = set(name
  62. for name, value in namespace.items()
  63. if getattr(value, "__isabstractmethod__", False))
  64. for base in bases:
  65. for name in getattr(base, "__abstractmethods__", set()):
  66. value = getattr(cls, name, None)
  67. if getattr(value, "__isabstractmethod__", False):
  68. abstracts.add(name)
  69. cls.__abstractmethods__ = frozenset(abstracts)
  70. # Set up inheritance registry
  71. cls._abc_registry = set()
  72. cls._abc_cache = set()
  73. cls._abc_negative_cache = set()
  74. cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter
  75. return cls
  76. def register(cls, subclass):
  77. """Register a virtual subclass of an ABC."""
  78. if not isinstance(cls, type):
  79. raise TypeError("Can only register classes")
  80. if issubclass(subclass, cls):
  81. return # Already a subclass
  82. # Subtle: test for cycles *after* testing for "already a subclass";
  83. # this means we allow X.register(X) and interpret it as a no-op.
  84. if issubclass(cls, subclass):
  85. # This would create a cycle, which is bad for the algorithm below
  86. raise RuntimeError("Refusing to create an inheritance cycle")
  87. cls._abc_registry.add(subclass)
  88. ABCMeta._abc_invalidation_counter += 1 # Invalidate negative cache
  89. def _dump_registry(cls, file=None):
  90. """Debug helper to print the ABC registry."""
  91. print >> file, "Class: %s.%s" % (cls.__module__, cls.__name__)
  92. print >> file, "Inv.counter: %s" % ABCMeta._abc_invalidation_counter
  93. for name in sorted(cls.__dict__.keys()):
  94. if name.startswith("_abc_"):
  95. value = getattr(cls, name)
  96. print >> file, "%s: %r" % (name, value)
  97. def __instancecheck__(cls, instance):
  98. """Override for isinstance(instance, cls)."""
  99. # Inline the cache checking when it's simple.
  100. subclass = getattr(instance, '__class__', None)
  101. if subclass in cls._abc_cache:
  102. return True
  103. subtype = type(instance)
  104. if subtype is subclass or subclass is None:
  105. if (cls._abc_negative_cache_version ==
  106. ABCMeta._abc_invalidation_counter and
  107. subtype in cls._abc_negative_cache):
  108. return False
  109. # Fall back to the subclass check.
  110. return cls.__subclasscheck__(subtype)
  111. return (cls.__subclasscheck__(subclass) or
  112. cls.__subclasscheck__(subtype))
  113. def __subclasscheck__(cls, subclass):
  114. """Override for issubclass(subclass, cls)."""
  115. # Check cache
  116. if subclass in cls._abc_cache:
  117. return True
  118. # Check negative cache; may have to invalidate
  119. if cls._abc_negative_cache_version < ABCMeta._abc_invalidation_counter:
  120. # Invalidate the negative cache
  121. cls._abc_negative_cache = set()
  122. cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter
  123. elif subclass in cls._abc_negative_cache:
  124. return False
  125. # Check the subclass hook
  126. ok = cls.__subclasshook__(subclass)
  127. if ok is not NotImplemented:
  128. assert isinstance(ok, bool)
  129. if ok:
  130. cls._abc_cache.add(subclass)
  131. else:
  132. cls._abc_negative_cache.add(subclass)
  133. return ok
  134. # Check if it's a direct subclass
  135. if cls in getattr(subclass, '__mro__', ()):
  136. cls._abc_cache.add(subclass)
  137. return True
  138. # Check if it's a subclass of a registered class (recursive)
  139. for rcls in cls._abc_registry:
  140. if issubclass(subclass, rcls):
  141. cls._abc_cache.add(subclass)
  142. return True
  143. # Check if it's a subclass of a subclass (recursive)
  144. for scls in cls.__subclasses__():
  145. if issubclass(subclass, scls):
  146. cls._abc_cache.add(subclass)
  147. return True
  148. # No dice; update negative cache
  149. cls._abc_negative_cache.add(subclass)
  150. return False