Thursday, July 5, 2012

IDKTAP #2: Booleans as fancy integers

I Didn't Know That About Python uncovers surprising tidbits about our favorite programming language. 

In Python, a Boolean (type bool) is a subtype of integers. True is equal to 1 and False is equal to 0.

True  == 1   # True
False == 0   # True

The special methods called __str__ and __repr__ define how an object is converted to a string and how it is represented in an interactive context, respectively. So bool is basically implemented like this:

class bool(int):
    def __str__(self):
        return "True" if self else "False"
    __repr__ = __str__


True, False = bool(1), bool(0)

(There are some other details I'm glossing over, such as the fact that True and False are singletons and only ever have one instance. That is, bool(1) is always the same object. The example above does not have this behavior. For a fun exercise, try adding it.)

The surprising thing is that in Python 2, True and False are simply built-in identifiers assigned to two specific bool singletons. This means that they can be reassigned:

True = 3

This will very likely cause quite odd behavior in your programs, which is why Python 3 reserves True and False as actual language keywords and doesn't let you reassign them. Still, issubclass(bool, int) remains True.

1 comment: