Python Reference ยท Built-in Functions
Python isinstance() function
Reference for Python isinstance(): test whether an object is an instance of a class or tuple of classes, with subclasses, the bool trap and duck typing advice.
The isinstance() function returns True if an object is an instance of a class, or of any subclass of it. That is the main difference from type(obj) == SomeClass, which only matches the exact class.
It is the standard way to check types at run time, for example to accept either a string or a list of strings. Use it sparingly: Python code is usually clearer when it relies on behavior (duck typing) instead of checking types everywhere.
print(isinstance(3, int)) # True print(isinstance("a", (int, str))) # True
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
isinstance(object, classinfo)
| Name | Description |
|---|---|
object |
The value to test. |
classinfo |
A class, a tuple of classes, a union such as `int |
Return value: True or False.
Raises: TypeError if classinfo is not a class, tuple of classes, or union of classes. Subscripted generics like list[int] are not allowed.
Usage notes
- Subclasses count. Because
boolsubclassesint,isinstance(True, int)isTrue. Checkboolfirst if the difference matters. - Tuples mean "any of".
isinstance(x, (int, float))is true ifxis one of those. Since Python 3.10 you can writeisinstance(x, int | float). - Prefer abstract types for behavior.
collections.abcclasses such asIterable,MappingandSequencecheck what an object can do, not what it inherits from. Note that astris anIterableand aSequence. - Exact type checks use
type(x) is SomeClass. They are rarely what you want, since they reject subclasses. - Duck typing. Often
try/exceptorhasattr()is more flexible than checking the type. Useisinstance()where the type genuinely decides what to do. - Typing helpers. Use the runtime class (
list), not generics (list[int]). Protocols marked@runtime_checkablecan also be used and only check that the methods exist. - Custom behavior. A class can customize results through
__instancecheck__on its metaclass, which abstract base classes use. - Pattern matching.
matchwith class patterns (case int():) performs anisinstance()check.