in Projects, Programming, Technology

Python Truthiness and Truth Table

I thought I might be able to find more fuel for my anti-python argument by investigating exactly what objects are equal to each other (generate a truth table). Actually, the python truth table is actually, very reasonable.

Also, I wanted to be confident of what values are considered True or False.

The one best practice related to this – that a colleague taught me – is to use x is None instead of use if x == None: ... because None could be equal to any object depending on its implementation of __eq__.

This is a pure and beautiful sight compared to to Javascript or PHP. It is a little surprising to me that [] == [] since I would expect them to be two different list instances, but I would expect equality for (,) = (,) (identical tuples).

There are a few nuances when considering truthiness, however. If you’ve got code that reads if x: ... The following values for x are treated as false:

  • None
  • False
  • zero of any numeric type. Like these: 00L0.00j.
  • any empty string, tuple, or array.  ''()[].
  • an empty dictionary, for example, {}.
  • instances of user-defined classes, if the class defines a __nonzero__() or __len__() method and that method returns the integer 0 or boolean value False

Everything else is truthy (considered equal to True).

Python Truthiness

Here’s the code I used to generate the tables above.

import math
values = [
True, False, 1, 0, 1, "true", "false", "1", "0", "-1", "", None, math.inf, math.inf, [], {}, [[]], [0], [1]
]
print("Truth Table")
print("———–")
for value in values:
print(f"\t", end="")
print(value, end="")
print("")
for value in values:
print(value, end="\t")
for value2 in values:
print(value == value2, end="\t")
print("")
print("\n\nTruthiness")
print("———-")
for value in values:
truthy = True if value else False
print(f"{value}\t{truthy}")
view raw truthiness.py hosted with ❤ by GitHub

What do you think?

This site uses Akismet to reduce spam. Learn how your comment data is processed.