/extern/python/reloop-closured/lib/python2.7/abc.py

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