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"
        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

Learn Flask development and learn to build cool apps with our premium Python course on Udemy.

Subscribe to be the first to know when a new Python course is released.