pydantic/pydantic · error · TypeError
Expected a class, got
Error message
Expected a class, got {type_param!r} What it means
A TypeError raised in _subclass_schema when the argument supplied to type[...] is neither a class nor None. After resolving Self types and rejecting generic aliases, the code calls inspect.isclass(type_param); if it is not a class (and is not None, which is special-cased to NoneType), it raises with the repr of the offending value. This is a low-level type-correctness guard, not a user-facing PydanticUserError.
Solutions
- Ensure the argument to type[...] is an actual class object, not a string, instance, or callable.
- If using a forward reference, make sure it resolves (import the class or call model_rebuild() after definition).
- Replace type[value] with the class itself if you meant 'an instance of this class'.
- For None, use type[None] explicitly (handled internally) rather than passing None as a runtime value.
Example fix
// before handler: type["MyHandler"] # string never resolved // after from myapp import MyHandler handler: type[MyHandler]
Defensive patterns
Strategy: validation
Validate before calling
import inspect, typing
def type_arg_is_class(tp) -> bool:
args = typing.get_args(tp)
if not args:
return True
inner = args[0]
return inner is None or inspect.isclass(inner) Type guard
import inspect, typing
def is_valid_type_of(tp) -> bool:
if typing.get_origin(tp) is not type:
return True
inner = typing.get_args(tp)[0]
return inspect.isclass(inner) or inner is None Try / catch
try:
Model.model_rebuild()
except TypeError as e:
if 'Expected a class' in str(e):
# replace the non-class argument to type[...]
... Prevention
- Ensure type[...] is parameterized with actual class objects, not strings or instances.
- Resolve forward references before using them as type[...] arguments.
- Static-check type[...] annotations with mypy/pyright to catch non-class arguments.
When it happens
Trigger: Annotating with type[<non-class>] such as type[42], type["SomeForwardRefString"], type[lambda], or passing an instance/module where a class is expected. Forward references that failed to resolve into an actual class object also surface here.
Common situations: Passing a string forward reference inside type[...] that never gets resolved to a class; bugs in dynamic schema construction that pass arbitrary objects as the type argument; confusion between type[X] (class of X) and X itself.
Related errors
- Subscripting `type[]` with an already parametrized type is…
- circular-reference-schema
- Could not find a ref for
- dataclass-init-false-extra-allow
- decorator-missing-field
AI-assisted analysis of pydantic/pydantic@cc13d1b8c9 (2026-08-11).
Data as JSON: /api/errors/cf83c0b4cd8c4c48.
Report an issue: GitHub.
Appendix: source
Thrown at pydantic/_internal/_generate_schema.py:1792
else:
return self._type_schema()
elif is_union_origin(get_origin(type_param)):
return self._union_is_subclass_schema(type_param)
else:
if typing_objects.is_self(type_param):
type_param = self._resolve_self_type(type_param)
if _typing_extra.is_generic_alias(type_param):
raise PydanticUserError(
'Subscripting `type[]` with an already parametrized type is not supported. '
f'Instead of using type[{type_param!r}], use type[{_repr.display_as_type(get_origin(type_param))}].',
code=None,
)
if not inspect.isclass(type_param):
# when using type[None], this doesn't type convert to type[NoneType], and None isn't a class
# so we handle it manually here
if type_param is None:
return core_schema.is_subclass_schema(NoneType)
raise TypeError(f'Expected a class, got {type_param!r}')
return core_schema.is_subclass_schema(type_param)
def _sequence_schema(self, items_type: Any) -> core_schema.CoreSchema:
"""Generate schema for a Sequence, e.g. `Sequence[int]`."""
from ._serializers import serialize_sequence_via_list
item_type_schema = self.generate_schema(items_type)
list_schema = core_schema.list_schema(item_type_schema)
json_schema = smart_deepcopy(list_schema)
python_schema = core_schema.is_instance_schema(typing.Sequence, cls_repr='Sequence')
if not typing_objects.is_any(items_type):
from ._validators import sequence_validator
python_schema = core_schema.chain_schema(
[python_schema, core_schema.no_info_wrap_validator_function(sequence_validator, list_schema)],
)
View on GitHub (pinned to cc13d1b8c9)