blob: f8e02302782b86ed691e7b58a4653df7cd80f9c2 [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.
Guido van Rossum8518bdc2007-06-14 00:03:37 +000059 """
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__")
Guido van Rossum894d35e2007-09-11 20:42:30 +000070 return super().__new__(cls)
Guido van Rossum8518bdc2007-06-14 00:03:37 +000071
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.
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000117 _abc_invalidation_counter = 0
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000118
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
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000133 cls._abc_registry = set()
134 cls._abc_cache = set()
135 cls._abc_negative_cache = set()
136 cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000137 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")
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000150 cls._abc_registry.add(subclass)
151 ABCMeta._abc_invalidation_counter += 1 # Invalidate negative cache
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000152
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)
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000156 print("Inv.counter: %s" % ABCMeta._abc_invalidation_counter, file=file)
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000157 for name in sorted(cls.__dict__.keys()):
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000158 if name.startswith("_abc_"):
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000159 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
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000170 if subclass in cls._abc_cache:
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000171 return True
172 # Check negative cache; may have to invalidate
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000173 if cls._abc_negative_cache_version < ABCMeta._abc_invalidation_counter:
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000174 # Invalidate the negative cache
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000175 cls._abc_negative_cache = set()
176 cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter
177 elif subclass in cls._abc_negative_cache:
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000178 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:
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000184 cls._abc_cache.add(subclass)
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000185 else:
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000186 cls._abc_negative_cache.add(subclass)
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000187 return ok
188 # Check if it's a direct subclass
189 if cls in subclass.__mro__:
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000190 cls._abc_cache.add(subclass)
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000191 return True
192 # Check if it's a subclass of a registered class (recursive)
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000193 for rcls in cls._abc_registry:
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000194 if issubclass(subclass, rcls):
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000195 cls._abc_registry.add(subclass)
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000196 return True
197 # Check if it's a subclass of a subclass (recursive)
198 for scls in cls.__subclasses__():
199 if issubclass(subclass, scls):
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000200 cls._abc_registry.add(subclass)
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000201 return True
202 # No dice; update negative cache
Guido van Rossumc1e315d2007-08-20 19:29:24 +0000203 cls._abc_negative_cache.add(subclass)
Guido van Rossum8518bdc2007-06-14 00:03:37 +0000204 return False