Sub topic 12
Common pitfalls
This chapter collects the mistakes that come up most often when you work with booleans, comparisons, and None. It assumes you know the basics of bool, truthiness, and/or/not, and the difference between is and ==. Each pitfall below shows the failure, explains the mechanism behind it, and gives a safer pattern.
Falsy values are not the same as None
Truthiness treats 0, 0.0, "", [], {}, and None alike: all are false. That is convenient, but it hides a difference when you want to ask "was a value supplied?"
def describe(count=None):
if not count:
return "no count given"
return f"count is {count}"
print(describe()) # no count given
print(describe(0)) # no count given <- wrong: 0 was givenA caller who passes 0 supplied a real value. The test not count cannot tell 0 from a missing argument. Test for None explicitly:
def describe(count=None):
if count is None:
return "no count given"
return f"count is {count}"
print(describe()) # no count given
print(describe(0)) # count is 0The same trap appears with or defaults:
def connect(timeout=None):
timeout = timeout or 30 # 0 becomes 30
return timeout
print(connect(0)) # 30, but the caller asked for 0Write timeout = 30 if timeout is None else timeout when 0, "", or an empty list are valid inputs.
Mutable default arguments
Default values are evaluated once, when the def statement runs, not on each call. A mutable default such as a list is therefore shared by every call that omits the argument.
def append_item(item, items=[]):
items.append(item)
return items
print(append_item(1)) # [1]
print(append_item(2)) # [1, 2] <- surprise
print(append_item(3)) # [1, 2, 3]All three calls mutate the same list object stored on the function. The standard fix is a None default, tested with is None:
def append_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
print(append_item(1)) # [1]
print(append_item(2)) # [2]
print(append_item(0, [])) # [0]Here is None matters. If you wrote if not items:, a caller who passed their own empty list would have it silently replaced by a new one, and their list would never receive the item.
def append_item_bad(item, items=None):
if not items: # an empty list passed by the caller is falsy
items = []
items.append(item)
return items
mine = []
append_item_bad(5, mine)
print(mine) # [] <- the caller's list was ignoredNaN is not equal to anything
float("nan") ("not a number") is defined by the IEEE 754 floating-point standard to compare unequal to everything, including itself. Python follows that rule.
nan = float("nan")
print(nan == nan) # False
print(nan != nan) # True
print(nan < 1, nan > 1) # False FalseConsequences:
x == float("nan")is never true, so it cannot detect NaN.- Sorting or taking
min/maxof data containing NaN gives order-dependent results, because every ordering comparison is false. nan in [nan]isTruefor the same object, because containment checks identity before equality. A different NaN object is not found.
import math
nan = float("nan")
print(nan in [nan]) # True (same object, identity check)
print(float("nan") in [nan]) # False (different object)
print(math.isnan(nan)) # TrueUse math.isnan(x) to detect NaN. The expression x != x also works but is harder to read. For Decimal or NumPy values, use the equivalents for those types (Decimal.is_nan(), numpy.isnan).
Ordering None against other values
Python 2 allowed None < 1. Python 3 removed implicit cross-type ordering, so it raises TypeError.
try:
None < 1
except TypeError as e:
print("TypeError:", e)
# TypeError: '<' not supported between instances of 'NoneType' and 'int'This usually surfaces in data work, for example sorting a list that contains missing values:
scores = [3, None, 1]
try:
sorted(scores)
except TypeError as e:
print("TypeError:", e)
print(sorted(s for s in scores if s is not None)) # [1, 3]
print(sorted(scores, key=lambda s: (s is None, s or 0))) # [1, 3, None]The key function sorts each value as a tuple. Items where s is None is True sort after those where it is False, which puts None last. The s or 0 part replaces None with 0 so the second tuple elements are always comparable. Note that s or 0 is safe here only because 0 and None are swapped for the same placeholder; for other uses, remember the falsy pitfall above.
Equality is different from ordering. None == 1 is simply False and never raises.
Chained comparisons that do not mean what you think
Chaining means a < b < c is a < b and b < c, with b evaluated once. That works as expected for ranges, but it also applies to operators you might not expect to chain, such as ==, is, and in.
print(1 < 2 < 3) # True
print(3 > 2 > 1) # True
print(1 == 1 < 2) # True (1 == 1 and 1 < 2)
print(False == False in [False]) # True, but unclearTwo cases cause trouble:
- A reader who comes from mathematics may see
a == b == cas fine (it is: all three equal) buta != b != cas "all different". It only meansa != b and b != c. The values1 != 2 != 1isTrueeven though the first and last are equal. - Mixing
inorisinto a chain reads as something else. Split it into separate conditions or add parentheses.
print(1 != 2 != 1) # True: only adjacent pairs are comparedComparing booleans with True and False
Writing == True is redundant and can be wrong, because equality with True means equality with 1.
flag = 2
print(bool(flag)) # True
print(flag == True) # False (2 != 1)
if flag:
print("truthy") # runsPrefer if flag: and if not flag:. The one exception is when you must tell True apart from other truthy values, for example an API that accepts True, False, or a number. In that case, use is True, and document why.
def set_verbose(value):
if value is True:
return "on"
if value is False:
return "off"
raise TypeError("verbose must be a bool")
print(set_verbose(True)) # onbool is an int
Because bool subclasses int, True and False behave as 1 and 0 in arithmetic, in dictionary keys, and in isinstance checks.
print(isinstance(True, int)) # True
print(True + True) # 2
d = {1: "one"}
d[True] = "true"
print(d) # {1: 'true'}
print({0, False, 0.0}) # {0}Two practical effects:
- Validation with
isinstance(x, int)acceptsTrueandFalse. If booleans should be rejected, checkisinstance(x, bool)first or usetype(x) is int. Trueand1collide as dictionary keys and set members, because they are equal and hash the same.
Summing booleans is a legitimate idiom for counting matches: sum(n > 2 for n in nums).
and/or return operands, not booleans
and and or return one of their operands. That is useful for defaults but surprising when you expect a bool.
print("a" and "b") # b
print([] and 1) # []
print(0 or "default") # default
print(bool([] and 1)) # FalseIf a function is documented to return a bool, wrap the expression in bool(...) or use a comparison so callers get True or False, not [] or "b".
The other consequence is precedence. not binds tighter than and, which binds tighter than or.
a, b, c = True, False, True
print(a or b and c) # True (a or (b and c))
print((a or b) and c) # True
a, b, c = True, False, False
print(a or b and c) # True
print((a or b) and c) # FalseAdd parentheses whenever you mix and and or.
Short-circuiting hides side effects
The right side of and/or is not evaluated if the left side settles the result. That is useful as a guard, but it means side effects may not run.
def check(name, result):
print("checking", name)
return result
if check("a", False) and check("b", True):
pass
# checking a (b is never evaluated)Do not put required work, such as logging, increments, or pop(), in the right-hand operand. Also note that any() and all() stop at the first deciding item, so a generator passed to them may be left partly consumed.
nums = iter([1, 5, 2, 8])
print(any(n > 3 for n in nums)) # True
print(list(nums)) # [2, 8]any() and all() on empty input
all([]) is True and any([]) is False. Logically, "every item passes" is vacuously true when there are no items. This becomes a bug when the empty case should count as a failure.
orders = []
print(all(o["paid"] for o in orders)) # True, but nothing was paid
if orders and all(o["paid"] for o in orders):
print("all paid")
else:
print("nothing to confirm") # nothing to confirmCheck for emptiness first when "no items" needs its own outcome.
Truthiness of strings and containers
Any non-empty string is true, including "0" and "False". This breaks code that converts text input to booleans.
print(bool("False"), bool("0"), bool(" ")) # True True True
def parse_bool(text):
value = text.strip().lower()
if value in {"true", "1", "yes"}:
return True
if value in {"false", "0", "no"}:
return False
raise ValueError(f"not a boolean: {text!r}")
print(parse_bool("False")) # FalseSimilarly, a list containing falsy items is itself true: bool([0]) is True. Truthiness looks only at the container's length, not its contents.
Custom classes: __bool__, __len__, and __eq__
If you define __len__ on a class, empty instances become falsy, which may be unintended for an object that is a "thing" rather than a collection. Define __bool__ to override this explicitly. Python checks __bool__ first and falls back to __len__.
Defining __eq__ has a second effect: Python sets __hash__ to None, so instances become unhashable unless you also define __hash__.
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __eq__(self, other):
if not isinstance(other, Point):
return NotImplemented
return (self.x, self.y) == (other.x, other.y)
def __hash__(self):
return hash((self.x, self.y))
print(Point(1, 2) == Point(1, 2)) # True
print(Point(1, 2) == (1, 2)) # False
print(len({Point(1, 2), Point(1, 2)})) # 1Returning NotImplemented for unknown types lets Python try the other operand's __eq__ and then fall back to False, instead of raising or guessing.
Summary table
| Pitfall | Symptom | Safer pattern |
|---|---|---|
| `if not x` for "missing" | `0` or `""` treated as absent | `if x is None` |
| Mutable default | State shared between calls | `None` default, create inside |
| NaN equality | `nan == nan` is `False` | `math.isnan(x)` |
| Ordering `None` | `TypeError` in sort | Filter or use a `key` function |
| `== True` | `2 == True` is `False` | `if flag:` |
| `isinstance(x, int)` | Accepts `True` | Check `bool` first |
| `all([])` | `True` for no items | Check emptiness first |
| `bool("False")` | `True` | Parse explicitly |
| `__eq__` without `__hash__` | Unhashable instances | Define both |
Exercise
The function below should return the discount percentage, using 10 when no discount is passed. A caller passes discount=0 to mean "no discount", but gets 10. Explain the cause and write the fix.
def price_discount(discount=None):
discount = discount or 10
return discount
Show answer
discount or 10 returns the right operand whenever the left operand is falsy, and 0 is falsy, so an explicit 0 is replaced by 10. The fix is to test for None only:
def pricediscount(discount=None):
if discount is None:
discount = 10
return discount
Now `pricediscount() returns 10 and price_discount(0)` returns 0.
Exercise
What do these three expressions print, and why? (1) print(all([])) (2) print(float("nan") == float("nan")) (3) print(1 != 2 != 1)
Show answer
(1) True, because all of an empty iterable is vacuously true. (2) False, because NaN compares unequal to everything, including another NaN. (3) True, because the chain means 1 != 2 and 2 != 1; only adjacent pairs are compared, so the first and last values are never compared.