Skip to content

API Reference

pydantic-explain: human-readable error messages for Pydantic validation errors.

ErrorDetail dataclass

A single parsed validation error.

Attributes:

Name Type Description
path str

Dotted path to the field, e.g. "user.addresses[1].zipcode".

message str

Human-readable error message from Pydantic.

error_type str

Pydantic error type code, e.g. "missing".

input_value Any

The actual invalid input value.

context dict[str, Any]

Extra context dict from Pydantic.

url str

Pydantic documentation URL for this error type.

Source code in src/pydantic_explain/_types.py
Python
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@dataclass(frozen=True, slots=True)
class ErrorDetail:
    """A single parsed validation error.

    Attributes:
        path: Dotted path to the field, e.g. ``"user.addresses[1].zipcode"``.
        message: Human-readable error message from Pydantic.
        error_type: Pydantic error type code, e.g. ``"missing"``.
        input_value: The actual invalid input value.
        context: Extra context dict from Pydantic.
        url: Pydantic documentation URL for this error type.
    """

    path: str
    message: str
    error_type: str
    input_value: Any
    context: dict[str, Any]
    url: str

FormatOptions dataclass

Configuration for error formatting.

Attributes:

Name Type Description
show_input bool

Whether to show the "Got:" line with the input value.

show_url bool

Whether to show the Pydantic docs URL.

show_error_type bool

Whether to show the error type tag.

input_max_length int

Maximum length for input value repr.

Source code in src/pydantic_explain/_types.py
Python
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
@dataclass(frozen=True, slots=True)
class FormatOptions:
    """Configuration for error formatting.

    Attributes:
        show_input: Whether to show the ``"Got:"`` line with the input value.
        show_url: Whether to show the Pydantic docs URL.
        show_error_type: Whether to show the error type tag.
        input_max_length: Maximum length for input value repr.
    """

    show_input: bool = True
    show_url: bool = False
    show_error_type: bool = False
    input_max_length: int = 80

explain(error)

Parse a Pydantic ValidationError into structured ErrorDetail objects.

Parameters:

Name Type Description Default
error ValidationError

A Pydantic ValidationError instance.

required

Returns:

Type Description
tuple[ErrorDetail, ...]

A tuple of ErrorDetail objects, one per validation error.

Source code in src/pydantic_explain/_explain.py
Python
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def explain(error: ValidationError) -> tuple[ErrorDetail, ...]:
    """Parse a Pydantic ValidationError into structured ErrorDetail objects.

    Args:
        error: A Pydantic ValidationError instance.

    Returns:
        A tuple of ErrorDetail objects, one per validation error.
    """
    return tuple(
        ErrorDetail(
            path=_format_loc(err["loc"]),
            message=err["msg"],
            error_type=err["type"],
            input_value=err.get("input"),
            context=err.get("ctx", {}),
            url=err.get("url", ""),
        )
        for err in error.errors()
    )

format_error_detail(detail, *, options=None)

Format a single ErrorDetail as a human-readable string.

Parameters:

Name Type Description Default
detail ErrorDetail

A parsed error detail.

required
options FormatOptions | None

Formatting options. Uses defaults if None.

None

Returns:

Type Description
str

A formatted multi-line string for one validation error.

Source code in src/pydantic_explain/_format.py
Python
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def format_error_detail(detail: ErrorDetail, *, options: FormatOptions | None = None) -> str:
    """Format a single ErrorDetail as a human-readable string.

    Args:
        detail: A parsed error detail.
        options: Formatting options. Uses defaults if None.

    Returns:
        A formatted multi-line string for one validation error.
    """
    opts = options or FormatOptions()
    lines = [f"  {detail.path}"]

    message = detail.message
    if opts.show_error_type:
        message = f"{message} [{detail.error_type}]"
    lines.append(f"    {message}")

    if opts.show_input:
        if detail.error_type == "missing":
            lines.append("    Got: (missing)")
        else:
            lines.append(f"    Got: {_truncate_repr(detail.input_value, opts.input_max_length)}")

    if opts.show_url and detail.url:
        lines.append(f"    See: {detail.url}")

    return "\n".join(lines)

format_errors(error, *, options=None)

Format a Pydantic ValidationError as a human-readable string.

Parameters:

Name Type Description Default
error ValidationError

A Pydantic ValidationError instance.

required
options FormatOptions | None

Formatting options. Uses defaults if None.

None

Returns:

Type Description
str

A formatted multi-line string describing all validation errors.

Source code in src/pydantic_explain/_format.py
Python
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def format_errors(error: ValidationError, *, options: FormatOptions | None = None) -> str:
    """Format a Pydantic ValidationError as a human-readable string.

    Args:
        error: A Pydantic ValidationError instance.
        options: Formatting options. Uses defaults if None.

    Returns:
        A formatted multi-line string describing all validation errors.
    """
    details = explain(error)
    opts = options or FormatOptions()

    count = len(details)
    plural = "error" if count == 1 else "errors"
    lines = [f"Validation failed for {error.title} with {count} {plural}"]

    for detail in details:
        lines.append("")
        lines.append(format_error_detail(detail, options=opts))

    return "\n".join(lines)