Skip to content

fix: improve error messages in deep_iterable and deep_mapping validators#1533

Closed
JasonOA888 wants to merge 2 commits intopython-attrs:mainfrom
JasonOA888:fix/deep-iterable-error-message-1245
Closed

fix: improve error messages in deep_iterable and deep_mapping validators#1533
JasonOA888 wants to merge 2 commits intopython-attrs:mainfrom
JasonOA888:fix/deep-iterable-error-message-1245

Conversation

@JasonOA888
Copy link

Summary

Fixes #1245 (also referenced in #1206)

When inner validators fail in deep_iterable or deep_mapping, the error message now includes the index/key of the failing element instead of just the parent attribute name.

Problem

Before this fix:

@define
class A:
    x: list = field(
        validator=deep_iterable(
            member_validator=[instance_of(str), min_len(1)],
        ),
    )

A(["abc", ""])
# ValueError: Length of 'x' must be >= 1: 0

The error says 'x' but it's not x that is too short - it's one of its items.

Solution

After this fix:

A(["abc", ""])
# ValueError: Length of 'x[1]' must be >= 1: 0

Now the error clearly indicates which element failed validation.

Changes

  • Modified _DeepIterable.__call__ to catch exceptions and rewrite the attribute name to include the index
  • Modified _DeepMapping.__call__ to catch exceptions and rewrite the attribute name to include the key

Testing

from attr import define, field
from attr.validators import deep_iterable, instance_of, min_len

@define
class TestA:
    x: list = field(
        validator=deep_iterable(
            member_validator=[instance_of(str), min_len(1)],
        ),
    )

try:
    TestA(["abc", ""])
except ValueError as e:
    print(e)  # Length of 'x[1]' must be >= 1: 0

JasonOA888 and others added 2 commits March 20, 2026 17:57
When inner validators fail, the error message now includes the index/key
of the failing element instead of just the parent attribute name.

Before: "Length of 'x' must be >= 1: 0"
After:  "Length of 'x[1]' must be >= 1: 0"

This makes it clear which element in the iterable/mapping failed validation.

Fixes python-attrs#1245
@JasonOA888 JasonOA888 closed this Mar 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Wrong error message for inner validators

1 participant