[issue24840] implement bool conversion for enums to prevent odd edge case

Mike Lundy report at bugs.python.org
Tue Aug 11 08:15:25 CEST 2015


Mike Lundy added the comment:

@serhiy.storchaka: It's somewhat of a special case, to be sure. However, I do think it's justified to put it into the base (rather than a user type) for three reasons:

1) It makes IntEnum and Enum consistent. IntEnum actually already handles this case just fine, because it's an int and therefore already supports __bool__ correctly. It feels odd that changing the storage format from an IntEnum to a Enum should break the logic- correctly used, the actual enum values should never matter. This small change just brings them into line.

2) It is less surprising than the current case; I discovered this when I did something like the Enum.Nope case here, and I naively used the enum in an if statement, assuming that the value would control the __bool__ value. (This was caught by my tests, of course, but the point remains that I wrote the code). Normally in python, you'd expect the default bool conversion to be unconditionally True, but enums aren't really normal objects; for any use case for which there is a default noop value, you'd generally put that value _into_ the enum:

class FilterType(Enum):
    NONE = None
    SUB  = 'Sub'
    UP   = 'Up'
    ...

3) It's not logically inconsistent with the idea of Enums. The other dunder methods you mention aren't consistent with the concept: __float__ (enum values aren't generally numbers except as an implementation detail), __lt__ (enums aren't generally ordered), __len__ (enums aren't generally containers). The one thing an enum does have is a value, and it feels consistent to me to check the truthiness of an enum without having to reach into the .value to do so.

Anyway, that's my case for inclusion!

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue24840>
_______________________________________


More information about the Python-bugs-list mailing list