Problem: What is the best way to check whether a given object is of a given type? For example, if you have a variable
object, how to check if it’s a
Check with Subclasses
Solution: To check if an
object is an instance of
str or any of its subclasses, use
if isinstance(o, str): print(o, 'is of type string')
Note that if the object inherits from string, the result of
isinstance(o, str) will also be
Here’s an example:
class Car: def speed(self): return 100 class Sportscar(Car): def speed(self): return 200 vw = Car() porsche = Sportscar() print(isinstance(vw, Car)) # True print(isinstance(porsche, Sportscar)) # True print(isinstance(porsche, Car)) # True --> Inherit being a Car from being a Sportscar
The example shows that the
vw is a
Car and the
porsche is a
Sportscar. However, as a
Sportscar inherits from
porsche is also a
However, you could argue that checking for type shouldn’t include checking for subclasses. So, in this example, the
porsche instance should not be a
Car. Let’s have a look how to accomplish this next!
Check without Subclasses
obj = 'hello' if type(obj) is str: print(obj, 'is of type string (it is not a subclass)')
The output is:
hello is of type string (it is not a subclass)
Similarly, if you use the same class example as before, the
porsche would now not be a
Car—even though it’s a
class Car: def speed(self): return 100 class Sportscar(Car): def speed(self): return 200 vw = Car() porsche = Sportscar() print(type(vw) is Car) # True print(type(porsche) is Sportscar) # True print(type(porsche) is Car) # False --> Inherit being a Car from being a Sportscar but is not of type Car
Resources: You may also enjoy to check out the following resources about Python typing:
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.