Non int Boolean

Weatherby,Gerard gweatherby at uchc.edu
Sat Jan 28 14:44:03 EST 2023


If someone really really wants a non-int Boolean, it is easy to implement. 5 or 6 lines, depending on whether you count the import statement:

from enum import Enum


class MyBool(Enum):
    TRUE = 42
    FALSE = 54


    def __bool__(self):
        return self == MyBool.TRUE


#
# testing
#
mytrue = MyBool.TRUE
try:
    print(int(mytrue)) #this fails
except TypeError as te:
    print(te)

asbool = bool(mytrue)
if mytrue:
    print("yep")

myfalse = MyBool.FALSE
if myfalse:
    print("nope")

---
I would never use such a thing, and I would be annoyed if I can across code that did. As has been said (beaten to death?) Python has an existing well-understood boolean type.




More information about the Python-list mailing list