Sub topic 8
Using isinstance and issubclass with ABCs
This chapter assumes you can write classes with inheritance, know how try/except works, and have seen @abstractmethod on a base class. Here you will see how isinstance and issubclass behave when the second argument is an abstract base class (ABC), and where those checks can mislead you.
What an ABC changes about type checks
With a normal class, isinstance(obj, Cls) is true when Cls appears in the MRO (method resolution order) of type(obj). ABCMeta, the metaclass behind ABC, overrides this. It adds two hooks, __instancecheck__ and __subclasscheck__, which let the ABC answer the question itself. isinstance(obj, Shape) calls Shape.__instancecheck__(obj). That call ends up in issubclass(type(obj), Shape).
For the classes you write yourself, the first branch is the one that matters. Registration and __subclasshook__ get their own chapters.
Checking your own ABCs
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self) -> float:
"""Return the area of the shape."""
class Square(Shape):
def __init__(self, side: float) -> None:
self.side = side
def area(self) -> float:
return self.side ** 2
class Incomplete(Shape):
pass
print(isinstance(Square(2), Shape))
print(issubclass(Square, Shape))
print(issubclass(Incomplete, Shape))
print(issubclass(int, Shape))This prints True, True, True, False. The third line surprises many people. issubclass only looks at the class hierarchy. It does not check whether the abstract methods are implemented. Incomplete is a subclass of Shape, but you can never create an instance of it. The instantiation check is what raises TypeError, not issubclass.
Checking against collections.abc
The standard library uses ABCs so you can test for a capability instead of a concrete type. A function that accepts "any mapping" should not insist on dict.
from collections.abc import Iterable, Mapping, Sequence
def describe(value) -> str:
if isinstance(value, Mapping):
return f"mapping with {len(value)} entries"
if isinstance(value, str):
return "text"
if isinstance(value, Sequence):
return f"sequence of {len(value)} items"
if isinstance(value, Iterable):
return "some other iterable"
return "a single value"
samples = [{"a": 1}, "hi", [1, 2, 3], (4, 5), {1, 2}, (n for n in range(3)), 42]
for sample in samples:
print(describe(sample))The output is:
mapping with 1 entries
text
sequence of 3 items
sequence of 2 items
some other iterable
some other iterable
a single valueThe order of the checks matters. A str is also a Sequence, so it must be tested first if you want to treat text differently from lists and tuples. A set is Iterable but not a Sequence, because it has no stable order or indexing.
Common errors
- Assuming
issubclassverifies the interface. It does not check that abstract methods are implemented, as theIncompleteexample shows. - Passing an instance to
issubclass.issubclass(Square(2), Shape)raisesTypeError: issubclass() arg 1 must be a class. Useisinstancefor objects andissubclassfor classes. - Checking
isinstanceon every call in a hot loop. An ABC check is slower than a plain class check.ABCMetacaches results, but it is still more work thantype(x) is dict. - Using an ABC check as a guarantee.
isinstance(x, Sequence)tells you what the class declares. It does not prove thatxbehaves well.
Prefer ABC checks over concrete types when you only need a capability. Use Mapping instead of dict, and Iterable instead of list. Often it is better still to skip the check and call the method, handling TypeError or AttributeError if it fails.
Exercise
Given class Shape(ABC) with an abstract area method and class Incomplete(Shape): pass, what do issubclass(Incomplete, Shape) and isinstance(Incomplete(), Shape) evaluate to?
Show answer
issubclass(Incomplete, Shape) is True, because Incomplete inherits from Shape. The expression Incomplete() raises TypeError before isinstance runs, since the abstract method area is not implemented. The subclass check looks only at the hierarchy. The instantiation check enforces the abstract methods.
Exercise
In the describe function, what changes if you move the Sequence check above the str check, and why?
Show answer
Strings would be reported as "sequence of N items" instead of "text". str is registered as a Sequence, so the first matching branch wins.