Falsey Enums
Pavol Lisy
pavol.lisy at gmail.com
Sat Jul 29 03:37:20 EDT 2017
On 7/28/17, 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.
BTW bool at enum seems to be expensive:
%timeit 7 if x else 0
850 ns ± 12.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit 7 if x.value else 0
479 ns ± 4.38 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit 7 if x!=X.Falsey else 0
213 ns ± 10.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
> Like Ben, I'm surprised that's not the default behaviour.
Me too.
I was trying to find some example which is not completely semantically
wrong and where backward compatibility is important.
Maybe something like this? ->
class Color(Enum):
black = 0 # this could equal to some external library constant
value for black
white = 0xff
color = user_choice()
if not color: # color is None
color = random.choice(list(Color))
More information about the Python-list
mailing list