Search code examples
pythonbooleanlogicpython-3.4truthiness

Mysterious Cases of Booleans, Equivalencies, and Object Identifiers


First Mystery of Strings:
How come bool('foo') returns True?

if
'foo' == True returns False
'foo' == False returns False
'foo' is True returns False
'foo' is False returns False

Second Mystery of Integers:
How come bool(5) returns True?

if
5 == True returns False
5 == False returns False
5 is True returns False
5 is False returns False

Third Mystery of Zeros:
How come bool(0) returns False?

if
0 == True returns False
0 == False returns True <-- Special Case
0 is True returns False
0 is False returns False

I am aware of some of the truthiness of Python, however, this all seems a bit mysterious. Someone mind shedding some light on this?


Solution

  • you need to read this: https://docs.python.org/2/library/stdtypes.html#truth-value-testing

    'foo' == True  # -> False
    '' == True     # -> False
    '' == False    # -> False
    

    will always be False. a string does not equal a bool. but - yes - bool('non-empty-str') -> True; bool('') -> False.

    and so on for you other 'mysteries'.

    is compares the identities id() of two objects (there are some mysteries here as well: What's with the Integer Cache inside Python?)

    also this may be interesting: Is False == 0 and True == 1 in Python an implementation detail or is it guaranteed by the language?