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