What’s the Standard Way to Check for Type in Python?

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 string?

Check with Subclasses

Solution: To check if an object is an instance of str or any of its subclasses, use isinstance:

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 True.

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 Car, the porsche is also a Car.

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

Solution 2: To check if an object is an instance of str, excluding subclasses, use Python’s built-in function type(object) and check if it’s the same as str using the keyword is.

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 Sportscar!

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: