skip to content

A Pydantic 2 booking model's check_out validator reads info.data['check_in'] and crashes with KeyError when check_in is invalid. Why, and how do you fix it?

level: seniorimportance: should knowfreq 32%

answer

  1. earlier fields only
  2. failed fields are left out
  3. which exceptions get converted
  4. a guarded lookup

basics

~20 s

In Pydantic 2, a field that fails validation is left out of ValidationInfo.data, and a KeyError is not converted into a validation error, so it escapes. Read with info.data.get('check_in') and skip the rule when it is missing.

solid answer

~30 s

`info.data` holds only fields validated earlier in definition order, and a field that failed, like an unparseable `check_in`, is not stored there. Pydantic keeps validating after a failure, so the `check_out` validator still runs and `info.data['check_in']` raises `KeyError`. Pydantic converts only `ValueError`, `AssertionError` and its own error types, so the `KeyError` escapes raw and the real `check_in` error is lost. The fix is `info.data.get('check_in')` with a skip when it is `None`, keeping `check_in` declared above `check_out`. The alternative is an after model validator, which runs only when both fields are valid but reports its error with an empty `loc`.

code

python · 23 lines
python
from datetime import date

from pydantic import BaseModel, ValidationError, ValidationInfo, field_validator


class Booking(BaseModel):
    check_in: date
    check_out: date

    @field_validator('check_out')
    @classmethod
    def after_check_in(cls, value: date, info: ValidationInfo) -> date:
        check_in = info.data.get('check_in')
        if check_in is not None and value <= check_in:
            raise ValueError('check_out must be after check_in')
        return value


try:
    Booking(check_in='next friday', check_out='2026-11-03')
except ValidationError as e:
    print([err['loc'] for err in e.errors()])
    #> [('check_in',)]

go deeper

for a junior

Remember that ValidationInfo.data holds fields validated before the current one, and that a validator should raise ValueError, not let other exceptions escape.

for a middle

Explain definition-order validation, why a failed field is missing from info.data, and how a guarded lookup keeps the real error visible.

for a senior

Diagnose the escaped KeyError from a traceback, choose between a guarded field validator and an after model validator, and test with the other field invalid.

for a principal

Push for validator tests that combine invalid fields, since interaction bugs like this pass every single-field test and only show up as production server errors.

## The scenario A booking model declares `check_in: date` and `check_out: date`. To get the error on the right field, someone wrote a field validator on `check_out` that reads the other date: ```python @field_validator('check_out') @classmethod def after_check_in(cls, value: date, info: ValidationInfo) -> date: if value <= info.data['check_in']: raise ValueError('check_out must be after check_in') return value ``` It passes every test with valid dates. In production, a request with `check_in='next friday'` returns a server error with a `KeyError: 'check_in'` traceback instead of a clean validation failure. ## Why it happens Three Pydantic 2 behaviours combine: 1. **Fields are validated in definition order.** `ValidationInfo.data` holds only the fields validated **before** the current one. `check_in` is declared first, so normally it is there. 2. **A failed field is left out of `info.data`.** When `'next friday'` fails date parsing, Pydantic records the error and moves on to the next field without storing a value for `check_in`. Errors are collected, so `check_out` is still validated. 3. **Only some exceptions are converted.** Pydantic turns `ValueError`, `AssertionError` and its own error classes into error entries. A `KeyError` is none of these, so it escapes as itself. The caller gets a raw `KeyError`, the collected `check_in` error is lost, and a web layer typically reports a server error rather than a validation failure. ## Reading the evidence The traceback is the clue. A validation problem surfaces as a `ValidationError` with a list of entries; this one surfaces as `KeyError: 'check_in'` raised from inside the validator function, with Pydantic's frames above it. That shape means the validator itself crashed. Two more signals point the same way: - the failure appears only for requests where `check_in` is malformed, never when both dates are valid; - logs show no validation error for `check_in`, although the input was plainly wrong, because the escaped exception replaced the error list Pydantic was building. ## The fix - Read with **`info.data.get('check_in')`** and skip the comparison when it is missing. The `ValidationError` then reports the real problem, the unparseable `check_in`, and once the client fixes it the order rule runs. - Keep `check_in` **declared above** `check_out`. If the order were reversed, `check_in` would never be in `info.data` when `check_out` is validated, and the rule would silently never fire. - Alternatively, move the rule to `@model_validator(mode='after')`. It runs only once every field is valid, so both attributes exist; the trade-off is that its error has an empty `loc` instead of naming `check_out`. | Approach | Error location | Needs a missing-key guard | Depends on field order | |---|---|---|---| | field validator on `check_out` with `info.data` | `('check_out',)` | yes | yes | | after model validator | `()` | no | no | ## Related `ValidationInfo` facts worth knowing - `info.data` is **`None` inside a model validator**; only field validators get the earlier fields. - `info.field_name` names the field being validated, useful when one function covers several fields. - `info.mode` says whether the input came in as Python objects or JSON (or strings), which lets a validator behave differently for the two. - `info.context` carries an object passed as `model_validate(data, context={...})`, for example a set of dates the hotel is closed. A plain `Booking(...)` call has no way to pass context, so a validator should treat a missing context as normal. ## How to catch this earlier - Test each validator with the **other** field invalid, not only with both valid. The failure only appears when two fields interact. - Treat any exception other than `ValueError` escaping a validator as a defect. Pydantic 2 deliberately stopped converting `TypeError` so that bugs surface as bugs; a `KeyError` behaves the same way. - Keep a cross-field validator's logic tolerant: assume any earlier field may be absent.

  • In Pydantic 2, how would you pass a set of dates the hotel is closed into this validator?
    Call `Booking.model_validate(data, context={'closed': closed_dates})` and read `info.context` inside the validator, checking it is a dict first. Context cannot be passed through a plain `Booking(...)` call, so the validator should treat a missing context as having no closed dates.
  • In Pydantic 2, what happens if check_out is declared above check_in in this model?
    Fields validate in definition order, so `check_in` is never in `info.data` when `check_out` is validated. With the guarded lookup the rule silently never fires; with the unguarded one every request raises `KeyError`. Keep the referenced field earlier, or move the rule to an after model validator.

  • info.data contains every field of the input, valid or not.
  • A failed field appears in info.data with the value None.
  • Pydantic wraps any exception from a validator in a ValidationError.
  • Field order in the class never affects validator behaviour.
  • Validation stops at the first failing field, so check_out never runs.