Sub topic 9
Checking for None and using None as a default
This chapter assumes you know how truthiness works and the difference between is and ==. It covers the two jobs None does most often: marking a missing value and serving as a safe default argument.
Test for None with is
None is a singleton: only one None object exists in a running program. Because of that, an identity check is the right test.
result = None
if result is None:
print("no result") # no result
if result is not None:
print("got a value")Write is not None, not not result is None. Both work, but the first reads as a sentence.
Why not use truthiness?
if not value: is true for None, but also for 0, 0.0, "", [] and {}. When those values are legitimate, a truthiness test treats them as missing.
count = 0
print(count == None) # False
print(count is None) # False
print(not count) # TrueThe count is zero, which is a real value. Use is None when the question is "was a value supplied?" Use plain truthiness when the question is "is there anything in it?"
| You want to know | Write |
|---|---|
| Is the value missing? | `x is None` |
| Is a value present? | `x is not None` |
| Is a container empty or falsy? | `not x` |
None as a default argument
Default values are evaluated once, when the function is defined. A mutable default such as a list is therefore shared by every call.
def bad_append(item, items=[]):
items.append(item)
return items
print(bad_append(1)) # [1]
print(bad_append(2)) # [1, 2]The second call sees the list the first call modified. The fix is to use None as the default 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]Each call that omits items gets a fresh list. The same pattern applies to dictionaries, sets, and any other mutable object.
Why `or` is a risky shortcut
You may be tempted to write items = items or []. This replaces every falsy argument, not only None.
def connect(retries=None):
if retries is None:
retries = 3
return retries
def connect_or(retries=None):
return retries or 3
print(connect(0)) # 0
print(connect_or(0)) # 3The caller asked for zero retries. The or version silently changed that to three. The is None version respects it.
Functions that return None
A function with no return statement returns None. Methods that change an object in place, such as list.sort() and list.append(), also return None.
numbers = [3, 1, 2]
sorted_numbers = numbers.sort()
print(sorted_numbers) # None
print(numbers) # [1, 2, 3]Assigning the result of an in-place method is a common source of surprising None values. If you need a new list, use sorted(numbers).
When None is a valid argument
Sometimes None is itself a meaningful value that the caller may want to pass. Then None cannot also mean "not supplied". The usual solution is a private sentinel object.
_MISSING = object()
def lookup(key, default=_MISSING):
data = {"a": 1}
if key in data:
return data[key]
if default is _MISSING:
raise KeyError(key)
return default
print(lookup("a")) # 1
print(lookup("b", None)) # NoneUse this only when you need it. For most functions, None as the default is enough.
Exercise
Write a function add_tag(tag, tags=None) that appends tag to tags and returns the list. If tags is omitted, it must start from a new empty list on every call. Then explain why add_tag("x", []) must return a list that is the same object the caller passed.
Show answer
def add_tag(tag, tags=None):
if tags is None:
tags = []
tags.append(tag)
return tags
The check is tags is None, not not tags. An empty list passed by the caller is falsy but not None, so the function keeps it and appends to the caller's own list. A truthiness check would replace it with a new list, and the caller's list would stay empty.