Sub topic 9
Checking for None and using None as a default
What you should already know
This chapter assumes you can write functions with default arguments and if statements. It also assumes you know the earlier chapters' main points: None is a single object of type NoneType, every object has a truth value, and is tests identity while == tests equality. Here you will apply those ideas to two everyday jobs: testing whether a value is None, and using None as a default argument.
Where None comes from
You will meet None in several places:
- A function that reaches its end without a
returnstatement returnsNone. dict.get(key)returnsNonewhen the key is missing.re.matchreturnsNonewhen the pattern does not match.- Your own code uses it to mean "not provided yet" or "no result".
import re
def greet(name):
print("Hello,", name)
result = greet("Ada") # prints: Hello, Ada
print(result) # None
match = re.match(r"\d+", "abc")
if match is None:
print("no match") # no match
settings = {"theme": "dark"}
print(settings.get("font")) # NoneEach of these calls hands you a value that you must check before using it. Calling match.group() on a None result raises AttributeError: 'NoneType' object has no attribute 'group'. This is one of the most common runtime errors in Python programs.
Testing for None with is
The standard test is is None, with is not None for the opposite.
value = None
if value is None:
print("missing")
if value is not None:
print("present")Use is because None is a singleton. There is exactly one None object in a running program, so asking "is this the None object?" is both correct and fast. PEP 8, Python's style guide, recommends this form. It also recommends if x is not None over if not x is None, which reads badly and parses differently from what many people expect.
== usually gives the same answer, but it asks the object's own __eq__ method, and that method can say anything:
class Anything:
def __eq__(self, other):
return True
obj = Anything()
print(obj == None) # True
print(obj is None) # FalseSome libraries define == as an elementwise operation. NumPy arrays are one example, where arr == None produces an array of booleans rather than a single answer. The is operator cannot be overridden, so it always gives a plain True or False.
None is not the same as "falsy"
None is false in a boolean context, but so are 0, 0.0, "", [], {}, and False. Writing if not value: therefore lumps them all together. Often that is what you want. Sometimes it is a bug.
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 resultHere is a function that needs the distinction:
def describe(count):
if count is None:
return "missing"
if not count:
return "zero or empty"
return "has value"
print(describe(None)) # missing
print(describe(0)) # zero or empty
print(describe([])) # zero or empty
print(describe(5)) # has valueA reasonable rule: use if x: when you mean "is there anything here?" and if x is None: when you mean "was a value supplied at all?". A user who enters 0 as a quantity has provided an answer. A user who entered nothing has not.
Using None as a default argument
Default values are evaluated once, when the def statement runs, not on each call. If the default is a mutable object such as a list, every call that omits the argument shares that one object.
def append_bad(item, items=[]):
items.append(item)
return items
print(append_bad(1)) # [1]
print(append_bad(2)) # [1, 2]
print(append_bad.__defaults__) # ([1, 2],)The second call did not get a fresh list. It got the list that the first call modified. You can see the stored default in the function's __defaults__ attribute.
The fix is to use None as the default and create the mutable object 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 builds its own list. A caller who passes a list still gets that list modified, which is usually the intended behavior.
The same mechanism affects any default that should be computed per call, such as the current time:
from datetime import datetime
def log(message, when=None):
if when is None:
when = datetime.now()
return f"{when:%Y-%m-%d} {message}"
print(log("started", datetime(2026, 1, 15))) # 2026-01-15 startedIf the signature said when=datetime.now(), the timestamp would be fixed at the moment the function was defined.
The or shortcut and why it misleads
Because or returns one of its operands, many programmers write the default like this:
def connect(host, timeout=None):
timeout = timeout or 30
return host, timeout
print(connect("db1")) # ('db1', 30)
print(connect("db1", 10)) # ('db1', 10)
print(connect("db1", 0)) # ('db1', 30)The last line is the problem. The caller passed 0, perhaps meaning "no timeout" or "fail immediately". Since 0 is falsy, or replaced it with 30. The explicit test avoids this:
def connect(host, timeout=None):
if timeout is None:
timeout = 30
return host, timeout
print(connect("db1", 0)) # ('db1', 0)The or form is fine when every falsy value really should be replaced. The earlier example name or "anonymous" is reasonable, because an empty name is no more useful than a missing one. Decide which meaning you intend and write the test that matches it.
When None is a valid value: sentinels
Sometimes None is itself a value callers may pass. In that case None cannot also mean "not provided". A common solution is a private sentinel, which is a unique object that nobody else can pass by accident.
_MISSING = object()
def get_value(data, key, default=_MISSING):
if key in data:
return data[key]
if default is _MISSING:
raise KeyError(key)
return default
print(get_value({"a": None}, "a")) # None
print(get_value({}, "a", None)) # None
try:
get_value({}, "a")
except KeyError as e:
print("KeyError:", e) # KeyError: 'a'This function can tell apart three cases that None alone would merge: a key holding None, a missing key with an explicit None default, and a missing key with no default at all. The built-in dict.get has a related ambiguity. d.get("k") returns None both when the key is absent and when the stored value is None. If that matters, test with "k" in d.
Use a sentinel only when you need it. For most functions, None as the default is simpler and what readers expect.
None in type hints
When a parameter may be None, say so in its annotation. Python 3.10 and later accept the | form:
def find_user(user_id: int) -> str | None:
users = {1: "ada", 2: "grace"}
return users.get(user_id)
name = find_user(3)
if name is not None:
print(name.upper())
else:
print("unknown user") # unknown userType checkers such as mypy understand the is None and is not None tests and narrow the type inside each branch. A truthiness test like if name: also narrows, but it additionally excludes the empty string, which may not be what you want. On older Pythons, write Optional[str] from the typing module.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| `if x == None:` | Works for most types, but a custom `__eq__` can make it lie | `if x is None:` |
| `if not x:` to detect a missing value | Also true for `0`, `""`, `[]` | `if x is None:` |
| `def f(items=[])` | All calls share one list | `items=None`, then create the list inside |
| `x = x or default` | Replaces valid falsy arguments | `if x is None: x = default` |
| Using the result of `re.match` directly | `AttributeError` on `None` | Test `is None` first |
| `None < 1` | `TypeError` in Python 3 | Check for `None` before comparing |
| Using `return` inside a loop but not after it | Function silently returns `None` | Add an explicit `return` or `raise` for the no-result path |
A decision guide
Read the chart top to bottom. Most code ends up in the is None branch, and the sentinel branch is rare.
Exercises
Exercise
What does this code print, and why? def add(item, bucket=[]): bucket.append(item) return bucket add("a") print(add("b"))
Show answer
It prints ['a', 'b']. The default list is created once when the function is defined, so both calls append to the same list. Rewriting the signature as bucket=None and adding if bucket is None: bucket = [] gives each call its own list, and the output becomes ['b'].
Exercise
A function sets retries = retries or 3. A caller passes retries=0 to disable retrying. What value does the function use, and how do you fix it?
Show answer
It uses 3, because 0 is falsy and or returns its right operand. Fix it with if retries is None: retries = 3, which only replaces a missing argument and keeps an explicit 0.
Exercise
Write a function first_or_none(items) that returns the first element of a list, or None if the list is empty. Then explain why if first_or_none([0, 1]) is None: is the correct way to test its result, and if not first_or_none([0, 1]): is not.
Show answer
def firstornone(items):
if items:
return items[0]
return None
For [0, 1] the function returns 0, which is a real value. is None is False, which is correct. not 0 is True, so the truthiness test would wrongly report that no element was found.