Python Enum for Boolean variable
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Quirky Dreamscape Looping
--
Chapters
00:00 Question
00:58 Accepted answer (Score 6)
02:06 Answer 2 (Score 5)
02:50 Thank you
--
Full question
https://stackoverflow.com/questions/3150...
Accepted answer links:
https://docs.python.org/3/library/enum.h...
Answer 2 links:
https://docs.python.org/3/library/enum.h...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #enums #boolean
#avk47
ANSWER 1
Score 9
Nowadays (python 3.6+) this could be much more conveniently achieved by using enum.Flag:
from enum import Flag
class Boolean(Flag):
TRUE = True
FALSE = False
An added benefit of enum.Flag over enum.Enum is that it supports (and is closed under) bit-wise operators (&,|,~) from the get-go:
>>> Boolean.TRUE & Boolean.FALSE
Boolean.FALSE
>>> Boolean.TRUE | Boolean.FALSE
Boolean.TRUE
>>> ~Boolean.FALSE
Boolean.TRUE
For more information see https://docs.python.org/3/library/enum.html#enum.Flag
ACCEPTED ANSWER
Score 6
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)