Is a typing.EnumValues feature a good idea for Python?

0
4
Asked By CuriousCoder84 On

Hey everyone! I recently encountered a challenge while working with Pydantic and thought of a potential enhancement for Python's typing system. I was using a Pydantic class with a string field that needed to match Enum values. My first attempt involved trying to use `Literal[*[e.value for e in MyEnum]]`, but it didn't play well with static type checkers.

Alternatively, I considered creating a separate type like:

```python
class MyEnum(str, Enum):
FIRST = "first"
SECOND = "second"

type EnumValuesLiteral = Literal["first", "second"]
```

This would work, but it splits the truth between the Enum definitions and the Literals, which could lead to errors if one is updated without the other.

I think this problem could be quite common, especially for APIs where you often map strings from requests/responses to Enums in Python. What do you all think? Would a feature like `EnumValues` be something you'd find useful? Here's a small example:

```python
from enum import Enum
from typing import EnumValues

class Colors(str, Enum):
RED = "red"
BLUE = "blue"
GREEN = "green"

class Button:
text: str
url: str
color: EnumValues[Colors] # This would be like Literal["red", "blue", "green"]
```

4 Answers

Answered By EnumExpert99 On

I suggest using the enum members directly instead of their string values.

Answered By TypeWhisperer67 On

There's actually no need for adding a separate literal type. You could simply set the type in your Pydantic model directly to `Color`. Sure, you might need some serialization logic, but Pydantic handles enums quite well!

CodeNinja22 -

A member of StrEnum doesn’t even require special serialization – it’s already a string.

OldSchoolDev -

Maybe those new coders just haven’t dealt with languages like Pascal, which could explain their perspective.

Answered By EnumFanatic88 On

As mentioned by others, Enums are well-supported in Pydantic. You might also want to subclass StrEnum instead of using str & enum together.

Answered By PydanticPro On

I’ve actually faced a similar issue before, and had to revert to using a literal type instead of enums. Although you can get the variants list with `typing.get_args()`, I believe adding too many special forms isn’t necessary. Python type expressions need to be valid runtime objects as well, which complicates things. However, a type like `EnumValues[T]` might be the only viable solution, despite adding complexity for a niche feature.

SolveItGuy -

In theory, I don't see why Python couldn't have a preprocessor to help with this. It might not be the best solution, but it could be a way forward.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.