Falsey Enums

Rustom Mody rustompmody at gmail.com
Fri Jul 28 05:00:03 EDT 2017


On Friday, July 28, 2017 at 1:45:46 PM UTC+5:30, Ben Finney wrote:
> Ethan Furman  writes:
> 
> > class X(Enum):
> >     Falsey = 0
> >     Truthy = 1
> >     Fakey = 2
> >     def __bool__(self):
> >         return bool(self.value)
> 
> I am surprised this is not already the behaviour of an Enum class,
> without overriding the ‘__bool__’ method.
> 
> What would be a good reason not to have this behaviour by default for
> ‘Enum.__bool__’? (i.e. if this were reported as a bug on the ‘enum.Enum’
> implementation, what would be good reasons not to fix it?)

<just_a_guess>
Enums are for abstracting away from ints (typically small) to more meaningful names.
In python's terms that means whether X.Truthy should mean 0 — the value —
or "Truthy" — the name — is intentionally left ambiguous/undecided.

Observe:

>>> print (X.Truthy)
X.Truthy    # So Truthy is well Truthy
>>> X.Truthy
<X.Truthy: 1>  # No! Truthy is 1

# In other words
>>> repr(X.Truthy)
'<X.Truthy: 1>'
>>> str(X.Truthy)
'X.Truthy'
>>> 

</just_a_guess>




More information about the Python-list mailing list