Use isinstance(obj, ExpectedType) (or isinstance(obj, (TypeA, TypeB)) / TypeA | TypeB in Python 3.10+) to check an object’s data type—which respects inheritance and virtual subclasses (collections.abc), reserving type(obj) is ExactType only for rare cases where subclasses must be explicitly rejected.
Basic Example
from collections.abc import Sequence
value = 42
items = [1, 2, 3]
# 1. Recommended: isinstance() checks exact type AND subclasses
print(isinstance(value, int)) # Output: True
print(isinstance(items, (list, tuple))) # Output: True (tuple of types)
print(isinstance(items, list | tuple)) # Output: True (Python 3.10+ union syntax)
# 2. Check abstract behavior rather than concrete type (e.g., any Sequence except str/bytes)
print(isinstance(items, Sequence)) # Output: True
# 3. Exact type check ONLY when subclasses must be excluded (`bool` is a subclass of `int`!)
flag = True
print(isinstance(flag, int)) # Output: True (`bool` subclasses `int`)
print(type(flag) is int) # Output: False (strictly `int` only)
Key Details & Edge Cases
- Why
isinstance()is strongly preferred overtype(x) == ...:isinstance(obj, cls)returnsTruefor instances ofcls, any subclass ofcls, and any class registered with an Abstract Base Class (ABC) likecollections.abc.MappingorIterable.- Using
type(obj) == listbreaks polymorphism—failing on customlistsubclasses, mock objects, and wrapped types.
- The
boolis a subclass ofintgotcha (isinstance(True, int) == True):- In Python,
issubclass(bool, int)isTrue(True == 1andFalse == 0). When validating JSON payloads, API parameters, or numeric inputs whereTrue/Falsemust not be accepted as integers, explicitly excludebool:is_strict_int = isinstance(x, int) and not isinstance(x, bool)
- In Python,
- Checking
None(x is None, NOTisinstance(x, type(None))):Noneis a guaranteed singleton in Python. Always check identity withx is Noneorx is not None(faster and cleaner per PEP 8).
- Prefer Duck Typing (EAFP) over rigid type checks when writing Pythonic functions:
- Instead of rejecting valid custom objects with
if not isinstance(data, list):, iterate or call the expected interface directly insidetry ... except TypeError:—or check against an abstract interface (isinstance(data, collections.abc.Iterable)) so tuples, generators, NumPy arrays, and custom containers all work seamlessly.
- Instead of rejecting valid custom objects with
- Checking generic types (
isinstance(x, list[int])raisesTypeError):- Parameterized generic types like
list[int]ordict[str, int]cannot be used directly insideisinstance()(raisesTypeError: Subscripted generics cannot be used with class and instance checks). Check the unparameterized container type (isinstance(x, list)) and validate elements separately if needed.
- Parameterized generic types like
Comparison of Type-Checking Approaches in Python
| Approach | Syntax | Supports Inheritance & ABCs? | Accepts bool for int? |
Best Used When |
|---|---|---|---|---|
isinstance(obj, T) |
isinstance(x, int | float) |
Yes | Yes (True is int) |
Standard runtime type validation across built-in, custom, and union types. |
isinstance(obj, ABC) |
isinstance(x, Mapping) |
Yes (structural/ABC) | N/A | Checking interface capabilities (e.g., any dict-like Mapping or Iterable). |
type(obj) is T |
type(x) is dict |
No (exact class only) | No (type(True) is int is False) |
Serialization/metaprogramming where subclasses must be handled differently. |
Identity Check (is None) |
x is None |
N/A | N/A | Checking whether a value is None (PEP 8 standard). |
| Structural Pattern Matching | match x: case int(): ... |
Yes (isinstance semantics) |
Yes | Dispatching across multiple types and destructuring shapes in Python 3.10+. |
You must log in or register to comment.
