Falsey Enums

Chris Angelico rosuav at gmail.com
Fri Jul 28 07:14:41 EDT 2017


On Fri, Jul 28, 2017 at 8:28 PM, Steve D'Aprano
<steve+python at pearwood.info> wrote:
> On Fri, 28 Jul 2017 05:52 pm, Ethan Furman wrote:
>
>> class X(Enum):
>>      Falsey = 0
>>      Truthy = 1
>>      Fakey = 2
>>      def __bool__(self):
>>          return bool(self.value)
>
> Thanks Ethan.
>
> Like Ben, I'm surprised that's not the default behaviour.

Because members of an Enum are considered to be "things". If you want
them to behave more like integers, instead subclass IntEnum:

>>> class Y(IntEnum):
...  Falsey = 0
...  Truthy = 1
...  File_Not_Found = 2
...
>>> Y.Falsey
<Y.Falsey: 0>
>>> bool(Y.Falsey)
False
>>> bool(Y.Truthy)
True

Among other differences, this means that zero is considered falsey,
and that the enumerated variables compare equal to the corresponding
integers.

ChrisA



More information about the Python-list mailing list