Skip to content

fix: improve enum misuse error - #770

Open
Sohel2309 wants to merge 1 commit into
python-attrs:mainfrom
Sohel2309:fix-601-enum-misuse
Open

fix: improve enum misuse error#770
Sohel2309 wants to merge 1 commit into
python-attrs:mainfrom
Sohel2309:fix-601-enum-misuse

Conversation

@Sohel2309

Copy link
Copy Markdown

Bug

Using a non-Enum value with an enum-typed attrs field can result in an
unhelpful AttributeError: 'str' object has no attribute 'value'.

Root cause

enum_unstructure_factory() generated unstructure hooks that accessed
.value without first checking that the value was an instance of the
expected Enum type.

Fix

Add an isinstance() check for the expected Enum type before accessing
.value. Invalid values now raise a clear TypeError describing the
expected Enum type and the received value.

The fix covers both the regular Enum and typed-enum paths.

Tests

Added regression tests covering:

The regression tests were verified to fail before the fix and pass after
the fix.

Changelog

Added the fix to HISTORY.md.

@Tinche

Tinche commented Aug 14, 2026

Copy link
Copy Markdown
Member

The problem is this inserts an isinstance check into every unstructure call, affecting performance. cattrs expects the type hints to be correct, so I'm not inclined to trade performance for better error messages in this particular case.

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.

2 participants