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."""
7 def abstractmethod(funcobj
):
8 """A decorator indicating abstract methods.
10 Requires that the metaclass is ABCMeta or derived from it. A
11 class that has a metaclass derived from ABCMeta cannot be
12 instantiated unless all of its abstract methods are overridden.
13 The abstract methods can be called using any of the the normal
14 'super' call mechanisms.
18 class C(metaclass=ABCMeta):
20 def my_abstract_method(self, ...):
23 funcobj
.__isabstractmethod
__ = True
27 class abstractproperty(property):
28 """A decorator indicating abstract properties.
30 Requires that the metaclass is ABCMeta or derived from it. A
31 class that has a metaclass derived from ABCMeta cannot be
32 instantiated unless all of its abstract properties are overridden.
33 The abstract properties can be called using any of the the normal
34 'super' call mechanisms.
38 class C(metaclass=ABCMeta):
40 def my_abstract_property(self):
43 This defines a read-only property; you can also define a read-write
44 abstract property using the 'long' form of property declaration:
46 class C(metaclass=ABCMeta):
48 def setx(self, value): ...
49 x = abstractproperty(getx, setx)
51 __isabstractmethod__
= True
54 class _Abstract(object):
56 """Helper class inserted into the bases by ABCMeta (using _fix_bases()).
58 You should never need to explicitly subclass this class.
60 There should never be a base class between _Abstract and object.
63 def __new__(cls
, *args
, **kwds
):
64 am
= cls
.__dict
__.get("__abstractmethods__")
66 raise TypeError("Can't instantiate abstract class %s "
67 "with abstract methods %s" %
68 (cls
.__name
__, ", ".join(sorted(am
))))
69 if (args
or kwds
) and cls
.__init
__ is object.__init
__:
70 raise TypeError("Can't pass arguments to __new__ "
71 "without overriding __init__")
72 return super(_Abstract
, cls
).__new
__(cls
)
75 def __subclasshook__(cls
, subclass
):
76 """Abstract classes can override this to customize issubclass().
78 This is invoked early on by __subclasscheck__() below. It
79 should return True, False or NotImplemented. If it returns
80 NotImplemented, the normal algorithm is used. Otherwise, it
81 overrides the normal algorithm (and the outcome is cached).
86 def _fix_bases(bases
):
87 """Helper method that inserts _Abstract in the bases if needed."""
89 if issubclass(base
, _Abstract
):
90 # _Abstract is already a base (maybe indirectly)
93 # Replace object with _Abstract
94 return tuple([_Abstract
if base
is object else base
96 # Append _Abstract to the end
97 return bases
+ (_Abstract
,)
102 """Metaclass for defining Abstract Base Classes (ABCs).
104 Use this metaclass to create an ABC. An ABC can be subclassed
105 directly, and then acts as a mix-in class. You can also register
106 unrelated concrete classes (even built-in classes) and unrelated
107 ABCs as 'virtual subclasses' -- these and their descendants will
108 be considered subclasses of the registering ABC by the built-in
109 issubclass() function, but the registering ABC won't show up in
110 their MRO (Method Resolution Order) nor will method
111 implementations defined by the registering ABC be callable (not
116 # A global counter that is incremented each time a class is
117 # registered as a virtual subclass of anything. It forces the
118 # negative cache to be cleared before its next use.
119 _abc_invalidation_counter
= 0
121 def __new__(mcls
, name
, bases
, namespace
):
122 bases
= _fix_bases(bases
)
123 cls
= super(ABCMeta
, mcls
).__new
__(mcls
, name
, bases
, namespace
)
124 # Compute set of abstract method names
126 for name
, value
in namespace
.items()
127 if getattr(value
, "__isabstractmethod__", False))
129 for name
in getattr(base
, "__abstractmethods__", set()):
130 value
= getattr(cls
, name
, None)
131 if getattr(value
, "__isabstractmethod__", False):
133 cls
.__abstractmethods
__ = abstracts
134 # Set up inheritance registry
135 cls
._abc
_registry
= set()
136 cls
._abc
_cache
= set()
137 cls
._abc
_negative
_cache
= set()
138 cls
._abc
_negative
_cache
_version
= ABCMeta
._abc
_invalidation
_counter
141 def register(cls
, subclass
):
142 """Register a virtual subclass of an ABC."""
143 if not isinstance(cls
, type):
144 raise TypeError("Can only register classes")
145 if issubclass(subclass
, cls
):
146 return # Already a subclass
147 # Subtle: test for cycles *after* testing for "already a subclass";
148 # this means we allow X.register(X) and interpret it as a no-op.
149 if issubclass(cls
, subclass
):
150 # This would create a cycle, which is bad for the algorithm below
151 raise RuntimeError("Refusing to create an inheritance cycle")
152 cls
._abc
_registry
.add(subclass
)
153 ABCMeta
._abc
_invalidation
_counter
+= 1 # Invalidate negative cache
155 def _dump_registry(cls
, file=None):
156 """Debug helper to print the ABC registry."""
157 print >> file, "Class: %s.%s" % (cls
.__module
__, cls
.__name
__)
158 print >> file, "Inv.counter: %s" % ABCMeta
._abc
_invalidation
_counter
159 for name
in sorted(cls
.__dict
__.keys()):
160 if name
.startswith("_abc_"):
161 value
= getattr(cls
, name
)
162 print >> file, "%s: %r" % (name
, value
)
164 def __instancecheck__(cls
, instance
):
165 """Override for isinstance(instance, cls)."""
166 return any(cls
.__subclasscheck
__(c
)
167 for c
in set([instance
.__class
__, type(instance
)]))
169 def __subclasscheck__(cls
, subclass
):
170 """Override for issubclass(subclass, cls)."""
172 if subclass
in cls
._abc
_cache
:
174 # Check negative cache; may have to invalidate
175 if cls
._abc
_negative
_cache
_version
< ABCMeta
._abc
_invalidation
_counter
:
176 # Invalidate the negative cache
177 cls
._abc
_negative
_cache
= set()
178 cls
._abc
_negative
_cache
_version
= ABCMeta
._abc
_invalidation
_counter
179 elif subclass
in cls
._abc
_negative
_cache
:
181 # Check the subclass hook
182 ok
= cls
.__subclasshook
__(subclass
)
183 if ok
is not NotImplemented:
184 assert isinstance(ok
, bool)
186 cls
._abc
_cache
.add(subclass
)
188 cls
._abc
_negative
_cache
.add(subclass
)
190 # Check if it's a direct subclass
191 if cls
in getattr(subclass
, '__mro__', ()):
192 cls
._abc
_cache
.add(subclass
)
194 # Check if it's a subclass of a registered class (recursive)
195 for rcls
in cls
._abc
_registry
:
196 if issubclass(subclass
, rcls
):
197 cls
._abc
_registry
.add(subclass
)
199 # Check if it's a subclass of a subclass (recursive)
200 for scls
in cls
.__subclasses
__():
201 if issubclass(subclass
, scls
):
202 cls
._abc
_registry
.add(subclass
)
204 # No dice; update negative cache
205 cls
._abc
_negative
_cache
.add(subclass
)