Convert string to Enum in Python
I wonder what's the correct way of converting (deserializing) a string to a Python's Enum class. Seems like getattr(YourEnumType, str)
does the job, but I'm not sure if it's safe enough.
Just to be more specific, I would like to convert a 'debug'
string to an Enum object like this:
class BuildType(Enum):
debug = 200
release = 400
This functionality is already built in to Enum [1]:
>>> from enum import Enum
>>> class Build(Enum):
... debug = 200
... build = 400
...
>>> Build['debug']
<Build.debug: 200>
The member names are case sensitive, so if user-input is being converted you need to make sure case matches:
an_enum = input('Which type of build?')
build_type = Build[an_enum.lower()]
[1] Official docs: Enum programmatic access
Another alternative (especially useful if your strings don't map 1-1 to your enum cases) is to add a staticmethod
to your Enum
, e.g.:
class QuestionType(enum.Enum):
MULTI_SELECT = "multi"
SINGLE_SELECT = "single"
@staticmethod
def from_str(label):
if label in ('single', 'singleSelect'):
return QuestionType.SINGLE_SELECT
elif label in ('multi', 'multiSelect'):
return QuestionType.MULTI_SELECT
else:
raise NotImplementedError
Then you can do question_type = QuestionType.from_str('singleSelect')