How can I validate a parameter passed by a user by ensuring it is one of the values of the members of an integer enum that already exists in my codebase?
I have the following SamplingRateEnum:
from enum import IntEnum, StrEnum
class SamplingRateEnum(IntEnum):
SR_22050 = 22_050
SR_44100 = 44_100
SR_80000 = 88_000 # NOTE *not* 88_200
I could validate the user input as follows, getting the desired result in valid_flag, but this seems like a bad way to achieve this outcome:
user_input = 22_050
valid_flag = user_input in SamplingRateEnum.__members__.values()
In the related Validate against enum members in Python, data had to be validated based on members' keys, and not their values. I want to validate data based on the latter.
Is there a better idiom or tool for this in the Python standard library? (I would like to avoiding an additional dependency just for this purpose.)
SamplingRateEnum(user_input)it will raise aValueErrorif it's not one of the valid values. Otherwise the resulting value can be used as if it was an integer.