---
title: Use isinstance() Instead of type() for Type Checking
impact: MEDIUM
impactDescription: Using type() == for type checks breaks polymorphism and inheritance, rejecting valid subclass instances that should be accepted by the contract.
tags: python, typing, isinstance, quality, oop
---

## Use isinstance() Instead of type() for Type Checking

The `type(x) == SomeClass` pattern performs an exact type match and does not account for subclasses. This violates the Liskov Substitution Principle: code that accepts a `list` should also accept `UserList` or any other list subclass.

Use `isinstance()` which checks the full MRO (method resolution order) and correctly handles subclasses and abstract base classes.

**Incorrect:**
```python
def process(data):
    if type(data) == list:    # rejects OrderedList, UserList, etc.
        for item in data:
            handle(item)
    if type(data) == dict:    # rejects defaultdict, OrderedDict, etc.
        process_mapping(data)

def serialize(value):
    if type(value) == str:    # rejects str subclasses
        return value.encode("utf-8")
```

**Correct:**
```python
def process(data):
    if isinstance(data, list):    # accepts all list subclasses
        for item in data:
            handle(item)
    if isinstance(data, dict):    # accepts defaultdict, OrderedDict, etc.
        process_mapping(data)

def serialize(value):
    if isinstance(value, str):
        return value.encode("utf-8")

# Use abstract base classes for duck typing
from collections.abc import Mapping, Sequence

def process_generic(data):
    if isinstance(data, Sequence):  # list, tuple, str, UserList, etc.
        for item in data:
            handle(item)
    if isinstance(data, Mapping):   # dict, defaultdict, ChainMap, etc.
        process_mapping(data)
```

**Exception — when exact type match IS needed:**
```python
# Only use type() == when you explicitly want to exclude subclasses
# e.g., in a serialization library distinguishing bool from int:
if type(value) is bool:  # True/False, not int subclasses
    return str(value).lower()
```

**Tools:** Ruff `E721` (type-comparison), Pylint `C0123` (unidiomatic-typecheck), mypy, pyright
