Sub topic 11
Duck-typed checks with __subclasshook__
This chapter assumes you know how @abstractmethod blocks instantiation and how isinstance and issubclass work with ABCs. It also assumes you have seen register, which makes a class a virtual subclass. __subclasshook__ is the third way a class can count as a subclass of an ABC. The class doesn't inherit from the ABC or get registered. The ABC inspects it and decides.
What the hook does
__subclasshook__ is a class method on an ABC. issubclass(C, SomeABC) calls it, and so does isinstance(obj, SomeABC) through type(obj). It receives the class being tested and returns one of three values:
| Return value | Meaning |
|---|---|
| `True` | `C` counts as a subclass. Python stops checking. |
| `False` | `C` does not count as a subclass. Python stops checking. |
| `NotImplemented` | The hook has no opinion. Python continues with its normal checks. |
The normal checks are inheritance through the MRO, then registered classes, then the ABC's own subclasses. This is how an ABC can say "anything with a close method is Closeable" without touching the class that has the method.
A minimal hook
from abc import ABC, abstractmethod
class Closeable(ABC):
@abstractmethod
def close(self) -> None:
...
@classmethod
def __subclasshook__(cls, subclass):
if cls is Closeable:
if any("close" in klass.__dict__ for klass in subclass.__mro__):
return True
return NotImplemented
class Connection:
def close(self) -> None:
print("connection closed")
print(issubclass(Connection, Closeable))
print(isinstance(Connection(), Closeable))
print(issubclass(int, Closeable))The output is:
True
True
FalseConnection never mentions Closeable, yet it passes both checks. int has no close, so the hook returns NotImplemented. Python then runs the normal checks, which also fail, so the answer is False.
The hook looks through subclass.__mro__ and not only subclass.__dict__. A class that inherits close from a base class should still match.
Where the hook sits in the check
The hook runs early, before the MRO check. The caches come first, as in CPython's pure-Python abc implementation.
Two consequences follow from this order:
- A hook that returns
Falseoverrides explicit inheritance. A class that inherits from the ABC can still failissubclassif the hook rejects it. - A hook that returns
Trueskips the other checks. It never affects the MRO or the abstract-method check.
Why the `cls is Closeable` guard matters
Subclasses inherit class methods, so they inherit __subclasshook__ too. Without the guard, every subclass of Closeable would use the same "has a close method" rule. Here is that case, with the guard in place:
from abc import ABC, abstractmethod
class Closeable(ABC):
@abstractmethod
def close(self) -> None:
...
@classmethod
def __subclasshook__(cls, subclass):
if cls is Closeable:
if any("close" in klass.__dict__ for klass in subclass.__mro__):
return True
return NotImplemented
class Resource(Closeable):
@abstractmethod
def flush(self) -> None:
...
class Connection:
def close(self) -> None:
print("connection closed")
print(issubclass(Connection, Closeable))
print(issubclass(Connection, Resource))This prints True and then False. When Python checks Resource, the hook runs with cls set to Resource, so it returns NotImplemented and the normal rules apply. Connection has no flush and does not inherit from Resource, so it is rejected. Without the guard, Connection would also count as a Resource, even though Resource requires flush.
A more careful check
The hook above only tests whether the name close exists. The standard library uses a helper that also respects the convention of setting a method to None to opt out. For example, __hash__ = None marks a class as unhashable. This version follows that logic:
from abc import ABC, abstractmethod
def check_methods(klass, *names):
for name in names:
for base in klass.__mro__:
if name in base.__dict__:
if base.__dict__[name] is None:
return NotImplemented
break
else:
return NotImplemented
return True
class Closeable(ABC):
@abstractmethod
def close(self) -> None:
...
@classmethod
def __subclasshook__(cls, subclass):
if cls is Closeable:
return check_methods(subclass, "close")
return NotImplemented
class Connection:
def close(self) -> None:
print("connection closed")
class Locked:
close = None
class Odd:
close = "not callable"
print(issubclass(Connection, Closeable))
print(issubclass(Locked, Closeable))
print(issubclass(Odd, Closeable))The output is True, False, True. Locked is rejected because close = None is an explicit opt-out. Odd is accepted even though close is a string. The hook checks that a name exists, and nothing more.
This is the same pattern used by ABCs such as collections.abc.Iterable and collections.abc.Sized. Their hooks check for __iter__ and __len__, which is why isinstance([], Iterable) works for a list.
Limits of the hook
- No signature checks. The hook sees names, not parameters or return types. A
close(self, a, b, c)method passes. - Class attributes only. The hook inspects classes. If
closeis assigned in__init__, it lives on the instance, not in any class__dict__, soisinstancereturnsFalse. - No enforcement. A class that matches through the hook is not checked against the abstract methods. It does not appear in the MRO and inherits no mixin methods from the ABC.
- Cached results. Python caches the answers per ABC. If you add a method to a class after it was checked, the cached answer can be stale.
- Needs an ABC.
__subclasshook__is only consulted on classes whose metaclass isABCMeta. On a plain class, defining it has no effect onissubclass.
When to use it
Use a hook when you control an ABC that others will test against with isinstance, and you want unrelated classes to match without importing or registering anything. That is why the standard library uses it for small, single-method interfaces. For larger interfaces, the next chapter compares ABCs with typing.Protocol. A Protocol gives you the same structural matching, and static type checkers understand it without any hook code.
Exercise
Given the hook-based Closeable from this chapter (with the cls is Closeable guard), a class Report defines close only inside __init__ with self.close = lambda: None. What does isinstance(Report(), Closeable) return, and why? What changes if close is defined as a method in the class body?
Show answer
It returns False. The hook inspects class __dict__ entries along the MRO, and a function assigned to self.close lives in the instance __dict__, so the hook finds no close and returns NotImplemented. The normal checks then fail as well. If close is defined in the class body, the hook finds it and returns True.
Exercise
Write a hook-based ABC Sized2 that treats any class with a __len__ method as a subclass, but rejects any class that sets __len__ = None. Which return values would your hook use in each case?
Show answer
Define Sized2(ABC) with an abstract __len__, and a class method __subclasshook__(cls, subclass). Start with if cls is Sized2:. Walk subclass.__mro__ and find the first base whose __dict__ has __len__. If that value is None, return NotImplemented. If it is anything else, return True. If no base defines it, return NotImplemented. Outside the guard, also return NotImplemented. The check_methods helper from this chapter does exactly this: return check_methods(subclass, "__len__").