blob: 8fb61c603c0689f35cb58ebf3b4c2e54adc783c8 [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
Raymond Hettinger93fa6082008-02-05 00:20:01 +00006from _weakrefset import WeakSet
Guido van Rossum8518bdc2007-06-14 00:03:37 +00007
8def 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 Rossumb31339f2007-08-01 17:32:28 +000028class 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 Rossum70d2b892007-08-01 17:52:23 +000034 The abstract properties can be called using any of the the normal
35 'super' call mechanisms.
Guido van Rossumb31339f2007-08-01 17:32:28 +000036
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 Rossum8518bdc2007-06-14 00:03:37 +000055class _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 Rossum8518bdc2007-06-14 00:03:37 +000060 """
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 Rossum894d35e2007-09-11 20:42:30 +000071 return super().__new__(cls)
Guido van Rossum8518bdc2007-06-14 00:03:37 +000072
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
85def _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
99class 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 Rossumc1e315d2007-08-20 19:29:24 +0000118 _abc_invalidation_counter = 0
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000119
120 def __new__(mcls, name, bases, namespace):
121 bases = _fix_bases(bases)
Guido van Rossumbb5f5902007-06-14 03:27:55 +0000122 cls = super().__new__(mcls, name, bases, namespace)
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000123 # 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 Brandl3b8cb172007-10-23 06:26:46 +0000134 cls._abc_registry = WeakSet()
135 cls._abc_cache = WeakSet()
136 cls._abc_negative_cache = WeakSet()
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000137 cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000138 return cls
139
Christian Heimes45031df2007-11-30 15:13:13 +0000140 def register(cls, subclass):
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000141 """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 Rossumc1e315d2007-08-20 19:29:24 +0000151 cls._abc_registry.add(subclass)
152 ABCMeta._abc_invalidation_counter += 1 # Invalidate negative cache
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000153
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 Rossumc1e315d2007-08-20 19:29:24 +0000157 print("Inv.counter: %s" % ABCMeta._abc_invalidation_counter, file=file)
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000158 for name in sorted(cls.__dict__.keys()):
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000159 if name.startswith("_abc_"):
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000160 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 Rossumc1e315d2007-08-20 19:29:24 +0000171 if subclass in cls._abc_cache:
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000172 return True
173 # Check negative cache; may have to invalidate
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000174 if cls._abc_negative_cache_version < ABCMeta._abc_invalidation_counter:
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000175 # Invalidate the negative cache
Georg Brandl3b8cb172007-10-23 06:26:46 +0000176 cls._abc_negative_cache = WeakSet()
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000177 cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter
178 elif subclass in cls._abc_negative_cache:
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000179 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 Rossumc1e315d2007-08-20 19:29:24 +0000185 cls._abc_cache.add(subclass)
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000186 else:
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000187 cls._abc_negative_cache.add(subclass)
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000188 return ok
189 # Check if it's a direct subclass
Christian Heimes043d6f62008-01-07 17:19:16 +0000190 if cls in getattr(subclass, '__mro__', ()):
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000191 cls._abc_cache.add(subclass)
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000192 return True
193 # Check if it's a subclass of a registered class (recursive)
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000194 for rcls in cls._abc_registry:
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000195 if issubclass(subclass, rcls):
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000196 cls._abc_registry.add(subclass)
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000197 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 Rossumc1e315d2007-08-20 19:29:24 +0000201 cls._abc_registry.add(subclass)
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000202 return True
203 # No dice; update negative cache
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000204 cls._abc_negative_cache.add(subclass)
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000205 return False