Sub topic 11
Duck-typed checks with __subclasshook__
This chapter assumes you know how isinstance and issubclass work with ABCs and how register creates virtual subclasses. It also assumes you can read classmethods and decorators.
The problem with nominal checks
An ABC normally recognizes a class in one of two ways. The class inherits from it, or someone calls register on it. Both are explicit. A class that has the right methods but never mentions the ABC is rejected.
__subclasshook__ lets the ABC decide for itself. It is a classmethod that ABCMeta calls during issubclass and isinstance checks. Your code can inspect the candidate class and answer by its shape: does it have a close method?
Writing a 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")
class Resource(Closeable):
def close(self) -> None:
print("resource closed")
print(issubclass(Connection, Closeable))
print(isinstance(Connection(), Closeable))
print(issubclass(int, Closeable))
print(issubclass(Connection, Resource))The four lines print True, True, False and False.
Connectionnever inherits fromCloseable, yet the hook accepts it becausecloseappears in its class dictionary.- The code searches every class in
subclass.__mro__, not onlysubclass.__dict__. This way a class that inheritsclosefrom a parent also matches. inthas noclose, so the hook returnsNotImplemented. The normal checks then run and say no.
The three return values
| Return value | Meaning |
|---|---|
| `True` | The class counts as a subclass. No further checks run. |
| `False` | The class is not a subclass. No further checks run. |
| `NotImplemented` | The hook has no opinion. Normal checks continue. |
Normal checks look at the real inheritance chain, then at registered classes, then at the ABC's own subclasses. Return NotImplemented rather than False in most cases, so that explicit inheritance and register still work.
The `cls is Closeable` guard
Subclasses inherit classmethods, so Resource also gets this hook. Without the guard, issubclass(Connection, Resource) would return True, because Connection has close. That is wrong, since Resource may add its own requirements. With the guard, cls is Resource there and the hook returns NotImplemented. The result is False, as the last line of the example shows.
Limits to know
- Only names are checked. The hook does not verify signatures, argument counts or return types. A
closethat requires three arguments still passes. - No enforcement.
Connectionis never forced to implement anything. The instantiation check applies only to real subclasses, soConnection()works because it does not inherit fromCloseable. - Results are cached.
ABCMetaremembers earlier answers. Changing a class after it has been checked, such as adding a method later, may not change the result. - Non-callables can match.
close = Nonewould pass the__dict__test above. The standard library handles this by treating aNonevalue as "not implemented", which is howcollections.abc.Hashablerejects classes that set__hash__ = None.
Exercise
Why does the hook in Closeable start with if cls is Closeable, and what would go wrong without it?
Show answer
Subclasses inherit the classmethod, so cls can be a subclass such as Resource. Without the guard, any class with a close method would count as a subclass of Resource too, ignoring whatever else Resource requires. With the guard, subclasses return NotImplemented and fall back to the normal checks.
Exercise
A class Logger defines close(self, force, timeout), which needs two arguments. Does issubclass(Logger, Closeable) return True, and why?
Show answer
Yes. The hook checks only whether the name close exists in the class's MRO. It never inspects signatures, so the mismatch is not detected.