liveBook · Manning

Isinstance

As explained in Python How-To

isinstance is a Python built-in function that tests whether an object is an instance of a specified class or tuple of classes, including subclasses.

Use isinstance(object, class_or_tuple) to test whether an object belongs to a class, any class in a tuple, or a superclass relationship. It is generally preferred over type for type checks because it supports inheritance. section 10.1.2

Choose the simplest check that matches the function's input contract:

  • Check one class, such as isinstance(4, int). section 10.1.2
  • Pass a tuple of classes to express an either-or check, such as isinstance(value, (list, tuple)). section 10.1.2
  • Prefer an abstract base class from collections.abc when multiple container types share an interface. section 10.1.3

Filtering by one urgency or several

A task filter can accept either one urgency value or a collection. Checking with isinstance keeps the branching explicit and extends naturally from list and tuple inputs to collection-like types. section 10.1.2 section 10.1.3

Listing 10.4 Checking an object’s type against an abstract class
from collections.abc import Collection

def filter_tasks(tasks, by_urgency):
   if isinstance(by_urgency, Collection):
       filtered = [x for x in tasks if x.urgency in by_urgency]
   else:
       filtered = [x for x in tasks if x.urgency == by_urgency]
   return filtered

Compare a generic Collection check with individual type checks when the function should accept list, tuple, set, or other types implementing the relevant interface. section 10.1.3

class User:
   pass

class Supervisor(User):
   pass

supervisor = Supervisor()

comparisons = [
   type(supervisor) is User,
   type(supervisor) is Supervisor,
   isinstance(supervisor, User),
   isinstance(supervisor, Supervisor)
]

print(comparisons)
# output: [False, True, True, True]

See how isinstance recognizes both a subclass instance and its superclass, unlike type's exact immediate-class comparison. section 10.1.2

How Python How-To covers it

How deep it goes
Explains single-class, tuple, inheritance-aware, and abstract-class checks through focused function examples.
Examples
Uses integer and list assertions, list-or-tuple arguments, task filtering, and User–Supervisor inheritance comparisons.
What it assumes
Assumes basic familiarity with Python objects and classes while distinguishing exact type comparison from inheritance-aware checking.
What you can do after
Apply isinstance to build runtime checks that tolerate subclasses, alternative classes, and collection-like inputs.
How it connects
Connects runtime type checking with type, class inheritance, abstract base classes, collections.abc, and interfaces.

Also explained in

Compare how 2 books explain isinstance →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.