blob: ad5a52313c4b5b9fd1444ffc1fe225828f4aab55 [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.
Guido van Rossum70d2b892007-08-01 17:52:23 +000033 The abstract properties can be called using any of the the normal
34 'super' call mechanisms.
Guido van Rossumb31339f2007-08-01 17:32:28 +000035
36 Usage:
37
38 class C(metaclass=ABCMeta):
39 @abstractproperty
40 def my_abstract_property(self):
41 ...
42
43 This defines a read-only property; you can also define a read-write
44 abstract property using the 'long' form of property declaration:
45
46 class C(metaclass=ABCMeta):
47 def getx(self): ...
48 def setx(self, value): ...
49 x = abstractproperty(getx, setx)
50 """
51 __isabstractmethod__ = True
52
53
Guido van Rossum8518bdc2007-06-14 00:03:37 +000054class _Abstract(object):
55
56 """Helper class inserted into the bases by ABCMeta (using _fix_bases()).
57
58 You should never need to explicitly subclass this class.
59
60 There should never be a base class between _Abstract and object.
61 """
62
63 def __new__(cls, *args, **kwds):
64 am = cls.__dict__.get("__abstractmethods__")
65 if am:
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 object.__new__(cls)
73
74 @classmethod
75 def __subclasshook__(cls, subclass):
76 """Abstract classes can override this to customize issubclass().
77
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).
82 """
83 return NotImplemented
84
85
86def _fix_bases(bases):
87 """Helper method that inserts _Abstract in the bases if needed."""
88 for base in bases:
89 if issubclass(base, _Abstract):
90 # _Abstract is already a base (maybe indirectly)
91 return bases
92 if object in bases:
93 # Replace object with _Abstract
94 return tuple([_Abstract if base is object else base
95 for base in bases])
96 # Append _Abstract to the end
97 return bases + (_Abstract,)
98
99
100class ABCMeta(type):
101
102 """Metaclass for defining Abstract Base Classes (ABCs).
103
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
112 even via super()).
113
114 """
115
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.
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000119 _abc_invalidation_counter = 0
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000120
121 def __new__(mcls, name, bases, namespace):
122 bases = _fix_bases(bases)
Guido van Rossumbb5f5902007-06-14 03:27:55 +0000123 cls = super().__new__(mcls, name, bases, namespace)
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000124 # Compute set of abstract method names
125 abstracts = {name
126 for name, value in namespace.items()
127 if getattr(value, "__isabstractmethod__", False)}
128 for base in bases:
129 for name in getattr(base, "__abstractmethods__", set()):
130 value = getattr(cls, name, None)
131 if getattr(value, "__isabstractmethod__", False):
132 abstracts.add(name)
133 cls.__abstractmethods__ = abstracts
134 # Set up inheritance registry
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000135 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
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000139 return cls
140
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")
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000152 cls._abc_registry.add(subclass)
153 ABCMeta._abc_invalidation_counter += 1 # Invalidate negative cache
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000154
155 def _dump_registry(cls, file=None):
156 """Debug helper to print the ABC registry."""
157 print("Class: %s.%s" % (cls.__module__, cls.__name__), file=file)
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000158 print("Inv.counter: %s" % ABCMeta._abc_invalidation_counter, file=file)
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000159 for name in sorted(cls.__dict__.keys()):
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000160 if name.startswith("_abc_"):
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000161 value = getattr(cls, name)
162 print("%s: %r" % (name, value), file=file)
163
164 def __instancecheck__(cls, instance):
165 """Override for isinstance(instance, cls)."""
166 return any(cls.__subclasscheck__(c)
167 for c in {instance.__class__, type(instance)})
168
169 def __subclasscheck__(cls, subclass):
170 """Override for issubclass(subclass, cls)."""
171 # Check cache
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000172 if subclass in cls._abc_cache:
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000173 return True
174 # Check negative cache; may have to invalidate
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000175 if cls._abc_negative_cache_version < ABCMeta._abc_invalidation_counter:
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000176 # Invalidate the negative cache
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000177 cls._abc_negative_cache = set()
178 cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter
179 elif subclass in cls._abc_negative_cache:
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000180 return False
181 # Check the subclass hook
182 ok = cls.__subclasshook__(subclass)
183 if ok is not NotImplemented:
184 assert isinstance(ok, bool)
185 if ok:
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000186 cls._abc_cache.add(subclass)
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000187 else:
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000188 cls._abc_negative_cache.add(subclass)
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000189 return ok
190 # Check if it's a direct subclass
191 if cls in subclass.__mro__:
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000192 cls._abc_cache.add(subclass)
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000193 return True
194 # Check if it's a subclass of a registered class (recursive)
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000195 for rcls in cls._abc_registry:
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000196 if issubclass(subclass, rcls):
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000197 cls._abc_registry.add(subclass)
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000198 return True
199 # Check if it's a subclass of a subclass (recursive)
200 for scls in cls.__subclasses__():
201 if issubclass(subclass, scls):
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000202 cls._abc_registry.add(subclass)
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000203 return True
204 # No dice; update negative cache
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000205 cls._abc_negative_cache.add(subclass)
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000206 return False