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