Sub topic 3
Checking for `None` and Using `None` as a Default
Assume you know variables, functions, if statements, and built-in types such as int, str, list, and dict.
Check for `None`
None is Python’s singleton value for “no value.” Use identity testing, is, rather than equality testing, ==:
result = None
if result is None:
print("No result")
elif result is not None:
print(result)is asks whether two references are the same object. == asks whether two objects have equal values. The idiomatic checks are value is None and value is not None.
A common function pattern uses None to mean that an argument was omitted:
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
print(add_item("a")) # ['a']
print(add_item("b")) # ['b']Creating the list inside the function gives each call a fresh list.
Related Boolean Tools
bool is a subclass of int. Therefore, True behaves like 1 and False like 0 in arithmetic:
print(True + True) # 2
print(isinstance(False, int)) # True
print(any(n > 2 for n in [1, 2, 3])) # True
print(all(n > 0 for n in [1, 2, 3])) # Trueany() returns true when at least one item is truthy. all() returns true when every item is truthy. all([]) is true because no item violates the condition.
Pitfalls and Custom Objects
float("nan") is unequal even to itself. Also, Python 3 does not order None with numbers, so None < 1 raises TypeError.
Python calls __bool__() for custom truthiness. If it is absent, Python uses __len__(). Equality can be customized with __eq__():
class Basket:
def __init__(self, items):
self.items = list(items)
def __len__(self):
return len(self.items)
def __eq__(self, other):
return isinstance(other, Basket) and self.items == other.items
print(bool(Basket([]))) # False
print(Basket([1]) == Basket([1])) # TrueExercise
Why should a default list argument usually be replaced with None?
Show answer
A list created in the function body is fresh for each call, so calls do not share mutable state.