Sub topic 6
Checking types with isinstance() and issubclass()
This chapter assumes you can define classes, create instances, write a subclass that inherits from a parent, and override a method. You should also know how attribute lookup works on a class and its parents. The chapter shows how to ask Python whether an object or a class belongs to an inheritance hierarchy. It also covers the common mistakes that come with those checks.
Why inheritance changes how you check types
Once you use inheritance, "what type is this object?" has two different meanings. One meaning is "what is the exact class that created it?" The other is "can I treat it as an instance of this class, because it is that class or one of its subclasses?"
A Dog is created from the class Dog. But a Dog is also an Animal, because Dog inherits from Animal. Code that accepts "any animal" should accept a Dog. Python gives you two built-in functions for the second meaning:
isinstance(obj, cls)asks whether an object is an instance of a class or of any subclass of it.issubclass(sub, cls)asks whether one class is the same as, or inherits from, another class.
The first works on objects. The second works on classes. Mixing them up is one of the most common errors, and it is covered later.
isinstance(): checking an object
The call isinstance(obj, cls) returns True if obj was created from cls or from any class that inherits from cls, directly or through several levels.
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
pass
d = Dog("Rex")
print(isinstance(d, Animal)) # True
print(isinstance(d, Dog)) # True
print(issubclass(Dog, Animal)) # True
print(type(d) is Animal) # FalseThe first line is True because Dog inherits from Animal. The second is True because every object is an instance of its own class. The last line shows the contrast. type(d) returns the exact class, Dog, so comparing it to Animal with is gives False.
Why isinstance() is usually better than type()
An exact comparison like type(d) is Animal ignores inheritance. If you write a function that checks type(x) is Animal, then it rejects every subclass. That defeats the purpose of inheritance, because a subclass is supposed to work anywhere its parent works.
Here is a function that makes this mistake:
class Animal:
pass
class Dog(Animal):
pass
def describe_exact(x):
if type(x) is Animal:
return "an animal"
return "not an animal"
def describe_inherited(x):
if isinstance(x, Animal):
return "an animal"
return "not an animal"
rex = Dog()
print(describe_exact(rex)) # not an animal
print(describe_inherited(rex)) # an animaldescribe_exact says a Dog is not an animal. That is wrong for the design. Use type(x) is SomeClass only when you really need the exact class, for example in a debugging message or when you must exclude subclasses on purpose. In most other code, use isinstance().
issubclass(): checking a class
issubclass(sub, cls) compares two classes. It returns True when sub is cls or inherits from it, at any depth.
class Animal:
pass
class Dog(Animal):
pass
class Puppy(Dog):
pass
print(issubclass(Puppy, Dog)) # True
print(issubclass(Puppy, Animal)) # True (two levels up)
print(issubclass(Dog, Puppy)) # False (the relation is not symmetric)
print(issubclass(Dog, Dog)) # True (a class is a subclass of itself)
print(issubclass(Dog, object)) # True (every class inherits from object)Three points are worth remembering:
- The relation is one-way.
Puppyis a subclass ofDog, butDogis not a subclass ofPuppy. - A class counts as a subclass of itself. This matches how
isinstance()treats an object and its own class. - Every class in Python 3 inherits from
object, soissubclass(anything, object)is alwaysTrue.
Passing an object instead of a class
issubclass() needs a class as its first argument. If you pass an instance, Python raises a TypeError.
class Animal:
pass
class Dog(Animal):
pass
rex = Dog()
try:
issubclass(rex, Animal)
except TypeError as exc:
print("TypeError:", exc)
print(issubclass(type(rex), Animal)) # True
print(isinstance(rex, Animal)) # TrueThe error message reads issubclass() arg 1 must be a class. If you have an object, either use isinstance() or get its class first with type(rex).
How the two functions relate
For ordinary classes, isinstance(obj, cls) gives the same answer as issubclass(type(obj), cls). The two are close relatives. They differ in what they take as input.
| Question | Function | First argument |
|---|---|---|
| Is this object an instance of this class or a subclass of it? | `isinstance(obj, cls)` | an object |
| Does this class inherit from (or equal) that class? | `issubclass(sub, cls)` | a class |
| Is this object's exact class this one? | `type(obj) is cls` | an object |
The relation isinstance(obj, cls) == issubclass(type(obj), cls) holds for ordinary classes. Python also lets a class customize both checks (see the section on abstract base classes below), so the equality is not guaranteed for every class.
The object at the bottom is an instance of Puppy. Because Puppy inherits from Dog, and Dog inherits from Animal, isinstance(obj, Puppy), isinstance(obj, Dog), and isinstance(obj, Animal) are all True.
Checking against several classes at once
The second argument of both functions can be a tuple of classes. The check passes if the object or class matches any one of them.
class Cat:
pass
class Dog:
pass
class Fish:
pass
pet = Dog()
print(isinstance(pet, (Cat, Dog))) # True
print(isinstance(pet, (Cat, Fish))) # False
print(issubclass(Dog, (Cat, Dog))) # TrueThe tuple must contain classes, not strings and not a list. A list raises a TypeError. A tuple is the correct container here.
class Dog:
pass
try:
isinstance(Dog(), [int, Dog])
except TypeError as exc:
print("TypeError:", exc)Since Python 3.10 you can also write the union form isinstance(x, int | str). A tuple works in every Python 3 version, so use it when you need older versions.
Common edge cases
bool is a subclass of int
Built-in types take part in inheritance too. bool inherits from int, so True and False count as integers.
print(isinstance(True, int)) # True
print(issubclass(bool, int)) # True
print(isinstance(1, bool)) # False
print(type(True) is int) # FalseThis surprises people who validate input. A function that accepts "an int" with isinstance(x, int) also accepts True. If you must reject booleans, check for them first:
def is_plain_int(x):
return isinstance(x, int) and not isinstance(x, bool)
print(is_plain_int(5)) # True
print(is_plain_int(True)) # FalseEvery object is an instance of object
isinstance(x, object) is True for any value, so it never filters anything out. It is rarely useful.
Checking a class against itself
isinstance(Dog, Dog) is False, because Dog the class is an instance of type, not of Dog. If you want to ask a question about a class, use issubclass().
class Dog:
pass
print(isinstance(Dog, Dog)) # False
print(isinstance(Dog, type)) # True
print(issubclass(Dog, Dog)) # TrueUsing isinstance() in practice
A common use is validating input at the edge of a function, where a wrong type should fail with a clear message.
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
pass
class Robot:
def __init__(self, name):
self.name = name
def greet(animal):
if not isinstance(animal, Animal):
raise TypeError(f"expected an Animal, got {type(animal).__name__}")
return f"Hello, {animal.name}"
print(greet(Dog("Rex"))) # Hello, Rex
try:
greet(Robot("R2"))
except TypeError as exc:
print("TypeError:", exc) # expected an Animal, got Robotgreet accepts an Animal and every subclass of it. It rejects Robot, which is unrelated. The error message uses type(animal).__name__ to name the actual class, which is exactly where an exact type is the right tool.
Avoid long isinstance() chains
A second common use is branching on type. A chain like this works, but it grows each time you add a class:
class Circle:
def __init__(self, r):
self.r = r
class Square:
def __init__(self, side):
self.side = side
def area(shape):
if isinstance(shape, Circle):
return 3.14159 * shape.r ** 2
elif isinstance(shape, Square):
return shape.side ** 2
raise TypeError("unknown shape")
print(area(Square(3))) # 9Every new shape forces you to edit area. Overriding a method on each class removes that need, because the call shape.area() picks the right version by itself. The next chapter, on polymorphism, covers that approach. Treat a long isinstance chain as a hint that a method override may fit better.
Customizing the checks with abstract base classes
The built-in functions ask the class itself how to answer. A class can customize the result through special methods on its metaclass, __instancecheck__ and __subclasscheck__. The classes in the abc module use them.
An abstract base class can register an unrelated class as a "virtual subclass". The registered class does not inherit anything, yet issubclass() and isinstance() report True.
from abc import ABC
class Speaker(ABC):
pass
class Parrot:
pass
Speaker.register(Parrot)
print(issubclass(Parrot, Speaker)) # True
print(isinstance(Parrot(), Speaker)) # True
print(Speaker in Parrot.__mro__) # FalseThe last line shows the catch. Speaker is not in the method resolution order of Parrot, so Parrot inherits no methods from it. The checks say yes, but the behavior is not inherited. Registration is a promise you make about the class, and Python does not verify it.
The standard library relies on this feature. For example, isinstance([], collections.abc.Sequence) is True even though list does not inherit from Sequence in the usual way.
from collections.abc import Sequence, Mapping
print(isinstance([1, 2], Sequence)) # True
print(isinstance({"a": 1}, Mapping)) # True
print(isinstance("text", Sequence)) # TrueChecking against collections.abc classes is better than checking against list or dict when you only need a behavior, such as "something I can index and iterate".
Common mistakes
- Using
type(x) == Clsto check inheritance. It rejects subclasses. Useisinstance()unless you truly need the exact class. - Passing an instance to
issubclass(). It raisesTypeError. Pass a class, or useisinstance()for an object. - Passing a list as the second argument. Use a tuple of classes, or a
|union on Python 3.10 and later. - Forgetting that
boolis anint. Check forboolfirst when you need a plain integer. - Branching on type instead of overriding. If you find yourself adding a new
elif isinstance(...)for every subclass, move that behavior into a method. - Treating a registered virtual subclass as inherited. The checks pass, but no methods or attributes come along.
Summary
isinstance(obj, cls)isTruewhenobjcomes fromclsor any subclass ofcls.issubclass(sub, cls)compares two classes and counts a class as a subclass of itself.type(obj) is clschecks the exact class and ignores inheritance.- Both functions accept a tuple of classes as the second argument.
- Built-in types follow the same rules, so
boolcounts as anint. - Abstract base classes can make the checks return
Truewithout real inheritance.
Exercise
Given class Animal: pass, class Dog(Animal): pass, class Puppy(Dog): pass and p = Puppy(), what do isinstance(p, Animal), type(p) is Dog, issubclass(Animal, Puppy) and issubclass(Puppy, (int, Dog)) return?
Show answer
isinstance(p, Animal) is True, because Puppy inherits from Dog, which inherits from Animal. type(p) is Dog is False, because the exact class of p is Puppy. issubclass(Animal, Puppy) is False, because the relation runs only from child to parent. issubclass(Puppy, (int, Dog)) is True, because Puppy is a subclass of Dog and a tuple passes if any entry matches.
Exercise
A function double(x) is meant to accept only real integers. It uses isinstance(x, int), yet double(True) returns 2 instead of raising an error. Why does this happen, and how do you fix it?
Show answer
bool is a subclass of int, so isinstance(True, int) is True. Add an explicit rejection of booleans: isinstance(x, int) and not isinstance(x, bool). Alternatively, compare the exact class with type(x) is int, which also rejects subclasses of int.