isinstance is a Python built-in function used to test whether or not a specific object is an instance of a particular class or type. It is available in both versions 2 and 3. Use this tag for questions explicitly dealing with the isinstance built-in.
isinstance
is a Python built-in function used to test whether or not a specific object is an instance of a particular class or type. It is available in both versions 2 and 3. Use this tag for questions explicitly dealing with the isinstance built-in.
The schematics for the function are below:
isinstance(object, class-or-type-or-tuple) -> bool
where object
is the object to test and class-or-type-or-tuple
is a class, type, or tuple of classes and/or types.
When invoked, and given a single class or type as its second argument, the function will return either True
or False
depending on whether or not the first argument is an instance of the second. Below is a demonstration:
>>> isinstance(1, int)
True
>>> isinstance(1, str)
False
>>>
If the function is given a tuple of classes and/or types as its second argument, it will return either True
or False
depending on whether or not the first argument is an instance of any of the classes/types contained in the tuple. Below is a demonstration:
>>> isinstance('a', (int, str))
True
>>> isinstance('a', (int, bool))
False
>>>
It should also be noted that the following code:
isinstance('a', (int, str))
is equivalent to this:
isinstance('a', int) or isinstance('a', str)