Updated docs for basicConfig to indicate it's a no-op if handlers have been defined...
[python.git] / Lib / abc.py
blob1ce38a81c8829cb0f97448caf381f89ffef44ce8
1 # Copyright 2007 Google, Inc. All Rights Reserved.
2 # Licensed to PSF under a Contributor Agreement.
4 """Abstract Base Classes (ABCs) according to PEP 3119."""
7 def abstractmethod(funcobj):
8 """A decorator indicating abstract methods.
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.
16 Usage:
18 class C(metaclass=ABCMeta):
19 @abstractmethod
20 def my_abstract_method(self, ...):
21 ...
22 """
23 funcobj.__isabstractmethod__ = True
24 return funcobj
27 class abstractproperty(property):
28 """A decorator indicating abstract properties.
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.
33 The abstract properties can be called using any of the the normal
34 'super' call mechanisms.
36 Usage:
38 class C(metaclass=ABCMeta):
39 @abstractproperty
40 def my_abstract_property(self):
41 ...
43 This defines a read-only property; you can also define a read-write
44 abstract property using the 'long' form of property declaration:
46 class C(metaclass=ABCMeta):
47 def getx(self): ...
48 def setx(self, value): ...
49 x = abstractproperty(getx, setx)
50 """
51 __isabstractmethod__ = True
54 class _Abstract(object):
56 """Helper class inserted into the bases by ABCMeta (using _fix_bases()).
58 You should never need to explicitly subclass this class.
60 There should never be a base class between _Abstract and object.
61 """
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 super(_Abstract, cls).__new__(cls)
74 @classmethod
75 def __subclasshook__(cls, subclass):
76 """Abstract classes can override this to customize issubclass().
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
86 def _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,)
100 class ABCMeta(type):
102 """Metaclass for defining Abstract Base Classes (ABCs).
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()).
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.
119 _abc_invalidation_counter = 0
121 def __new__(mcls, name, bases, namespace):
122 bases = _fix_bases(bases)
123 cls = super(ABCMeta, mcls).__new__(mcls, name, bases, namespace)
124 # Compute set of abstract method names
125 abstracts = set(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
135 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
139 return cls
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")
152 cls._abc_registry.add(subclass)
153 ABCMeta._abc_invalidation_counter += 1 # Invalidate negative cache
155 def _dump_registry(cls, file=None):
156 """Debug helper to print the ABC registry."""
157 print >> file, "Class: %s.%s" % (cls.__module__, cls.__name__)
158 print >> file, "Inv.counter: %s" % ABCMeta._abc_invalidation_counter
159 for name in sorted(cls.__dict__.keys()):
160 if name.startswith("_abc_"):
161 value = getattr(cls, name)
162 print >> file, "%s: %r" % (name, value)
164 def __instancecheck__(cls, instance):
165 """Override for isinstance(instance, cls)."""
166 return any(cls.__subclasscheck__(c)
167 for c in set([instance.__class__, type(instance)]))
169 def __subclasscheck__(cls, subclass):
170 """Override for issubclass(subclass, cls)."""
171 # Check cache
172 if subclass in cls._abc_cache:
173 return True
174 # Check negative cache; may have to invalidate
175 if cls._abc_negative_cache_version < ABCMeta._abc_invalidation_counter:
176 # Invalidate the negative cache
177 cls._abc_negative_cache = set()
178 cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter
179 elif subclass in cls._abc_negative_cache:
180 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:
186 cls._abc_cache.add(subclass)
187 else:
188 cls._abc_negative_cache.add(subclass)
189 return ok
190 # Check if it's a direct subclass
191 if cls in getattr(subclass, '__mro__', ()):
192 cls._abc_cache.add(subclass)
193 return True
194 # Check if it's a subclass of a registered class (recursive)
195 for rcls in cls._abc_registry:
196 if issubclass(subclass, rcls):
197 cls._abc_registry.add(subclass)
198 return True
199 # Check if it's a subclass of a subclass (recursive)
200 for scls in cls.__subclasses__():
201 if issubclass(subclass, scls):
202 cls._abc_registry.add(subclass)
203 return True
204 # No dice; update negative cache
205 cls._abc_negative_cache.add(subclass)
206 return False