blob: ab6325e713730f43033cf6666417313882c90700 [file] [log] [blame]
Guido van Rossum8518bdc2007-06-14 00:03:37 +00001# Copyright 2007 Google, Inc. All Rights Reserved.
2# Licensed to PSF under a Contributor Agreement.
3
4"""Abstract Base Classes (ABCs) according to PEP 3119."""
5
6
7def abstractmethod(funcobj):
8 """A decorator indicating abstract methods.
9
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.
15
16 Usage:
17
18 class C(metaclass=ABCMeta):
19 @abstractmethod
20 def my_abstract_method(self, ...):
21 ...
22 """
23 funcobj.__isabstractmethod__ = True
24 return funcobj
25
26
Guido van Rossumb31339f2007-08-01 17:32:28 +000027class abstractproperty(property):
28 """A decorator indicating abstract properties.
29
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
34 Usage:
35
36 class C(metaclass=ABCMeta):
37 @abstractproperty
38 def my_abstract_property(self):
39 ...
40
41 This defines a read-only property; you can also define a read-write
42 abstract property using the 'long' form of property declaration:
43
44 class C(metaclass=ABCMeta):
45 def getx(self): ...
46 def setx(self, value): ...
47 x = abstractproperty(getx, setx)
48 """
49 __isabstractmethod__ = True
50
51
Guido van Rossum8518bdc2007-06-14 00:03:37 +000052class _Abstract(object):
53
54 """Helper class inserted into the bases by ABCMeta (using _fix_bases()).
55
56 You should never need to explicitly subclass this class.
57
58 There should never be a base class between _Abstract and object.
59 """
60
61 def __new__(cls, *args, **kwds):
62 am = cls.__dict__.get("__abstractmethods__")
63 if am:
64 raise TypeError("Can't instantiate abstract class %s "
65 "with abstract methods %s" %
66 (cls.__name__, ", ".join(sorted(am))))
67 if (args or kwds) and cls.__init__ is object.__init__:
68 raise TypeError("Can't pass arguments to __new__ "
69 "without overriding __init__")
70 return object.__new__(cls)
71
72 @classmethod
73 def __subclasshook__(cls, subclass):
74 """Abstract classes can override this to customize issubclass().
75
76 This is invoked early on by __subclasscheck__() below. It
77 should return True, False or NotImplemented. If it returns
78 NotImplemented, the normal algorithm is used. Otherwise, it
79 overrides the normal algorithm (and the outcome is cached).
80 """
81 return NotImplemented
82
83
84def _fix_bases(bases):
85 """Helper method that inserts _Abstract in the bases if needed."""
86 for base in bases:
87 if issubclass(base, _Abstract):
88 # _Abstract is already a base (maybe indirectly)
89 return bases
90 if object in bases:
91 # Replace object with _Abstract
92 return tuple([_Abstract if base is object else base
93 for base in bases])
94 # Append _Abstract to the end
95 return bases + (_Abstract,)
96
97
98class ABCMeta(type):
99
100 """Metaclass for defining Abstract Base Classes (ABCs).
101
102 Use this metaclass to create an ABC. An ABC can be subclassed
103 directly, and then acts as a mix-in class. You can also register
104 unrelated concrete classes (even built-in classes) and unrelated
105 ABCs as 'virtual subclasses' -- these and their descendants will
106 be considered subclasses of the registering ABC by the built-in
107 issubclass() function, but the registering ABC won't show up in
108 their MRO (Method Resolution Order) nor will method
109 implementations defined by the registering ABC be callable (not
110 even via super()).
111
112 """
113
114 # A global counter that is incremented each time a class is
115 # registered as a virtual subclass of anything. It forces the
116 # negative cache to be cleared before its next use.
117 __invalidation_counter = 0
118
119 def __new__(mcls, name, bases, namespace):
120 bases = _fix_bases(bases)
Guido van Rossumbb5f5902007-06-14 03:27:55 +0000121 cls = super().__new__(mcls, name, bases, namespace)
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000122 # Compute set of abstract method names
123 abstracts = {name
124 for name, value in namespace.items()
125 if getattr(value, "__isabstractmethod__", False)}
126 for base in bases:
127 for name in getattr(base, "__abstractmethods__", set()):
128 value = getattr(cls, name, None)
129 if getattr(value, "__isabstractmethod__", False):
130 abstracts.add(name)
131 cls.__abstractmethods__ = abstracts
132 # Set up inheritance registry
133 cls.__registry = set()
134 cls.__cache = set()
135 cls.__negative_cache = set()
136 cls.__negative_cache_version = ABCMeta.__invalidation_counter
137 return cls
138
139 def register(cls, subclass):
140 """Register a virtual subclass of an ABC."""
141 if not isinstance(cls, type):
142 raise TypeError("Can only register classes")
143 if issubclass(subclass, cls):
144 return # Already a subclass
145 # Subtle: test for cycles *after* testing for "already a subclass";
146 # this means we allow X.register(X) and interpret it as a no-op.
147 if issubclass(cls, subclass):
148 # This would create a cycle, which is bad for the algorithm below
149 raise RuntimeError("Refusing to create an inheritance cycle")
150 cls.__registry.add(subclass)
151 ABCMeta.__invalidation_counter += 1 # Invalidate negative cache
152
153 def _dump_registry(cls, file=None):
154 """Debug helper to print the ABC registry."""
155 print("Class: %s.%s" % (cls.__module__, cls.__name__), file=file)
156 print("Inv.counter: %s" % ABCMeta.__invalidation_counter, file=file)
157 for name in sorted(cls.__dict__.keys()):
158 if name.startswith("__abc_"):
159 value = getattr(cls, name)
160 print("%s: %r" % (name, value), file=file)
161
162 def __instancecheck__(cls, instance):
163 """Override for isinstance(instance, cls)."""
164 return any(cls.__subclasscheck__(c)
165 for c in {instance.__class__, type(instance)})
166
167 def __subclasscheck__(cls, subclass):
168 """Override for issubclass(subclass, cls)."""
169 # Check cache
170 if subclass in cls.__cache:
171 return True
172 # Check negative cache; may have to invalidate
173 if cls.__negative_cache_version < ABCMeta.__invalidation_counter:
174 # Invalidate the negative cache
175 cls.__negative_cache_version = ABCMeta.__invalidation_counter
176 cls.__negative_cache = set()
177 elif subclass in cls.__negative_cache:
178 return False
179 # Check the subclass hook
180 ok = cls.__subclasshook__(subclass)
181 if ok is not NotImplemented:
182 assert isinstance(ok, bool)
183 if ok:
184 cls.__cache.add(subclass)
185 else:
186 cls.__negative_cache.add(subclass)
187 return ok
188 # Check if it's a direct subclass
189 if cls in subclass.__mro__:
190 cls.__cache.add(subclass)
191 return True
192 # Check if it's a subclass of a registered class (recursive)
193 for rcls in cls.__registry:
194 if issubclass(subclass, rcls):
195 cls.__registry.add(subclass)
196 return True
197 # Check if it's a subclass of a subclass (recursive)
198 for scls in cls.__subclasses__():
199 if issubclass(subclass, scls):
200 cls.__registry.add(subclass)
201 return True
202 # No dice; update negative cache
203 cls.__negative_cache.add(subclass)
204 return False