Python is a “dynamically typed language,” meaning you don’t need to specify types when declaring variables. Therefore, you might encounter situations where you want to check “what kind of data is currently in this variable” or perform conditional branching like “perform calculation only if it’s a number.”
Python provides two main built-in functions for handling types: type() and isinstance(). While used for similar purposes, they have a decisive difference in how they handle inheritance.
This article explains their basic usage and key differences.
1. type() Function: Getting the Type Itself
The type() function returns the “type (class)” of the object passed as an argument. It is mainly used for debugging to display the variable type on the console.
Syntax:
type(object)
Example: Checking types of integers, strings, lists, and a custom class instance.
# Integer (int)
user_age = 25
print(f"Type of user_age: {type(user_age)}")
# String (str)
user_name = "Tanaka"
print(f"Type of user_name: {type(user_name)}")
# List (list)
item_list = [100, 200, 300]
print(f"Type of item_list: {type(item_list)}")
# Custom Class
class Product:
pass
# Instantiation
laptop = Product()
print(f"Type of laptop: {type(laptop)}")
Output:
Type of user_age: <class 'int'>
Type of user_name: <class 'str'>
Type of item_list: <class 'list'>
Type of laptop: <class '__main__.Product'>
As shown, it returns the class information in the format <class 'TypeName'>.
2. isinstance() Function: Checking for a Specific Type
The isinstance() function checks if an object is of a “specific type (class)” and returns True or False. It is generally used for conditional branching in programs, like “if it’s a string, do A; if it’s a number, do B.”
Syntax:
isinstance(object, type)
Example: Checking if a variable is an integer or a list.
# Check for integer
score = 85
is_integer = isinstance(score, int)
print(f"Is score an int?: {is_integer}")
# Check for string
message = "Hello"
is_string = isinstance(message, str)
print(f"Is message a str?: {is_string}")
# Check for different type
# Asking "Is it an int?" for a string
is_score_int = isinstance(message, int)
print(f"Is message an int?: {is_score_int}")
Output:
Is score an int?: True
Is message a str?: True
Is message an int?: False
You can also check against multiple types by passing a tuple as the second argument, like isinstance(x, (int, float)), which means “True if it’s an integer OR a float.”
3. The Most Important Difference: Handling Inheritance
The biggest difference between type() and isinstance() is whether they consider class inheritance.
type(): Looks only at the strict type of the object. A parent class (superclass) is treated as a “different type.”isinstance(): Checks if the object is an instance of that class OR an instance of a subclass (child class) that inherits from it.
Specific Code Example
Let’s compare the behavior using a “Vehicle” class and a “Car” class that inherits from it.
# Parent Class
class Vehicle:
pass
# Child Class (Inherits from Vehicle)
class Car(Vehicle):
pass
# Create instances of each
my_vehicle = Vehicle()
my_car = Car()
print("--- With isinstance() (Considers Inheritance) ---")
# A Car instance is considered both a Car type AND a Vehicle type
print(f"Is my_car a Car?: {isinstance(my_car, Car)}")
print(f"Is my_car a Vehicle?: {isinstance(my_car, Vehicle)}")
print("\n--- With type() (Strict Match) ---")
# A Car instance matches Car type, but does NOT match Vehicle type
print(f"Is my_car a Car?: {type(my_car) is Car}")
print(f"Is my_car a Vehicle?: {type(my_car) is Vehicle}")
Output:
--- With isinstance() (Considers Inheritance) ---
Is my_car a Car?: True
Is my_car a Vehicle?: True
--- With type() (Strict Match) ---
Is my_car a Car?: True
Is my_car a Vehicle?: False
isinstance() correctly recognizes the inheritance relationship “A car is a type of vehicle” and returns True, whereas type() treats “Car class” and “Vehicle class” as different things and returns False.
Summary: Usage Guidelines
In Python programming, it is generally recommended to use isinstance(). This is because if you extend functionality by creating a subclass in the future, existing code (designed for the parent class) will continue to work for the subclass if isinstance() is used (Polymorphism).
type(): Use for debugging to display type names, or in special cases where you strictly want to target only instances of that exact class, ignoring inheritance.isinstance(): The standard choice for type checking in conditional branching.
