blob: c37ed8fd61bd5c457db63ffd1015b33693321f35 [file] [log] [blame]
Guido van Rossumb5591132007-09-10 22:36:02 +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
Florent Xicluna47627d52010-03-08 15:20:28 +00007# Instance of old-style class
8class _C: pass
9_InstanceType = type(_C())
10
11
Guido van Rossumb5591132007-09-10 22:36:02 +000012def abstractmethod(funcobj):
13 """A decorator indicating abstract methods.
14
15 Requires that the metaclass is ABCMeta or derived from it. A
16 class that has a metaclass derived from ABCMeta cannot be
17 instantiated unless all of its abstract methods are overridden.
Walter Dörwald28277092009-05-04 16:03:03 +000018 The abstract methods can be called using any of the normal
Guido van Rossumb5591132007-09-10 22:36:02 +000019 'super' call mechanisms.
20
21 Usage:
22
Georg Brandlbcf7bf32009-02-28 21:33:10 +000023 class C:
24 __metaclass__ = ABCMeta
Guido van Rossumb5591132007-09-10 22:36:02 +000025 @abstractmethod
26 def my_abstract_method(self, ...):
27 ...
28 """
29 funcobj.__isabstractmethod__ = True
30 return funcobj
31
32
33class abstractproperty(property):
34 """A decorator indicating abstract properties.
35
36 Requires that the metaclass is ABCMeta or derived from it. A
37 class that has a metaclass derived from ABCMeta cannot be
38 instantiated unless all of its abstract properties are overridden.
Walter Dörwald28277092009-05-04 16:03:03 +000039 The abstract properties can be called using any of the normal
Guido van Rossumb5591132007-09-10 22:36:02 +000040 'super' call mechanisms.
41
42 Usage:
43
Georg Brandlbcf7bf32009-02-28 21:33:10 +000044 class C:
45 __metaclass__ = ABCMeta
Guido van Rossumb5591132007-09-10 22:36:02 +000046 @abstractproperty
47 def my_abstract_property(self):
48 ...
49
50 This defines a read-only property; you can also define a read-write
51 abstract property using the 'long' form of property declaration:
52
Georg Brandlbcf7bf32009-02-28 21:33:10 +000053 class C:
54 __metaclass__ = ABCMeta
Guido van Rossumb5591132007-09-10 22:36:02 +000055 def getx(self): ...
56 def setx(self, value): ...
57 x = abstractproperty(getx, setx)
58 """
59 __isabstractmethod__ = True
60
61
Guido van Rossumb5591132007-09-10 22:36:02 +000062class ABCMeta(type):
63
64 """Metaclass for defining Abstract Base Classes (ABCs).
65
66 Use this metaclass to create an ABC. An ABC can be subclassed
67 directly, and then acts as a mix-in class. You can also register
68 unrelated concrete classes (even built-in classes) and unrelated
69 ABCs as 'virtual subclasses' -- these and their descendants will
70 be considered subclasses of the registering ABC by the built-in
71 issubclass() function, but the registering ABC won't show up in
72 their MRO (Method Resolution Order) nor will method
73 implementations defined by the registering ABC be callable (not
74 even via super()).
75
76 """
77
78 # A global counter that is incremented each time a class is
79 # registered as a virtual subclass of anything. It forces the
80 # negative cache to be cleared before its next use.
81 _abc_invalidation_counter = 0
82
83 def __new__(mcls, name, bases, namespace):
Guido van Rossumb5591132007-09-10 22:36:02 +000084 cls = super(ABCMeta, mcls).__new__(mcls, name, bases, namespace)
85 # Compute set of abstract method names
86 abstracts = set(name
87 for name, value in namespace.items()
88 if getattr(value, "__isabstractmethod__", False))
89 for base in bases:
90 for name in getattr(base, "__abstractmethods__", set()):
91 value = getattr(cls, name, None)
92 if getattr(value, "__isabstractmethod__", False):
93 abstracts.add(name)
Jeffrey Yasskin960b9b72008-02-28 04:45:36 +000094 cls.__abstractmethods__ = frozenset(abstracts)
Guido van Rossumb5591132007-09-10 22:36:02 +000095 # Set up inheritance registry
96 cls._abc_registry = set()
97 cls._abc_cache = set()
98 cls._abc_negative_cache = set()
99 cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter
100 return cls
101
102 def register(cls, subclass):
103 """Register a virtual subclass of an ABC."""
Benjamin Peterson2deb5c72010-01-27 02:16:42 +0000104 if not isinstance(subclass, type):
Guido van Rossumb5591132007-09-10 22:36:02 +0000105 raise TypeError("Can only register classes")
106 if issubclass(subclass, cls):
107 return # Already a subclass
108 # Subtle: test for cycles *after* testing for "already a subclass";
109 # this means we allow X.register(X) and interpret it as a no-op.
110 if issubclass(cls, subclass):
111 # This would create a cycle, which is bad for the algorithm below
112 raise RuntimeError("Refusing to create an inheritance cycle")
113 cls._abc_registry.add(subclass)
114 ABCMeta._abc_invalidation_counter += 1 # Invalidate negative cache
115
116 def _dump_registry(cls, file=None):
117 """Debug helper to print the ABC registry."""
118 print >> file, "Class: %s.%s" % (cls.__module__, cls.__name__)
119 print >> file, "Inv.counter: %s" % ABCMeta._abc_invalidation_counter
120 for name in sorted(cls.__dict__.keys()):
121 if name.startswith("_abc_"):
122 value = getattr(cls, name)
123 print >> file, "%s: %r" % (name, value)
124
125 def __instancecheck__(cls, instance):
126 """Override for isinstance(instance, cls)."""
Jeffrey Yasskinb9e15f72008-03-17 16:31:21 +0000127 # Inline the cache checking when it's simple.
128 subclass = getattr(instance, '__class__', None)
Jeffrey Yasskin57bd60b2008-02-13 17:58:04 +0000129 if subclass in cls._abc_cache:
130 return True
131 subtype = type(instance)
Florent Xicluna47627d52010-03-08 15:20:28 +0000132 # Old-style instances
133 if subtype is _InstanceType:
134 subtype = subclass
Jeffrey Yasskinb9e15f72008-03-17 16:31:21 +0000135 if subtype is subclass or subclass is None:
Jeffrey Yasskin57bd60b2008-02-13 17:58:04 +0000136 if (cls._abc_negative_cache_version ==
137 ABCMeta._abc_invalidation_counter and
Jeffrey Yasskinb9e15f72008-03-17 16:31:21 +0000138 subtype in cls._abc_negative_cache):
Jeffrey Yasskin57bd60b2008-02-13 17:58:04 +0000139 return False
140 # Fall back to the subclass check.
Jeffrey Yasskinb9e15f72008-03-17 16:31:21 +0000141 return cls.__subclasscheck__(subtype)
Jeffrey Yasskin57bd60b2008-02-13 17:58:04 +0000142 return (cls.__subclasscheck__(subclass) or
143 cls.__subclasscheck__(subtype))
Guido van Rossumb5591132007-09-10 22:36:02 +0000144
145 def __subclasscheck__(cls, subclass):
146 """Override for issubclass(subclass, cls)."""
147 # Check cache
148 if subclass in cls._abc_cache:
149 return True
150 # Check negative cache; may have to invalidate
151 if cls._abc_negative_cache_version < ABCMeta._abc_invalidation_counter:
152 # Invalidate the negative cache
153 cls._abc_negative_cache = set()
154 cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter
155 elif subclass in cls._abc_negative_cache:
156 return False
157 # Check the subclass hook
158 ok = cls.__subclasshook__(subclass)
159 if ok is not NotImplemented:
160 assert isinstance(ok, bool)
161 if ok:
162 cls._abc_cache.add(subclass)
163 else:
164 cls._abc_negative_cache.add(subclass)
165 return ok
166 # Check if it's a direct subclass
Jeffrey Yasskinfd1c2452008-01-07 06:09:40 +0000167 if cls in getattr(subclass, '__mro__', ()):
Guido van Rossumb5591132007-09-10 22:36:02 +0000168 cls._abc_cache.add(subclass)
169 return True
170 # Check if it's a subclass of a registered class (recursive)
171 for rcls in cls._abc_registry:
172 if issubclass(subclass, rcls):
Nick Coghlan91ae3ea2008-09-02 10:14:47 +0000173 cls._abc_cache.add(subclass)
Guido van Rossumb5591132007-09-10 22:36:02 +0000174 return True
175 # Check if it's a subclass of a subclass (recursive)
176 for scls in cls.__subclasses__():
177 if issubclass(subclass, scls):
Nick Coghlan91ae3ea2008-09-02 10:14:47 +0000178 cls._abc_cache.add(subclass)
Guido van Rossumb5591132007-09-10 22:36:02 +0000179 return True
180 # No dice; update negative cache
181 cls._abc_negative_cache.add(subclass)
182 return False