Problem:
I'm parsing some config file and one field should be parsed to an Enum. Let's say there may be 3 possible values:
`foo`, `bar`, `baz`
And I want to parse them into the following enum's values:
class ConfigField(Enum):
FOO = 'foo'
BAR = 'bar'
BAZ = 'baz'
What have I tried so far:
I have written the following function to do that:
def parse_config_field(x: str) -> ConfigField:
for key, val in ConfigField.__members__.items():
if x == val.value:
return val
else:
raise ValueError('invalid ConfigField: ' + str(x))
But I think this is ugly and too complicated for something so simple and straightforward. I also considered just lowercasing enum field's names:
def parse_config_field2(x: str) -> ConfigField:
value = ConfigField.__members__.get(x.lower(), None)
if value is None:
raise ValueError('invalid ConfigField: ' + str(x))
else:
return value
Which is slightly shorter, but still pretty ugly and what's worse, it creates direct dependence between config values (in some text config file) and ConfigField which I'm not comfortable with.
I just recently switched from python2 to python3 so I'm not 100% familiar with Enums and I'm hoping there may be a better way to do this.
Question:
Is there a better way to do this? I'm looking for simpler (and perhaps more "built-in" / "pythonic") solution than my parse_config_field - perhaps something like:
value = ConfigField.get_by_value(cfg_string)