Sub topic 6
Checking types with isinstance() and issubclass()
This chapter assumes you can define classes, create instances, and write a subclass that inherits from a parent. You should also be comfortable with print and f-strings. Here you learn how to ask Python whether an object or a class belongs to an inheritance family, and which of the two ways of checking is usually right.
Two questions, two functions
Inheritance creates an "is a" relationship. A Dog is an Animal. Python gives you two built-in functions to test this relationship:
isinstance(obj, cls)asks whether an object is an instance of a class or of any subclass of it.issubclass(sub, cls)asks whether a class is the same as, or inherits from, another class.
The first works on objects. The second works on classes.
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 d was built from Dog, and Dog inherits from Animal. The last line is False because type(d) returns the exact class, which is Dog. An exact comparison ignores inheritance.
Why isinstance() is usually the better test
Compare these two checks:
type(x) is Animalis true only whenxwas created directly fromAnimal.isinstance(x, Animal)is true forAnimaland every subclass.
If you write the first form, your code stops working the moment someone passes in a Dog. That defeats the purpose of inheritance, because a subclass is meant to be usable wherever its parent is expected. Prefer isinstance() unless you really need the exact class.
Checking against several classes
Both functions accept a tuple of classes as the second argument. The result is True if any of them match.
class Animal:
pass
class Dog(Animal):
pass
class Cat(Animal):
pass
class Robot:
pass
pets = [Dog(), Cat(), Robot()]
for item in pets:
print(type(item).__name__, isinstance(item, (Dog, Cat)))
print(issubclass(Cat, (Dog, Animal))) # True
print(issubclass(Robot, Animal)) # FalseThe output is:
Dog True
Cat True
Robot False
True
FalseCommon errors
Passing an instance to issubclass(). issubclass() needs a class as its first argument. Passing an object raises 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)) # TrueIf you only have an object, use isinstance(), or call type(obj) first.
Treating a class as a subclass of itself incorrectly. issubclass(Dog, Dog) is True. Python counts a class as a subclass of itself. Likewise, isinstance(Dog(), Dog) is True.
Checking types instead of using polymorphism. A long chain of if isinstance(...) branches is often a sign of a design problem. If each branch calls a different behavior, define a method on each class and let overriding choose the right one. Chapter 7 covers this. Type checks fit best at boundaries, such as validating input, and not as a replacement for overridden methods.
Using the check for input validation
A good use of isinstance() is rejecting wrong input early with a clear error.
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
pass
def adopt(animal):
if not isinstance(animal, Animal):
raise TypeError(f"Expected an Animal, got {type(animal).__name__}")
return f"{animal.name} has been adopted"
print(adopt(Dog("Rex")))
try:
adopt("Rex")
except TypeError as exc:
print("TypeError:", exc)adopt() accepts an Animal or any subclass, and rejects everything else with a message that names the wrong type.
Exercise
Given class Animal: pass and class Dog(Animal): pass, and d = Dog(), what do isinstance(d, Animal), type(d) is Animal, and issubclass(Animal, Dog) return, and why?
Show answer
They return True, False, and False. isinstance(d, Animal) is True because d is a Dog, and Dog inherits from Animal. type(d) is Animal is False because type(d) is exactly Dog, and this check ignores inheritance. issubclass(Animal, Dog) is False because inheritance runs one way: Dog is a subclass of Animal, but Animal is not a subclass of Dog.
Exercise
Why does issubclass(Dog(), Animal) raise a TypeError, and how do you fix it?
Show answer
issubclass() expects a class as its first argument, and Dog() is an instance. Use isinstance(Dog(), Animal) to test the object, or issubclass(Dog, Animal) to test the class.