What's the canonical way to check a type in Python?


The canonical way to check for the type of an object in Python is to use the isinstance function. Isinstance checks if an object is an instance of a specified class or of a subclass thereof.

Here's an example:

def check_type(obj):
    if isinstance(obj, int):
        return "Integer"
    elif isinstance(obj, float):
        return "Float"
    elif isinstance(obj, str):
        return "String"
    else:
        return "Other"

print(check_type(42)) # Output: Integer
print(check_type(3.14)) # Output: Float
print(check_type("hello")) # Output: String
print(check_type([1, 2, 3])) # Output: Other
In this example, check_type is a function that takes an object 'obj' and returns a string indicating its type. The function uses the isinstance function to check if 'obj' is an instance of the int, float, or str classes, and returns a corresponding string if a match is found. If obj is not an instance of any of these classes, the function returns "Other".
Recommended Course

Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.