Skip to content
Tutorials Center
My learning

Topics

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.

Python
print(isinstance(3, int))            # True
print(isinstance("a", (int, str)))   # True

Try it

Python Types and subclasses

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.

Python The bool trap and abstract types

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

Python
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 bool subclasses int, isinstance(True, int) is True. Check bool first if the difference matters.
  • Tuples mean "any of". isinstance(x, (int, float)) is true if x is one of those. Since Python 3.10 you can write isinstance(x, int | float).
  • Prefer abstract types for behavior. collections.abc classes such as Iterable, Mapping and Sequence check what an object can do, not what it inherits from. Note that a str is an Iterable and a Sequence.
  • Exact type checks use type(x) is SomeClass. They are rarely what you want, since they reject subclasses.
  • Duck typing. Often try/except or hasattr() is more flexible than checking the type. Use isinstance() where the type genuinely decides what to do.
  • Typing helpers. Use the runtime class (list), not generics (list[int]). Protocols marked @runtime_checkable can 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. match with class patterns (case int():) performs an isinstance() check.