Search code examples
pythonenumsboolean

Python Enum for Boolean variable


I'm using class enum.Enum in order to create a variable with selected members.

The main reason is to enable other developers in my team to use the same convention by selecting one of several permitted members for variable.

I would like to create a Boolean variable in the same way, enabling other developers to select either True or False.

Is it possible to define an enum which will receive True False options? Is there any better alternative?

The following options don't work:

boolean_enum = Enum('boolean_enum', 'True False')

boolean_enum = Enum('boolean_enum', True False)


Solution

  • boolean_enum = Enum('boolean_enum', [('True', True), ('False', False)])
    

    Checkout the documentation of this API: https://docs.python.org/3/library/enum.html#functional-api

    If you just specify 'True False' for the names parameter, they will be assigned automatic enumerated values (1,2) which is not what you want. And of courase you can't just send True False without it being a string argument for the names parameter.

    so what you want is one of the options that allow you to specify name and value, such as the above.

    Edit:
    When defined as above, the enum elements aren't accessible by boolean_enum.True (but they are accessible by boolean_enum['True'] or boolean_enum(True)).
    To avoid this issue, the field names can be changed and defined as

    Enum('boolean_enum', [('TRUE', True), ('FALSE', False)])
    

    Then accessed as boolean_enum.TRUE or boolean_enum['TRUE'] or boolean_enum(True)