#
9 PEP 285: A Boolean Type

A Boolean type was added to Python 2.3. Two new constants were added to the `__builtin__` module, `True` and `False`. (`True` and `False` constants were added to the built-ins in Python 2.2.1, but the 2.2.1 versions are simply set to integer values of 1 and 0 and aren't a different type.)

The type object for this new type is named `bool`; the constructor for it takes any Python value and converts it to `True` or `False`.

    >>> bool(1)
    True
    >>> bool(0)
    False
    >>> bool([])
    False
    >>> bool( (1,) )
    True

Most of the standard library modules and built-in functions have been changed to return Booleans.

    >>> obj = []
    >>> hasattr(obj, 'append')
    True
    >>> isinstance(obj, list)
    True
    >>> isinstance(obj, tuple)
    False

Python's Booleans were added with the primary goal of making code clearer. For example, if you're reading a function and encounter the statement `return 1`, you might wonder whether the `1` represents a Boolean truth value, an index, or a coefficient that multiplies some other quantity. If the statement is `return True`, however, the meaning of the return value is quite clear.

Python's Booleans were not added for the sake of strict type-checking. A very strict language such as Pascal would also prevent you performing arithmetic with Booleans, and would require that the expression in an `if` statement always evaluate to a Boolean result. Python is not this strict and never will be, as PEP 285 explicitly says. This means you can still use any expression in an `if` statement, even ones that evaluate to a list or tuple or some random object. The Boolean type is a subclass of the `int` class so that arithmetic using a Boolean still works.

    >>> True + 1
    2
    >>> False + 1
    1
    >>> False * 75
    0
    >>> True * 75
    75

To sum up `True` and `False` in a sentence: they're alternative ways to spell the integer values 1 and 0, with the single difference that `str()` and `repr()` return the strings `'True'` and `'False'` instead of `'1'` and `'0'`.

See Also:

PEP 285, Adding a bool type
  Written and implemented by GvR.