Home >Backend Development >Python Tutorial >How Can I Check the Type of an Object in Python?
Checking for Types in Python
Python provides multiple methods for verifying an object's type.
Using isinstance
isinstance determines if an object is an instance of a specified class or its subclasses. To check if an object o is of type str, use the following code:
if isinstance(o, str): # Code to execute if `o` is a string
Checking the Exact Type
To verify if an object's type is precisely str, excluding its subclasses, employ the type function:
if type(o) is str: # Code to execute if `o` is exactly of type `str`
Additional Notes
In Python 2, use isinstance(o, basestring) to check if an object is a string, as it encompasses both regular strings and Unicode strings. In Python 3, basestring is obsolete.
Alternatively, isinstance can accept a tuple of classes:
if isinstance(o, (str, unicode)): # Code to execute if `o` is an instance of `str` or `unicode`
The above is the detailed content of How Can I Check the Type of an Object in Python?. For more information, please follow other related articles on the PHP Chinese website!