Convert string to Enum in Python

Vladius picture Vladius · Dec 31, 2016 · Viewed 82.7k times · Source

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

Answer

Ethan Furman picture Ethan Furman · Dec 31, 2016

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>

[1] Official docs: Enum programmatic access