Skip to content

fix: include index/key context in deep_iterable and deep_mapping errors#1554

Open
lihan3238 wants to merge 8 commits intopython-attrs:mainfrom
lihan3238:fix-1245
Open

fix: include index/key context in deep_iterable and deep_mapping errors#1554
lihan3238 wants to merge 8 commits intopython-attrs:mainfrom
lihan3238:fix-1245

Conversation

@lihan3238
Copy link
Copy Markdown

@lihan3238 lihan3238 commented May 8, 2026

Fixes #1245 (also referenced in #1206)

Summary

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

Before

A(x=["hello", 123])
# TypeError: 'x' must be <class 'str'> (got 123)

After

A(x=["hello", 123])
# TypeError: 'x[1]' must be <class 'str'> (got 123)

Changes

  • _DeepIterable.__call__: Wrap member validator call in try/except, replace attribute name with indexed name (x -> x[1])
  • _DeepMapping.__call__: Same for key and value validator calls, using key repr (m -> m['key'])

Test

Verified with:

  • deep_iterable + instance_of(str): error shows x[1] instead of x
  • deep_mapping + instance_of(int) values: error shows m['b'] instead of m
  • Valid data passes through unchanged

lihan3238 and others added 8 commits May 9, 2026 02:11
…r messages

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

Before: "'x' must be <class 'str'> (got 123)"
After:  "'x[1]' must be <class 'str'> (got 123)"

Fixes python-attrs#1245
str(Exception) returns the repr of all args when there are multiple,
which corrupted the error message. Use e.args[0] to get just the
message and reconstruct with (new_msg,) + e.args[1:] to preserve
the original args structure.

Also update test_bad_exception_args to expect the improved error
message format with index context.
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