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 normal
14 'super' call mechanisms.
19 __metaclass__ = ABCMeta
21 def my_abstract_method(self, ...):
24 funcobj
.__isabstractmethod
__ = True
28 class abstractproperty(property):
29 """A decorator indicating abstract properties.
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.
34 The abstract properties can be called using any of the normal
35 'super' call mechanisms.
40 __metaclass__ = ABCMeta
42 def my_abstract_property(self):
45 This defines a read-only property; you can also define a read-write
46 abstract property using the 'long' form of property declaration:
49 __metaclass__ = ABCMeta
51 def setx(self, value): ...
52 x = abstractproperty(getx, setx)
54 __isabstractmethod__
= True
59 """Metaclass for defining Abstract Base Classes (ABCs).
61 Use this metaclass to create an ABC. An ABC can be subclassed
62 directly, and then acts as a mix-in class. You can also register
63 unrelated concrete classes (even built-in classes) and unrelated
64 ABCs as 'virtual subclasses' -- these and their descendants will
65 be considered subclasses of the registering ABC by the built-in
66 issubclass() function, but the registering ABC won't show up in
67 their MRO (Method Resolution Order) nor will method
68 implementations defined by the registering ABC be callable (not
73 # A global counter that is incremented each time a class is
74 # registered as a virtual subclass of anything. It forces the
75 # negative cache to be cleared before its next use.
76 _abc_invalidation_counter
= 0
78 def __new__(mcls
, name
, bases
, namespace
):
79 cls
= super(ABCMeta
, mcls
).__new
__(mcls
, name
, bases
, namespace
)
80 # Compute set of abstract method names
82 for name
, value
in namespace
.items()
83 if getattr(value
, "__isabstractmethod__", False))
85 for name
in getattr(base
, "__abstractmethods__", set()):
86 value
= getattr(cls
, name
, None)
87 if getattr(value
, "__isabstractmethod__", False):
89 cls
.__abstractmethods
__ = frozenset(abstracts
)
90 # Set up inheritance registry
91 cls
._abc
_registry
= set()
92 cls
._abc
_cache
= set()
93 cls
._abc
_negative
_cache
= set()
94 cls
._abc
_negative
_cache
_version
= ABCMeta
._abc
_invalidation
_counter
97 def register(cls
, subclass
):
98 """Register a virtual subclass of an ABC."""
99 if not isinstance(cls
, type):
100 raise TypeError("Can only register classes")
101 if issubclass(subclass
, cls
):
102 return # Already a subclass
103 # Subtle: test for cycles *after* testing for "already a subclass";
104 # this means we allow X.register(X) and interpret it as a no-op.
105 if issubclass(cls
, subclass
):
106 # This would create a cycle, which is bad for the algorithm below
107 raise RuntimeError("Refusing to create an inheritance cycle")
108 cls
._abc
_registry
.add(subclass
)
109 ABCMeta
._abc
_invalidation
_counter
+= 1 # Invalidate negative cache
111 def _dump_registry(cls
, file=None):
112 """Debug helper to print the ABC registry."""
113 print >> file, "Class: %s.%s" % (cls
.__module
__, cls
.__name
__)
114 print >> file, "Inv.counter: %s" % ABCMeta
._abc
_invalidation
_counter
115 for name
in sorted(cls
.__dict
__.keys()):
116 if name
.startswith("_abc_"):
117 value
= getattr(cls
, name
)
118 print >> file, "%s: %r" % (name
, value
)
120 def __instancecheck__(cls
, instance
):
121 """Override for isinstance(instance, cls)."""
122 # Inline the cache checking when it's simple.
123 subclass
= getattr(instance
, '__class__', None)
124 if subclass
in cls
._abc
_cache
:
126 subtype
= type(instance
)
127 if subtype
is subclass
or subclass
is None:
128 if (cls
._abc
_negative
_cache
_version
==
129 ABCMeta
._abc
_invalidation
_counter
and
130 subtype
in cls
._abc
_negative
_cache
):
132 # Fall back to the subclass check.
133 return cls
.__subclasscheck
__(subtype
)
134 return (cls
.__subclasscheck
__(subclass
) or
135 cls
.__subclasscheck
__(subtype
))
137 def __subclasscheck__(cls
, subclass
):
138 """Override for issubclass(subclass, cls)."""
140 if subclass
in cls
._abc
_cache
:
142 # Check negative cache; may have to invalidate
143 if cls
._abc
_negative
_cache
_version
< ABCMeta
._abc
_invalidation
_counter
:
144 # Invalidate the negative cache
145 cls
._abc
_negative
_cache
= set()
146 cls
._abc
_negative
_cache
_version
= ABCMeta
._abc
_invalidation
_counter
147 elif subclass
in cls
._abc
_negative
_cache
:
149 # Check the subclass hook
150 ok
= cls
.__subclasshook
__(subclass
)
151 if ok
is not NotImplemented:
152 assert isinstance(ok
, bool)
154 cls
._abc
_cache
.add(subclass
)
156 cls
._abc
_negative
_cache
.add(subclass
)
158 # Check if it's a direct subclass
159 if cls
in getattr(subclass
, '__mro__', ()):
160 cls
._abc
_cache
.add(subclass
)
162 # Check if it's a subclass of a registered class (recursive)
163 for rcls
in cls
._abc
_registry
:
164 if issubclass(subclass
, rcls
):
165 cls
._abc
_cache
.add(subclass
)
167 # Check if it's a subclass of a subclass (recursive)
168 for scls
in cls
.__subclasses
__():
169 if issubclass(subclass
, scls
):
170 cls
._abc
_cache
.add(subclass
)
172 # No dice; update negative cache
173 cls
._abc
_negative
_cache
.add(subclass
)