Sub topic 8
Using isinstance and issubclass with ABCs
This chapter assumes you can define classes with inheritance, know how @abstractmethod blocks instantiation, and can read try/except. It covers how isinstance and issubclass behave when the second argument is an abstract base class (ABC), how that differs from plain classes, and where the checks mislead.
Why ABCs change the meaning of the checks
For ordinary classes, isinstance(obj, C) asks one question: is C in the inheritance chain of type(obj)? An ABC lets the class answer for itself. ABCMeta, the metaclass behind ABC, defines two hooks:
ABCMeta.__instancecheck__runs when you callisinstance(obj, SomeABC).ABCMeta.__subclasscheck__runs when you callissubclass(cls, SomeABC).
isinstance delegates to the subclass check, so the real logic lives in one place. You rarely call these hooks yourself. You use isinstance and issubclass as usual and let the ABC decide.
The basics: real subclasses
With real inheritance, ABCs behave like normal classes. The abstract class itself cannot be instantiated, but it works fine as the second argument of a check.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self) -> float:
"""Return the area."""
class Rectangle(Shape):
def __init__(self, width: float, height: float) -> None:
self.width = width
self.height = height
def area(self) -> float:
return self.width * self.height
class Square(Rectangle):
def __init__(self, side: float) -> None:
super().__init__(side, side)
shape = Square(2)
print(isinstance(shape, Square))
print(isinstance(shape, Rectangle))
print(isinstance(shape, Shape))
print(issubclass(Square, Shape))
print(issubclass(Shape, Shape))
print(isinstance(3, Shape))
print(isinstance(shape, (int, Shape)))This prints True for every line except isinstance(3, Shape), which prints False. Three details are worth noting:
- A class is a subclass of itself, so
issubclass(Shape, Shape)isTrue. - Passing a tuple works as with any class: the check succeeds if any member matches.
- The check looks at inheritance only.
Shapenever confirms thatSquareimplementsareacorrectly. Instantiation already enforced that.
How the answer is computed
When issubclass(Candidate, SomeABC) runs, ABCMeta works through several sources of evidence in a fixed order.
The table below lists the same steps with what each one means.
| Step | Source of evidence | Where it comes from |
|---|---|---|
| 1 | Cache | Earlier answers, stored in weak sets |
| 2 | `__subclasshook__` | A classmethod on the ABC. It may return `True`, `False` or `NotImplemented` |
| 3 | Inheritance | `SomeABC` appears in `Candidate.__mro__` |
| 4 | Registry | `SomeABC.register(...)` was called for `Candidate` or one of its bases |
| 5 | Subclass tree | `Candidate` descends from a known subclass of `SomeABC` |
Steps 2 and 4 are what separate ABCs from plain classes. The later chapters on register and __subclasshook__ cover them in detail. For now, remember that a True answer does not always mean inheritance.
For isinstance, ABCMeta also looks at obj.__class__, not only type(obj). A proxy object can set __class__ to report another type, and isinstance will honor it.
ABCs from collections.abc
The most common place you meet these checks is collections.abc. It provides ABCs such as Iterable, Sized, Sequence and Mapping. Built-in types satisfy them without inheriting from them. Some do so through register (for example, dict is registered as a MutableMapping). Others do so through __subclasshook__ (for example, anything with __len__ counts as Sized).
from collections.abc import Iterable, Mapping, Sequence, Sized
print(isinstance([1, 2], Sequence))
print(isinstance((1, 2), Sequence))
print(isinstance("abc", Sequence))
print(isinstance({"a": 1}, Mapping))
print(isinstance({"a": 1}, Sequence))
print(isinstance(iter([]), Iterable))
print(isinstance(5, Sized))
print(issubclass(dict, Mapping))
print(issubclass(list, Mapping))The output is True for the first four lines, then False, True, False, True and False. Look at the third line: a str is a Sequence. Strings support indexing and length, and str is registered as a Sequence. This surprises many people, and it matters whenever you want to accept "a list of things" but not a string.
A practical pattern: accept collections, treat strings as single values
from collections.abc import Iterable
def as_list(value):
if isinstance(value, (str, bytes)):
return [value]
if isinstance(value, Iterable):
return list(value)
return [value]
print(as_list("abc"))
print(as_list((1, 2)))
print(as_list(7))
print(as_list({"a": 1}))The output is:
['abc']
[1, 2]
[7]
['a']The str and bytes check comes first because both are iterable and would otherwise be split into characters or integers. Testing against the abstract Iterable is better than testing isinstance(value, (list, tuple)). It also accepts sets, generators, dictionary views and your own iterable classes.
The last line shows a side effect of that flexibility. A dictionary is iterable, so you get its keys. If keys are not what you want, test for Mapping earlier in the function.
Errors and limits
The first argument of issubclass must be a class
isinstance accepts any object, but issubclass requires a class as its first argument.
from collections.abc import Mapping
try:
issubclass({"a": 1}, Mapping)
except TypeError:
print("issubclass needs a class, not an instance")
print(issubclass(type({"a": 1}), Mapping))This prints the message and then True. If you hold an instance, use isinstance, or pass type(obj).
Parameterized generics are not allowed
You can write Mapping[str, int] in a type hint, but not in a runtime check.
from collections.abc import Mapping
try:
isinstance({"a": 1}, Mapping[str, int])
except TypeError:
print("cannot check against a subscripted generic")
print(isinstance({"a": 1}, Mapping))Python cannot verify the key and value types without scanning the contents. Check against the bare ABC, then validate the contents yourself if you need to.
The check does not inspect implementations
Instantiation checks apply only to real subclasses. Treat the isinstance result as a claim of membership, not proof that every method works.
Results are cached
ABCMeta caches positive and negative answers. Calling SomeABC.register(...) invalidates the negative cache, so new registrations take effect. Changing a class after the fact, such as adding a method to a class that a __subclasshook__ already rejected, may not be noticed. Avoid patching classes at runtime when ABC checks are involved.
When to use these checks
Type checks and duck typing pull in different directions. Python's usual style is to call the method and handle failure (EAFP, "easier to ask forgiveness than permission"). ABC checks are the right tool in a few cases:
- You must branch on the kind of input, as in
as_listabove, where a string and a list need different handling. - You are validating input at a boundary, such as a public function or a configuration loader, and want a clear error early.
- You are writing a registry or dispatcher that selects a handler by type.
Inside a class hierarchy you control, a chain of isinstance calls to pick behavior is usually a sign that the behavior belongs in a method on the classes. Put the variation in an abstract method and let each subclass implement it.
Summary of behavior
isinstanceandissubclasscallABCMetahooks, so an ABC can say yes to classes that do not inherit from it.- The abstract class works in checks even though you cannot instantiate it.
- A tuple of types works as usual.
issubclassneeds a class as its first argument, and neither function accepts subscripted generics.- A
Trueresult is a membership claim. It does not prove the abstract methods exist or work. strandbytescount asSequence, so handle them first when you want to treat them as single values.
Exercise
A function receives either one filename or a collection of filenames and must always loop over a collection of names. A colleague writes names = value if isinstance(value, Sequence) else [value] using collections.abc.Sequence. What goes wrong when the caller passes "report.txt", and how do you fix it?
Show answer
A str is registered as a Sequence, so "report.txt" passes the check and the loop iterates over single characters. Test for str (and bytes if needed) first: names = [value] if isinstance(value, (str, bytes)) else list(value), or check isinstance(value, str) before the Sequence test.
Exercise
You define class Closeable(ABC) with an abstract close method and call Closeable.register(Report), where Report has no close method. What do issubclass(Report, Closeable) and Report() do, and what does this show about the check?
Show answer
issubclass(Report, Closeable) returns True and Report() succeeds without a TypeError, because registered classes are not checked for the abstract methods. It shows that a True result from isinstance or issubclass is a claim of membership, not a guarantee that the interface is implemented.