What's the canonical way to check for type in Python?
In Python, you can use the isinstance
function to check if an object is an instance of a particular type. For example:
def is_integer(x):
return isinstance(x, int)
print(is_integer(5)) # True
print(is_integer(5.5)) # False
print(is_integer("hello")) # False
Watch a video course
Python - The Practical Guide
Alternatively, you can use the type
function to check the type of an object. For example:
def is_integer(x):
return type(x) == int
print(is_integer(5)) # True
print(is_integer(5.5)) # False
print(is_integer("hello")) # False
Both of these approaches are correct, and you can choose the one that is most readable and maintainable for your code.