Hi all,
I’d like to propose adding a method _normalize_input_
to StrEnum
, allowing developers to define a custom input normalization before value lookup.
Why?
StrEnum
requires exact string matches, making it cumbersome to handle case-insensitive or normalized value lookups.- Many real-world use cases require flexible matching (e.g. GraphQL, REST APIs, JSON)
- Current workarounds require adding manual helpers methods, which are redundant across projects.
Proposal
A new class method _normalize_input_
(similarly to _generate_next_value_
or __new__
) would allow developers to override how input values are processed before lookup.
class Colors(StrEnum):
@staticmethod
def _normalize_input_(cls, value):
return value.lower() # Allows case-insensitive lookup
RED = auto()
BLUE = auto()
GREEN = auto()
Now, lookups apply _normalize_input_
before matching:
In [1]: Colors("Red")
Out[1]: <Colors.RED: 'red'>
In [2]: Colors("BLUE")
Out[2]: <Colors.BLUE: 'blue'>
In [3]: Colors("green")
Out[3]: <Colors.GREEN: 'green'>
Why this matters
- Allows case-insensitive lookups and others pre-lookup transformations.
- Integrates well with GraphQL, APIs and JSON configs.
- Keeps Enums immutable while enabling flexible lookups.
Would love to hear your thoughts, is this something the community would find useful?
Thanks, Gonzalo