bool(Enum) should raise ValueError
Chris Angelico
rosuav at gmail.com
Fri Jul 26 15:33:30 EDT 2019
On Sat, Jul 27, 2019 at 5:16 AM Erik Aronesty <erik at q32.com> wrote:
>
> I just spend a while tracking down and killing all "if Enum" and "if not
> Enum" bugs in my code. I was frankly shocked that this didn't raise a
> ValueError to begin with.
>
> Apparently all enums are true/false depending on whether the underlying
> value is truthy or falsy.
>
> Which breaks the abstraction Enum's are trying to achieve because now the
> user of an Enum has to know "stuff" about the underlying value and how it
> behaves.
If you want to abstract away the underlying value, just don't have one?
>>> from enum import Enum, auto
>>> class Color(Enum):
... red = auto()
... green = auto()
... blue = auto()
...
>>> bool(Color.red)
True
>>> bool(Color.green)
True
>>> bool(Color.blue)
True
They happen to have the values 1, 2, and 3, but that doesn't matter.
When an enum has to correspond to a real underlying value, it behaves
as similarly to that value as possible:
>>> http.HTTPStatus.METHOD_NOT_ALLOWED == 405
True
Thus it should also inherit its truthiness from that value.
ChrisA
More information about the Python-list
mailing list