0

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)

1 Answer 1

3

I believe you are looking for accessing by value: ConfigField("foo"), which gives <ConfigField.FOO: 'foo'>.

A ValueError will be raised for parsing using not existing values:

>>> ConfigField("not foo")
ValueError: 'not foo' is not a valid ConfigField
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Program Files\Python38\lib\enum.py", line 309, in __call__
    return cls.__new__(cls, value)
  File "C:\Program Files\Python38\lib\enum.py", line 600, in __new__
    raise exc
  File "C:\Program Files\Python38\lib\enum.py", line 584, in __new__
    result = cls._missing_(value)
  File "C:\Program Files\Python38\lib\enum.py", line 613, in _missing_
    raise ValueError("%r is not a valid %s" % (value, cls.__name__))
ValueError: 'not foo' is not a valid ConfigField
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.