1 # Copyright 2007 Google, Inc. All Rights Reserved.
2 # Licensed to PSF under a Contributor Agreement.
4 """Abstract Base Classes (ABCs) according to PEP 3119."""
6 from _weakrefset
import WeakSet
8 def abstractmethod(funcobj
):
9 """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.
19 class C(metaclass=ABCMeta):
21 def my_abstract_method(self, ...):
24 funcobj
.__isabstractmethod
__ = True
28 class abstractproperty(property):
29 """A decorator indicating abstract properties.
31 Requires that the metaclass is ABCMeta or derived from it. A
32 class that has a metaclass derived from ABCMeta cannot be
33 instantiated unless all of its abstract properties are overridden.
34 The abstract properties can be called using any of the normal
35 'super' call mechanisms.
39 class C(metaclass=ABCMeta):
41 def my_abstract_property(self):
44 This defines a read-only property; you can also define a read-write
45 abstract property using the 'long' form of property declaration:
47 class C(metaclass=ABCMeta):
49 def setx(self, value): ...
50 x = abstractproperty(getx, setx)
52 __isabstractmethod__
= True
57 """Metaclass for defining Abstract Base Classes (ABCs).
59 Use this metaclass to create an ABC. An ABC can be subclassed
60 directly, and then acts as a mix-in class. You can also register
61 unrelated concrete classes (even built-in classes) and unrelated
62 ABCs as 'virtual subclasses' -- these and their descendants will
63 be considered subclasses of the registering ABC by the built-in
64 issubclass() function, but the registering ABC won't show up in
65 their MRO (Method Resolution Order) nor will method
66 implementations defined by the registering ABC be callable (not
71 # A global counter that is incremented each time a class is
72 # registered as a virtual subclass of anything. It forces the
73 # negative cache to be cleared before its next use.
74 _abc_invalidation_counter
= 0
76 def __new__(mcls
, name
, bases
, namespace
):
77 cls
= super().__new
__(mcls
, name
, bases
, namespace
)
78 # Compute set of abstract method names
80 for name
, value
in namespace
.items()
81 if getattr(value
, "__isabstractmethod__", False)}
83 for name
in getattr(base
, "__abstractmethods__", set()):
84 value
= getattr(cls
, name
, None)
85 if getattr(value
, "__isabstractmethod__", False):
87 cls
.__abstractmethods
__ = frozenset(abstracts
)
88 # Set up inheritance registry
89 cls
._abc
_registry
= WeakSet()
90 cls
._abc
_cache
= WeakSet()
91 cls
._abc
_negative
_cache
= WeakSet()
92 cls
._abc
_negative
_cache
_version
= ABCMeta
._abc
_invalidation
_counter
95 def register(cls
, subclass
):
96 """Register a virtual subclass of an ABC."""
97 if not isinstance(cls
, type):
98 raise TypeError("Can only register classes")
99 if issubclass(subclass
, cls
):
100 return # Already a subclass
101 # Subtle: test for cycles *after* testing for "already a subclass";
102 # this means we allow X.register(X) and interpret it as a no-op.
103 if issubclass(cls
, subclass
):
104 # This would create a cycle, which is bad for the algorithm below
105 raise RuntimeError("Refusing to create an inheritance cycle")
106 cls
._abc
_registry
.add(subclass
)
107 ABCMeta
._abc
_invalidation
_counter
+= 1 # Invalidate negative cache
109 def _dump_registry(cls
, file=None):
110 """Debug helper to print the ABC registry."""
111 print("Class: %s.%s" % (cls
.__module
__, cls
.__name
__), file=file)
112 print("Inv.counter: %s" % ABCMeta
._abc
_invalidation
_counter
, file=file)
113 for name
in sorted(cls
.__dict
__.keys()):
114 if name
.startswith("_abc_"):
115 value
= getattr(cls
, name
)
116 print("%s: %r" % (name
, value
), file=file)
118 def __instancecheck__(cls
, instance
):
119 """Override for isinstance(instance, cls)."""
120 # Inline the cache checking
121 subclass
= instance
.__class
__
122 if subclass
in cls
._abc
_cache
:
124 subtype
= type(instance
)
125 if subtype
is subclass
:
126 if (cls
._abc
_negative
_cache
_version
==
127 ABCMeta
._abc
_invalidation
_counter
and
128 subclass
in cls
._abc
_negative
_cache
):
130 # Fall back to the subclass check.
131 return cls
.__subclasscheck
__(subclass
)
132 return any(cls
.__subclasscheck
__(c
) for c
in {subclass
, subtype
})
134 def __subclasscheck__(cls
, subclass
):
135 """Override for issubclass(subclass, cls)."""
137 if subclass
in cls
._abc
_cache
:
139 # Check negative cache; may have to invalidate
140 if cls
._abc
_negative
_cache
_version
< ABCMeta
._abc
_invalidation
_counter
:
141 # Invalidate the negative cache
142 cls
._abc
_negative
_cache
= WeakSet()
143 cls
._abc
_negative
_cache
_version
= ABCMeta
._abc
_invalidation
_counter
144 elif subclass
in cls
._abc
_negative
_cache
:
146 # Check the subclass hook
147 ok
= cls
.__subclasshook
__(subclass
)
148 if ok
is not NotImplemented:
149 assert isinstance(ok
, bool)
151 cls
._abc
_cache
.add(subclass
)
153 cls
._abc
_negative
_cache
.add(subclass
)
155 # Check if it's a direct subclass
156 if cls
in getattr(subclass
, '__mro__', ()):
157 cls
._abc
_cache
.add(subclass
)
159 # Check if it's a subclass of a registered class (recursive)
160 for rcls
in cls
._abc
_registry
:
161 if issubclass(subclass
, rcls
):
162 cls
._abc
_cache
.add(subclass
)
164 # Check if it's a subclass of a subclass (recursive)
165 for scls
in cls
.__subclasses
__():
166 if issubclass(subclass
, scls
):
167 cls
._abc
_cache
.add(subclass
)
169 # No dice; update negative cache
170 cls
._abc
_negative
_cache
.add(subclass
)