pythonstringenumstype-conversion

Convert string to Enum in Python


What's the correct way to convert a string to a corresponding instance of an Enum subclass? Seems like getattr(YourEnumType, str) does the job, but I'm not sure if it's safe enough.

As an example, suppose I have an enum like

class BuildType(Enum):
    debug = 200
    release = 400

Given the string 'debug', how can I get BuildType.debug as a result?


Solution

  • This functionality is already built in to Enum:

    >>> 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()]