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."""
8 from _weakrefset
import WeakSet
10 # Instance of old-style class
12 _InstanceType
= type(_C())
15 def abstractmethod(funcobj
):
16 """A decorator indicating abstract methods.
18 Requires that the metaclass is ABCMeta or derived from it. A
19 class that has a metaclass derived from ABCMeta cannot be
20 instantiated unless all of its abstract methods are overridden.
21 The abstract methods can be called using any of the normal
22 'super' call mechanisms.
27 __metaclass__ = ABCMeta
29 def my_abstract_method(self, ...):
32 funcobj
.__isabstractmethod
__ = True
36 class abstractproperty(property):
37 """A decorator indicating abstract properties.
39 Requires that the metaclass is ABCMeta or derived from it. A
40 class that has a metaclass derived from ABCMeta cannot be
41 instantiated unless all of its abstract properties are overridden.
42 The abstract properties can be called using any of the normal
43 'super' call mechanisms.
48 __metaclass__ = ABCMeta
50 def my_abstract_property(self):
53 This defines a read-only property; you can also define a read-write
54 abstract property using the 'long' form of property declaration:
57 __metaclass__ = ABCMeta
59 def setx(self, value): ...
60 x = abstractproperty(getx, setx)
62 __isabstractmethod__
= True
67 """Metaclass for defining Abstract Base Classes (ABCs).
69 Use this metaclass to create an ABC. An ABC can be subclassed
70 directly, and then acts as a mix-in class. You can also register
71 unrelated concrete classes (even built-in classes) and unrelated
72 ABCs as 'virtual subclasses' -- these and their descendants will
73 be considered subclasses of the registering ABC by the built-in
74 issubclass() function, but the registering ABC won't show up in
75 their MRO (Method Resolution Order) nor will method
76 implementations defined by the registering ABC be callable (not
81 # A global counter that is incremented each time a class is
82 # registered as a virtual subclass of anything. It forces the
83 # negative cache to be cleared before its next use.
84 _abc_invalidation_counter
= 0
86 def __new__(mcls
, name
, bases
, namespace
):
87 cls
= super(ABCMeta
, mcls
).__new
__(mcls
, name
, bases
, namespace
)
88 # Compute set of abstract method names
90 for name
, value
in namespace
.items()
91 if getattr(value
, "__isabstractmethod__", False))
93 for name
in getattr(base
, "__abstractmethods__", set()):
94 value
= getattr(cls
, name
, None)
95 if getattr(value
, "__isabstractmethod__", False):
97 cls
.__abstractmethods
__ = frozenset(abstracts
)
98 # Set up inheritance registry
99 cls
._abc
_registry
= WeakSet()
100 cls
._abc
_cache
= WeakSet()
101 cls
._abc
_negative
_cache
= WeakSet()
102 cls
._abc
_negative
_cache
_version
= ABCMeta
._abc
_invalidation
_counter
105 def register(cls
, subclass
):
106 """Register a virtual subclass of an ABC."""
107 if not isinstance(subclass
, (type, types
.ClassType
)):
108 raise TypeError("Can only register classes")
109 if issubclass(subclass
, cls
):
110 return # Already a subclass
111 # Subtle: test for cycles *after* testing for "already a subclass";
112 # this means we allow X.register(X) and interpret it as a no-op.
113 if issubclass(cls
, subclass
):
114 # This would create a cycle, which is bad for the algorithm below
115 raise RuntimeError("Refusing to create an inheritance cycle")
116 cls
._abc
_registry
.add(subclass
)
117 ABCMeta
._abc
_invalidation
_counter
+= 1 # Invalidate negative cache
119 def _dump_registry(cls
, file=None):
120 """Debug helper to print the ABC registry."""
121 print >> file, "Class: %s.%s" % (cls
.__module
__, cls
.__name
__)
122 print >> file, "Inv.counter: %s" % ABCMeta
._abc
_invalidation
_counter
123 for name
in sorted(cls
.__dict
__.keys()):
124 if name
.startswith("_abc_"):
125 value
= getattr(cls
, name
)
126 print >> file, "%s: %r" % (name
, value
)
128 def __instancecheck__(cls
, instance
):
129 """Override for isinstance(instance, cls)."""
130 # Inline the cache checking when it's simple.
131 subclass
= getattr(instance
, '__class__', None)
132 if subclass
is not None and subclass
in cls
._abc
_cache
:
134 subtype
= type(instance
)
135 # Old-style instances
136 if subtype
is _InstanceType
:
138 if subtype
is subclass
or subclass
is None:
139 if (cls
._abc
_negative
_cache
_version
==
140 ABCMeta
._abc
_invalidation
_counter
and
141 subtype
in cls
._abc
_negative
_cache
):
143 # Fall back to the subclass check.
144 return cls
.__subclasscheck
__(subtype
)
145 return (cls
.__subclasscheck
__(subclass
) or
146 cls
.__subclasscheck
__(subtype
))
148 def __subclasscheck__(cls
, subclass
):
149 """Override for issubclass(subclass, cls)."""
151 if subclass
in cls
._abc
_cache
:
153 # Check negative cache; may have to invalidate
154 if cls
._abc
_negative
_cache
_version
< ABCMeta
._abc
_invalidation
_counter
:
155 # Invalidate the negative cache
156 cls
._abc
_negative
_cache
= WeakSet()
157 cls
._abc
_negative
_cache
_version
= ABCMeta
._abc
_invalidation
_counter
158 elif subclass
in cls
._abc
_negative
_cache
:
160 # Check the subclass hook
161 ok
= cls
.__subclasshook
__(subclass
)
162 if ok
is not NotImplemented:
163 assert isinstance(ok
, bool)
165 cls
._abc
_cache
.add(subclass
)
167 cls
._abc
_negative
_cache
.add(subclass
)
169 # Check if it's a direct subclass
170 if cls
in getattr(subclass
, '__mro__', ()):
171 cls
._abc
_cache
.add(subclass
)
173 # Check if it's a subclass of a registered class (recursive)
174 for rcls
in cls
._abc
_registry
:
175 if issubclass(subclass
, rcls
):
176 cls
._abc
_cache
.add(subclass
)
178 # Check if it's a subclass of a subclass (recursive)
179 for scls
in cls
.__subclasses
__():
180 if issubclass(subclass
, scls
):
181 cls
._abc
_cache
.add(subclass
)
183 # No dice; update negative cache
184 cls
._abc
_negative
_cache
.add(subclass
)