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

