pydantic/pydantic · error · TypeError

Unexpected type of exclude value {class_name}

Error message

Unexpected type of exclude value {class_name}

What it means

A `TypeError` from `ValueItems._coerce_items`, raised when the top-level `include`/`exclude` argument is neither a Mapping (dict) nor an AbstractSet (set). Pydantic only accepts these two shapes for include/exclude specifications.

Source

Thrown at pydantic/_internal/_utils.py:288

            merge_keys = list(base) + [k for k in override if k not in base]

        merged: dict[int | str, Any] = {}
        for k in merge_keys:
            merged_item = cls.merge(base.get(k), override.get(k), intersect=intersect)
            if merged_item is not None:
                merged[k] = merged_item

        return merged

    @staticmethod
    def _coerce_items(items: AbstractSetIntStr | MappingIntStrAny) -> MappingIntStrAny:
        if isinstance(items, Mapping):
            pass
        elif isinstance(items, AbstractSet):
            items = dict.fromkeys(items, ...)  # type: ignore
        else:
            class_name = getattr(items, '__class__', '???')
            raise TypeError(f'Unexpected type of exclude value {class_name}')
        return items  # type: ignore

    @classmethod
    def _coerce_value(cls, value: Any) -> Any:
        if value is None or cls.is_true(value):
            return value
        return cls._coerce_items(value)

    @staticmethod
    def is_true(v: Any) -> bool:
        return v is True or v is ...

    def __repr_args__(self) -> _repr.ReprArgs:
        return [(None, self._items)]


if TYPE_CHECKING:

View on GitHub (pinned to 2e5f0e2b42)

Solutions

  1. Convert the value to a set: `model_dump(exclude=set(my_list))`.
  2. If you need nested exclusions, pass a dict: `exclude={'a', 'b': {'c'}}`.
  3. Validate that the include/exclude arg is a set or dict before serializing.

Example fix

# before
m.model_dump(exclude=['secret', 'token'])  # list rejected

# after
m.model_dump(exclude={'secret', 'token'})  # set accepted
Defensive patterns

Strategy: validation

Validate before calling

from collections.abc import Mapping, Set
def valid_include_exclude(v) -> bool:
    return v is None or isinstance(v, (Mapping, Set))

Prevention

When it happens

Trigger: Passing `exclude=[0, 1]` (a list) or `exclude=('a', 'b')` (a tuple) or a custom iterable to `model_dump`/`model_dump_json`. Lists/tuples/strings are not accepted; only sets and dicts are.

Common situations: Passing JSON-decoded lists (from a web request) directly as exclude; assuming any iterable works; converting between set/list representations carelessly.

Related errors


AI-assisted analysis of pydantic/pydantic@2e5f0e2b42 (2026-08-04). Data as JSON: /data/errors/76560f80a77d5538.json. Report an issue: GitHub.