Skip to content

gh-150220: List valid member values in Enum's default lookup ValueError#150223

Closed
drain99 wants to merge 1 commit into
python:mainfrom
drain99:gh-150220-list-valid-enum-values
Closed

gh-150220: List valid member values in Enum's default lookup ValueError#150223
drain99 wants to merge 1 commit into
python:mainfrom
drain99:gh-150220-list-valid-enum-values

Conversation

@drain99
Copy link
Copy Markdown

@drain99 drain99 commented May 22, 2026

  • Problem
>>> from enum import Enum
>>> class Currency(Enum):
...     USD = "USD"; EUR = "EUR"; JPY = "JPY"
>>> Currency("USO")
ValueError: 'USO' is not a valid Currency

The user has to inspect cls.__members__ to discover the legal set.
Pydantic and similar validators already include the list ("Input should be 'USD', 'EUR' or 'JPY'").

  • Proposal
-ValueError: 'USO' is not a valid Currency
+ValueError: 'USO' is not a valid Currency. Valid values: 'USD', 'EUR', 'JPY'

…but only when _missing_ has not been overridden. Subclasses that
override _missing_ (case-insensitive matching, aliases,
Flag/IntFlag's bitwise composition, ...) own their own error
messages.

  • Behaviour matrix
Case Listing?
Enum / IntEnum / StrEnum (default _missing_) yes
Flag / IntFlag (override for bitwise) no
Subclass _missing_ returning None no (subclass owns msg)
Subclass _missing_ raising ValueError no (own message preserved)

Existing test_enum.py suite passes unchanged.

  • Backward compatibility

Additive. ValueError type and prefix unchanged; only a Valid values: ... suffix.
Code asserting on the exact bare message would need a minor change.

…lueError

Append the list of valid member values to the default ValueError raised
by Enum.__new__ when an unknown value is looked up, but only when the
class has not overridden _missing_. Flag/IntFlag and any user enum
defining a custom _missing_ are unaffected and continue to produce the
bare default message.

    >>> class Currency(Enum):
    ...     USD = 'USD'; EUR = 'EUR'; JPY = 'JPY'
    >>> Currency('USO')
    ValueError: 'USO' is not a valid Currency. Valid values: 'USD', 'EUR', 'JPY'
@drain99 drain99 requested a review from ethanfurman as a code owner May 22, 2026 07:57
@bedevere-app
Copy link
Copy Markdown

bedevere-app Bot commented May 22, 2026

Most changes to Python require a NEWS entry. Add one using the blurb_it web app or the blurb command-line tool.

If this change has little impact on Python users, wait for a maintainer to apply the skip news label instead.

@picnixz
Copy link
Copy Markdown
Member

picnixz commented May 22, 2026

See issue for the closing rationale.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants