skip to content

Why does a Pydantic 2 order model with `extra='forbid'` silently drop a misspelled key inside a nested line item, and how do you fix it?

level: seniorimportance: should knowfreq 40%

answer

  1. each model its own settings
  2. default is ignore
  3. configuration boundary
  4. inherited base config

basics

~20 s

Pydantic 2 does not propagate model_config into nested Pydantic models: each model keeps its own configuration, and the line item still uses the default extra='ignore'. Put extra='forbid' on a shared base class that every model inherits.

solid answer

~40 s

`extra` controls unknown keys: `'ignore'` (the default) drops them, `'forbid'` raises `extra_forbidden`, and `'allow'` keeps them in `__pydantic_extra__` (readable as `model_extra`). The catch is that **configuration does not propagate into nested models**: each `BaseModel` or Pydantic dataclass is its own **configuration boundary**, so `Order`'s `extra='forbid'` says nothing about `LineItem`, which still ignores a typo such as `quantiy` and falls back to its default. The fix is a base class, say `StrictModel` with `model_config = ConfigDict(extra='forbid')`, that every inbound model inherits; configuration is inherited and merged with a subclass's own. The same boundary applies to every setting, including `frozen`, which is also shallow: it blocks attribute assignment, not mutation of a list or dict inside.

code

python · 39 lines
python
from pydantic import BaseModel, ConfigDict, ValidationError


class LineItem(BaseModel):
    sku: str
    quantity: int = 1


class Order(BaseModel):
    model_config = ConfigDict(extra='forbid')

    order_id: str
    items: list[LineItem]


payload = {'order_id': 'A-1', 'items': [{'sku': 'S1', 'quantiy': 5}]}
print(Order.model_validate(payload).items[0].quantity)
#> 1


class StrictModel(BaseModel):
    model_config = ConfigDict(extra='forbid')


class StrictLineItem(StrictModel):
    sku: str
    quantity: int = 1


class StrictOrder(StrictModel):
    order_id: str
    items: list[StrictLineItem]


try:
    StrictOrder.model_validate(payload)
except ValidationError as exc:
    print([(e['loc'], e['type']) for e in exc.errors()])
#> [(('items', 0, 'quantiy'), 'extra_forbidden')]

go deeper

for a junior

Recall the three extra values and that ignore is the default, so unknown keys disappear silently unless you choose otherwise.

for a middle

Explain where allowed extras are stored, the extra_forbidden error, and how a subclass's model_config merges with its parent's.

for a senior

Diagnose a nested typo that passed because configuration stops at each model, fix it with a shared base class, and prove it with a nested-key test.

for a principal

Weigh forbidding unknown keys on every inbound model against partners adding fields freely, and how the shared base class becomes an enforced team policy.

## What `extra` does When input contains keys that match no declared field (or alias), Pydantic 2 consults the model's **`extra`** setting in `model_config`: | Value | Unknown key | Where it goes | |---|---|---| | `'ignore'` (default) | accepted silently | discarded | | `'forbid'` | rejected | `ValidationError` entry with type `extra_forbidden` | | `'allow'` | accepted | kept in `__pydantic_extra__`, exposed as `model_extra`, and included in dumps | With `'allow'`, the extra values are **not validated** by default; you can annotate `__pydantic_extra__` (for example as `dict[str, int]`) to give them a type. Since version 2.12 the validation methods, such as `model_validate()`, also take an `extra` argument that overrides the model's setting for one call. ## Reading an `extra_forbidden` error When `'forbid'` rejects a key, the `ValidationError` holds one entry per unknown key, so a payload with three stray keys reports three entries rather than stopping at the first. Each entry carries: - `type`: `'extra_forbidden'` - `msg`: `'Extra inputs are not permitted'` - `loc`: the path to the offending key, including list indexes for nested items - `input`: the value that was sent under that key The `loc` is the useful part when talking to a partner: it names the exact key, at the exact depth, that your contract does not know. ## Why the nested typo slips through Pydantic treats every model class as its own **configuration boundary**. When `Order` has a field `items: list[LineItem]`, validating an order validates each item against `LineItem`'s schema, built from `LineItem`'s own `model_config`. `Order`'s settings stay at `Order`'s edge. So in this situation: - `Order` sets `extra='forbid'`. - `LineItem` sets nothing, so it uses the default `extra='ignore'`. - The partner sends `{"sku": "S1", "quantiy": 5}`. `LineItem` sees an unknown `quantiy`, drops it, and `quantity` takes its default of `1`. Nothing fails, and the order ships the wrong quantity. A top-level typo in the order would have been rejected, which is why this bug survives a quick test. The documentation spells out the rule: for Pydantic models and Pydantic dataclasses, configuration is **not** propagated. Standard-library dataclasses and `TypedDict` classes used as field types are the exception: they take the enclosing model's configuration unless they set their own, for example with `with_config`. ## Fixing it The standard fix is to make the strictness a property of a **base class**: 1. Define `class StrictModel(BaseModel): model_config = ConfigDict(extra='forbid')`. 2. Make every inbound model, nested ones included, inherit from `StrictModel`. 3. Let individual models add settings of their own; a subclass's `model_config` is **merged** with the parent's, so `extra='forbid'` is kept. Caveats worth knowing: - With **multiple inheritance**, Pydantic currently does not follow the method resolution order when merging configuration, so keep the base hierarchy simple. - Third-party or generated models that do not inherit your base keep their own settings. Review them individually. - Choosing `'forbid'` for inbound payloads is a contract decision as well as a code one: it turns a partner's harmless new field into a rejected request. The general trade-off between rejecting and ignoring unknown fields is a wire-contract question, covered with schema evolution. ## The same boundary applies to `frozen` `frozen` is another per-model setting, and it behaves the same way: - `ConfigDict(frozen=True)` makes attribute assignment raise a `ValidationError` of type `frozen_instance`, and gives the model a `__hash__`, so instances are hashable when all their values are. - `Field(frozen=True)` freezes one field; assigning it raises `frozen_field`. - Freezing is **shallow**. A frozen order with a `dict` field still lets `order.meta['k'] = 1` succeed, and a frozen `Order` holding non-frozen `LineItem` instances still lets `order.items[0].quantity = 5` succeed, because `LineItem` has its own configuration. The documentation calls this **faux immutability**: Python does not enforce immutability, and Pydantic only blocks `__setattr__` and deletion on the frozen model itself. ## How to check your models - Validate a payload with a misspelled **nested** key in a test, and assert an `extra_forbidden` error whose `loc` points inside the list, such as `('items', 0, 'quantiy')`. - Grep for models that subclass `BaseModel` directly in an inbound package; each one is a model outside your policy. - If you use `frozen` for value objects, freeze the nested models too, and prefer tuples to lists inside them.

  • In Pydantic 2, how do you keep unknown keys but still validate their values?
    Set `extra='allow'` and annotate `__pydantic_extra__` with a value type, for example `__pydantic_extra__: dict[str, int] = Field(init=False)`. Unknown keys are then stored and each value is validated as an int. Without the annotation, extra values are kept as they arrived, unvalidated.
  • In Pydantic 2, a frozen Order holds a list of LineItem models. Can code still change an item's quantity?
    Yes. `frozen=True` on Order blocks assigning Order's own attributes, but the list is mutable and LineItem has its own configuration, so `order.items[0].quantity = 5` succeeds unless LineItem is frozen too. Freezing in Pydantic is shallow and per model.

  • Nested models inherit model_config from the model that contains them.
  • Pydantic 2 rejects unknown keys by default.
  • Values kept with extra='allow' are validated against a type by default.
  • frozen=True makes the whole object graph immutable.
  • Configuration from several base classes is merged in method resolution order.