1

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.)

2
  • 1
    If you use SamplingRateEnum(user_input) it will raise a ValueError if it's not one of the valid values. Otherwise the resulting value can be used as if it was an integer. Commented Sep 28, 2023 at 10:48
  • what is the problem with your solution? Commented Sep 28, 2023 at 10:58

1 Answer 1

1

You can replace __members__.values() with iter

valid_flag = user_input in iter(SamplingRateEnum)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.