1 | n/a | # Copyright 2007 Google, Inc. All Rights Reserved. |
---|
2 | n/a | # Licensed to PSF under a Contributor Agreement. |
---|
3 | n/a | |
---|
4 | n/a | """Abstract Base Classes (ABCs) according to PEP 3119.""" |
---|
5 | n/a | |
---|
6 | n/a | from _weakrefset import WeakSet |
---|
7 | n/a | |
---|
8 | n/a | |
---|
9 | n/a | def abstractmethod(funcobj): |
---|
10 | n/a | """A decorator indicating abstract methods. |
---|
11 | n/a | |
---|
12 | n/a | Requires that the metaclass is ABCMeta or derived from it. A |
---|
13 | n/a | class that has a metaclass derived from ABCMeta cannot be |
---|
14 | n/a | instantiated unless all of its abstract methods are overridden. |
---|
15 | n/a | The abstract methods can be called using any of the normal |
---|
16 | n/a | 'super' call mechanisms. |
---|
17 | n/a | |
---|
18 | n/a | Usage: |
---|
19 | n/a | |
---|
20 | n/a | class C(metaclass=ABCMeta): |
---|
21 | n/a | @abstractmethod |
---|
22 | n/a | def my_abstract_method(self, ...): |
---|
23 | n/a | ... |
---|
24 | n/a | """ |
---|
25 | n/a | funcobj.__isabstractmethod__ = True |
---|
26 | n/a | return funcobj |
---|
27 | n/a | |
---|
28 | n/a | |
---|
29 | n/a | class abstractclassmethod(classmethod): |
---|
30 | n/a | """ |
---|
31 | n/a | A decorator indicating abstract classmethods. |
---|
32 | n/a | |
---|
33 | n/a | Similar to abstractmethod. |
---|
34 | n/a | |
---|
35 | n/a | Usage: |
---|
36 | n/a | |
---|
37 | n/a | class C(metaclass=ABCMeta): |
---|
38 | n/a | @abstractclassmethod |
---|
39 | n/a | def my_abstract_classmethod(cls, ...): |
---|
40 | n/a | ... |
---|
41 | n/a | |
---|
42 | n/a | 'abstractclassmethod' is deprecated. Use 'classmethod' with |
---|
43 | n/a | 'abstractmethod' instead. |
---|
44 | n/a | """ |
---|
45 | n/a | |
---|
46 | n/a | __isabstractmethod__ = True |
---|
47 | n/a | |
---|
48 | n/a | def __init__(self, callable): |
---|
49 | n/a | callable.__isabstractmethod__ = True |
---|
50 | n/a | super().__init__(callable) |
---|
51 | n/a | |
---|
52 | n/a | |
---|
53 | n/a | class abstractstaticmethod(staticmethod): |
---|
54 | n/a | """ |
---|
55 | n/a | A decorator indicating abstract staticmethods. |
---|
56 | n/a | |
---|
57 | n/a | Similar to abstractmethod. |
---|
58 | n/a | |
---|
59 | n/a | Usage: |
---|
60 | n/a | |
---|
61 | n/a | class C(metaclass=ABCMeta): |
---|
62 | n/a | @abstractstaticmethod |
---|
63 | n/a | def my_abstract_staticmethod(...): |
---|
64 | n/a | ... |
---|
65 | n/a | |
---|
66 | n/a | 'abstractstaticmethod' is deprecated. Use 'staticmethod' with |
---|
67 | n/a | 'abstractmethod' instead. |
---|
68 | n/a | """ |
---|
69 | n/a | |
---|
70 | n/a | __isabstractmethod__ = True |
---|
71 | n/a | |
---|
72 | n/a | def __init__(self, callable): |
---|
73 | n/a | callable.__isabstractmethod__ = True |
---|
74 | n/a | super().__init__(callable) |
---|
75 | n/a | |
---|
76 | n/a | |
---|
77 | n/a | class abstractproperty(property): |
---|
78 | n/a | """ |
---|
79 | n/a | A decorator indicating abstract properties. |
---|
80 | n/a | |
---|
81 | n/a | Requires that the metaclass is ABCMeta or derived from it. A |
---|
82 | n/a | class that has a metaclass derived from ABCMeta cannot be |
---|
83 | n/a | instantiated unless all of its abstract properties are overridden. |
---|
84 | n/a | The abstract properties can be called using any of the normal |
---|
85 | n/a | 'super' call mechanisms. |
---|
86 | n/a | |
---|
87 | n/a | Usage: |
---|
88 | n/a | |
---|
89 | n/a | class C(metaclass=ABCMeta): |
---|
90 | n/a | @abstractproperty |
---|
91 | n/a | def my_abstract_property(self): |
---|
92 | n/a | ... |
---|
93 | n/a | |
---|
94 | n/a | This defines a read-only property; you can also define a read-write |
---|
95 | n/a | abstract property using the 'long' form of property declaration: |
---|
96 | n/a | |
---|
97 | n/a | class C(metaclass=ABCMeta): |
---|
98 | n/a | def getx(self): ... |
---|
99 | n/a | def setx(self, value): ... |
---|
100 | n/a | x = abstractproperty(getx, setx) |
---|
101 | n/a | |
---|
102 | n/a | 'abstractproperty' is deprecated. Use 'property' with 'abstractmethod' |
---|
103 | n/a | instead. |
---|
104 | n/a | """ |
---|
105 | n/a | |
---|
106 | n/a | __isabstractmethod__ = True |
---|
107 | n/a | |
---|
108 | n/a | |
---|
109 | n/a | class ABCMeta(type): |
---|
110 | n/a | |
---|
111 | n/a | """Metaclass for defining Abstract Base Classes (ABCs). |
---|
112 | n/a | |
---|
113 | n/a | Use this metaclass to create an ABC. An ABC can be subclassed |
---|
114 | n/a | directly, and then acts as a mix-in class. You can also register |
---|
115 | n/a | unrelated concrete classes (even built-in classes) and unrelated |
---|
116 | n/a | ABCs as 'virtual subclasses' -- these and their descendants will |
---|
117 | n/a | be considered subclasses of the registering ABC by the built-in |
---|
118 | n/a | issubclass() function, but the registering ABC won't show up in |
---|
119 | n/a | their MRO (Method Resolution Order) nor will method |
---|
120 | n/a | implementations defined by the registering ABC be callable (not |
---|
121 | n/a | even via super()). |
---|
122 | n/a | |
---|
123 | n/a | """ |
---|
124 | n/a | |
---|
125 | n/a | # A global counter that is incremented each time a class is |
---|
126 | n/a | # registered as a virtual subclass of anything. It forces the |
---|
127 | n/a | # negative cache to be cleared before its next use. |
---|
128 | n/a | # Note: this counter is private. Use `abc.get_cache_token()` for |
---|
129 | n/a | # external code. |
---|
130 | n/a | _abc_invalidation_counter = 0 |
---|
131 | n/a | |
---|
132 | n/a | def __new__(mcls, name, bases, namespace): |
---|
133 | n/a | cls = super().__new__(mcls, name, bases, namespace) |
---|
134 | n/a | # Compute set of abstract method names |
---|
135 | n/a | abstracts = {name |
---|
136 | n/a | for name, value in namespace.items() |
---|
137 | n/a | if getattr(value, "__isabstractmethod__", False)} |
---|
138 | n/a | for base in bases: |
---|
139 | n/a | for name in getattr(base, "__abstractmethods__", set()): |
---|
140 | n/a | value = getattr(cls, name, None) |
---|
141 | n/a | if getattr(value, "__isabstractmethod__", False): |
---|
142 | n/a | abstracts.add(name) |
---|
143 | n/a | cls.__abstractmethods__ = frozenset(abstracts) |
---|
144 | n/a | # Set up inheritance registry |
---|
145 | n/a | cls._abc_registry = WeakSet() |
---|
146 | n/a | cls._abc_cache = WeakSet() |
---|
147 | n/a | cls._abc_negative_cache = WeakSet() |
---|
148 | n/a | cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter |
---|
149 | n/a | return cls |
---|
150 | n/a | |
---|
151 | n/a | def register(cls, subclass): |
---|
152 | n/a | """Register a virtual subclass of an ABC. |
---|
153 | n/a | |
---|
154 | n/a | Returns the subclass, to allow usage as a class decorator. |
---|
155 | n/a | """ |
---|
156 | n/a | if not isinstance(subclass, type): |
---|
157 | n/a | raise TypeError("Can only register classes") |
---|
158 | n/a | if issubclass(subclass, cls): |
---|
159 | n/a | return subclass # Already a subclass |
---|
160 | n/a | # Subtle: test for cycles *after* testing for "already a subclass"; |
---|
161 | n/a | # this means we allow X.register(X) and interpret it as a no-op. |
---|
162 | n/a | if issubclass(cls, subclass): |
---|
163 | n/a | # This would create a cycle, which is bad for the algorithm below |
---|
164 | n/a | raise RuntimeError("Refusing to create an inheritance cycle") |
---|
165 | n/a | cls._abc_registry.add(subclass) |
---|
166 | n/a | ABCMeta._abc_invalidation_counter += 1 # Invalidate negative cache |
---|
167 | n/a | return subclass |
---|
168 | n/a | |
---|
169 | n/a | def _dump_registry(cls, file=None): |
---|
170 | n/a | """Debug helper to print the ABC registry.""" |
---|
171 | n/a | print("Class: %s.%s" % (cls.__module__, cls.__qualname__), file=file) |
---|
172 | n/a | print("Inv.counter: %s" % ABCMeta._abc_invalidation_counter, file=file) |
---|
173 | n/a | for name in sorted(cls.__dict__.keys()): |
---|
174 | n/a | if name.startswith("_abc_"): |
---|
175 | n/a | value = getattr(cls, name) |
---|
176 | n/a | print("%s: %r" % (name, value), file=file) |
---|
177 | n/a | |
---|
178 | n/a | def __instancecheck__(cls, instance): |
---|
179 | n/a | """Override for isinstance(instance, cls).""" |
---|
180 | n/a | # Inline the cache checking |
---|
181 | n/a | subclass = instance.__class__ |
---|
182 | n/a | if subclass in cls._abc_cache: |
---|
183 | n/a | return True |
---|
184 | n/a | subtype = type(instance) |
---|
185 | n/a | if subtype is subclass: |
---|
186 | n/a | if (cls._abc_negative_cache_version == |
---|
187 | n/a | ABCMeta._abc_invalidation_counter and |
---|
188 | n/a | subclass in cls._abc_negative_cache): |
---|
189 | n/a | return False |
---|
190 | n/a | # Fall back to the subclass check. |
---|
191 | n/a | return cls.__subclasscheck__(subclass) |
---|
192 | n/a | return any(cls.__subclasscheck__(c) for c in {subclass, subtype}) |
---|
193 | n/a | |
---|
194 | n/a | def __subclasscheck__(cls, subclass): |
---|
195 | n/a | """Override for issubclass(subclass, cls).""" |
---|
196 | n/a | # Check cache |
---|
197 | n/a | if subclass in cls._abc_cache: |
---|
198 | n/a | return True |
---|
199 | n/a | # Check negative cache; may have to invalidate |
---|
200 | n/a | if cls._abc_negative_cache_version < ABCMeta._abc_invalidation_counter: |
---|
201 | n/a | # Invalidate the negative cache |
---|
202 | n/a | cls._abc_negative_cache = WeakSet() |
---|
203 | n/a | cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter |
---|
204 | n/a | elif subclass in cls._abc_negative_cache: |
---|
205 | n/a | return False |
---|
206 | n/a | # Check the subclass hook |
---|
207 | n/a | ok = cls.__subclasshook__(subclass) |
---|
208 | n/a | if ok is not NotImplemented: |
---|
209 | n/a | assert isinstance(ok, bool) |
---|
210 | n/a | if ok: |
---|
211 | n/a | cls._abc_cache.add(subclass) |
---|
212 | n/a | else: |
---|
213 | n/a | cls._abc_negative_cache.add(subclass) |
---|
214 | n/a | return ok |
---|
215 | n/a | # Check if it's a direct subclass |
---|
216 | n/a | if cls in getattr(subclass, '__mro__', ()): |
---|
217 | n/a | cls._abc_cache.add(subclass) |
---|
218 | n/a | return True |
---|
219 | n/a | # Check if it's a subclass of a registered class (recursive) |
---|
220 | n/a | for rcls in cls._abc_registry: |
---|
221 | n/a | if issubclass(subclass, rcls): |
---|
222 | n/a | cls._abc_cache.add(subclass) |
---|
223 | n/a | return True |
---|
224 | n/a | # Check if it's a subclass of a subclass (recursive) |
---|
225 | n/a | for scls in cls.__subclasses__(): |
---|
226 | n/a | if issubclass(subclass, scls): |
---|
227 | n/a | cls._abc_cache.add(subclass) |
---|
228 | n/a | return True |
---|
229 | n/a | # No dice; update negative cache |
---|
230 | n/a | cls._abc_negative_cache.add(subclass) |
---|
231 | n/a | return False |
---|
232 | n/a | |
---|
233 | n/a | |
---|
234 | n/a | class ABC(metaclass=ABCMeta): |
---|
235 | n/a | """Helper class that provides a standard way to create an ABC using |
---|
236 | n/a | inheritance. |
---|
237 | n/a | """ |
---|
238 | n/a | pass |
---|
239 | n/a | |
---|
240 | n/a | |
---|
241 | n/a | def get_cache_token(): |
---|
242 | n/a | """Returns the current ABC cache token. |
---|
243 | n/a | |
---|
244 | n/a | The token is an opaque object (supporting equality testing) identifying the |
---|
245 | n/a | current version of the ABC cache for virtual subclasses. The token changes |
---|
246 | n/a | with every call to ``register()`` on any ABC. |
---|
247 | n/a | """ |
---|
248 | n/a | return ABCMeta._abc_invalidation_counter |
---|