Sub topic 12
Common pitfalls
This chapter assumes you know basic Python syntax, the built-in types, and the earlier chapters on truthiness, is versus ==, and None. It collects the mistakes that still catch people who know the rules.
Falsy is not the same as None
Truthiness answers "is this value empty or zero?" A None check answers "is a value missing?" These are different questions. 0, "", and [] are all falsy, but none of them is None.
count = 0
print(count == None) # False
print(count is None) # False
print(not count) # True
result = None
if result is None:
print("no result") # no resultIf 0 or an empty string is a valid value in your program, if not value: will treat it as missing. Use is None when you mean "missing".
The mutable default argument
Python evaluates a default value once, when the def statement runs. A list used as a default is therefore shared by every call that omits the argument. The standard fix is to default to None and create the list inside the function.
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]Test with is None, not if not items. If the caller passes their own empty list, not items is true and you would silently replace it with a new list. The caller's list would never receive the item.
NaN is not equal to itself
float("nan") means "not a number". By the IEEE 754 floating-point standard, every comparison with NaN is false, except !=. That includes comparing NaN with itself.
nan = float("nan")
print(nan == nan) # False
print(nan != nan) # True
try:
None < 1
except TypeError as e:
print("TypeError:", e)
# TypeError: '<' not supported between instances of 'NoneType' and 'int'To detect NaN, use math.isnan(x). Do not write x == float("nan"), which is always false.
Ordering None raises TypeError
In Python 3, None has no order relative to numbers or strings. None < 1 raises TypeError. This often appears inside sorted() or max() when a list contains a missing value. Filter out the None values first, or supply a sort key that handles them.
scores = [3, None, 1]
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 returns a tuple. Tuples compare element by element, so every None sorts after the numbers, because False < True.
Other traps
"0"and"False"are non-empty strings, so both are true.bool("False")isTrue.True + Trueis2becauseboolis a subclass ofint. Code such assum(flags)works for counting, butTrue == 1can also surprise you when booleans are used as dictionary keys alongside integers.x == Trueis almost never what you want. A value like2is truthy but2 == TrueisFalse. Writeif x:instead.andandorreturn operands, not booleans.x = a or bmay give you a string or list, which matters if you later compare it withis True.- A chained comparison such as
a < b < cis not the same as(a < b) < c. The second form compares a bool withc.
Exercise
This function should add a tag to a list the caller supplies, or to a new list if none is supplied. What is wrong with def add_tag(tag, tags=[]), and how do you fix it? Also, why does if not tags: tags = [] give a wrong result when the caller passes their own empty list?
Show answer
The default [] is created once and shared across calls, so tags accumulate between calls. Fix it with tags=None and if tags is None: tags = []. With if not tags, a caller's empty list is falsy, so it is replaced by a new list and the caller's list never receives the tag.
Exercise
Predict the output of nan = float("nan"), then print(nan == nan, nan in [nan], [nan] == [nan]).
Show answer
It prints False True True. Comparing nan == nan is false. The in operator and list equality first check identity (is) and only then equality, so the same NaN object is found. Two different NaN objects would not match.