Sub topic 7
None: Python's absence of a value
This chapter assumes you know basic Python syntax (variables, functions, if statements) and the built-in types int, str, list, and dict. It also assumes you have met truthiness in an earlier chapter. Here you learn what None is, where it comes from, and how it fails when you misuse it. The chapters after this one cover is versus == and the standard patterns for testing and defaulting.
What None is
None is a built-in constant that means "no value here". It is the only instance of the type NoneType.
print(type(None)) # <class 'NoneType'>
print(bool(None)) # False
print(repr(None), str(None)) # None None
print(isinstance(None, int)) # FalseFour facts follow from this.
- There is exactly one
Noneobject. EveryNonein your program is the same object. This is called a singleton. Noneis a keyword-like constant. You cannot rebind it. The statementNone = 1is aSyntaxError.Noneis falsy.bool(None)isFalse, soif value:treats it like an empty list or0.Noneis not any other falsy value. It is not0,"",[], orFalse. It has no length, supports no arithmetic, and has almost no methods.
The singleton property is visible if you create a second reference through the type itself:
a = None
b = type(None)()
print(a is b) # True
print(id(a) == id(b)) # TrueCalling NoneType() does not build a new object. It returns the existing None. This is why identity checks work reliably for None, which a later chapter uses.
How None differs from other "empty" values
Many beginners treat None as a synonym for "empty". It is not. The values below are all falsy, but they mean different things.
| Value | Type | `bool(value)` | Meaning |
|---|---|---|---|
| `None` | `NoneType` | `False` | No value, unknown, not applicable |
| `0` | `int` | `False` | The number zero |
| `""` | `str` | `False` | A string with no characters |
| `[]` | `list` | `False` | A list with no items |
| `False` | `bool` | `False` | The boolean false |
A user's age of 0 is a known value. A user whose age was never entered is None. Collapsing the two with a truthiness test is a common source of bugs, and the Pitfalls chapter returns to it.
If you come from other languages, None plays the role of null in Java and JavaScript, nil in Ruby and Go, and NULL in SQL. One difference from SQL is that Python's None == None is True, while NULL = NULL is not true in SQL.
Where None comes from
You rarely type None into a program as often as you receive it. It appears in four main ways, shown in the diagram.
1. Functions without a return value
A function that never executes a return statement returns None. So does a bare return.
def greet(name):
print("Hello,", name)
result = greet("Ada")
print(result) # Noneprint itself returns None. The text on screen is a side effect, not a return value.
2. Branches that fall off the end
This is the subtle version of the same rule. If some paths return a value and others do not, the missing paths return None silently.
def sign(n):
if n > 0:
return "positive"
elif n < 0:
return "negative"
print(sign(5)) # positive
print(sign(0)) # NonePython gives no warning. A function that "sometimes returns a string" is really a function that returns str | None. Either add an explicit final return or make the None result deliberate.
3. Lookups that find nothing
Several standard APIs use None to say "not found".
import re
ages = {"ada": 36}
print(ages.get("grace")) # None
print(ages.get("grace", 0)) # 0
print(re.match(r"\d+", "abc")) # Nonedict.get returns None for a missing key unless you pass a second argument. re.match returns None when the pattern does not match, and a match object when it does. Code that calls .group() on the result without checking will fail on the first non-matching input.
4. Methods that change an object in place
Methods that modify a mutable object usually return None. This signals "I changed the object, there is nothing new to hand back". The list methods sort, append, extend, reverse, and insert all work this way, as do dict.update and set.add.
numbers = [3, 1, 2]
sorted_numbers = numbers.sort()
print(sorted_numbers) # None
print(numbers) # [1, 2, 3]
numbers = [3, 1, 2]
print(sorted(numbers)) # [1, 2, 3] (a new list; numbers is unchanged)Writing numbers = numbers.sort() is a classic mistake. It sorts the list and then replaces your variable with None. Use sorted(numbers) when you want a new list, and numbers.sort() as a standalone statement when you want in-place sorting.
What goes wrong when you use None
None supports almost nothing, so operations on it raise errors. These errors usually appear far from the real cause, because the None was produced earlier and passed along.
value = None
try:
value + 1
except TypeError as e:
print("TypeError:", e)
# TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
try:
value.append(1)
except AttributeError as e:
print("AttributeError:", e)
# AttributeError: 'NoneType' object has no attribute 'append'AttributeError: 'NoneType' object has no attribute ... is one of the most common Python error messages. When you see it, the real question is not "why does None lack this method?" but "which earlier call returned None, and why?". Work backwards from the failing line to the variable's assignment, then to the function that produced it.
Ordering comparisons also fail. None < 1 raises TypeError in Python 3, which also means sorted([3, None, 1]) fails. If your data may contain None, filter it out or supply a key function.
data = [3, None, 1, 2]
cleaned = sorted(x for x in data if x is not None)
print(cleaned) # [1, 2, 3]Equality comparisons do not fail. None == 1 is simply False.
None as a stored value
None is an ordinary object, so you can put it in lists, use it as a dict value, and even use it as a dict key (it is hashable).
record = {"name": "Ada", "email": None}
print(record["email"]) # None
print(record.get("phone")) # None
print("email" in record, "phone" in record) # True FalseThe first two lookups print the same thing, but they mean different things. The key "email" exists and holds "no value". The key "phone" does not exist. If that difference matters, test membership with in rather than comparing get() results.
A related problem arises when None is itself a legitimate argument value. Then you cannot use None to mean "the caller passed nothing". The standard solution is a private sentinel, a unique object that no caller could pass by accident.
_MISSING = object()
def describe(settings, key):
value = settings.get(key, _MISSING)
if value is _MISSING:
return f"{key}: not set"
if value is None:
return f"{key}: explicitly none"
return f"{key}: {value}"
config = {"timeout": None, "retries": 3}
print(describe(config, "timeout")) # timeout: explicitly none
print(describe(config, "retries")) # retries: 3
print(describe(config, "proxy")) # proxy: not setYou will need this only occasionally. Most code can treat None as the one "no value" marker.
Documenting None in signatures
When a function can return None, say so in its type hints. Since Python 3.10 the notation is T | None. Older code writes Optional[T] from the typing module, which means the same thing.
def find_user(users: dict[str, int], name: str) -> int | None:
return users.get(name)
uid = find_user({"ada": 1}, "grace")
print(uid) # NoneHints do not change runtime behavior. Type checkers such as mypy use them to flag code that calls .bit_length() on a result that might be None, which catches the AttributeError above before the program runs.
Practical rules
- Treat every function that can fall off the end as returning
None, and make that deliberate. - Do not assign the result of an in-place method such as
sort()orappend(). - Check the result of lookups that can fail (
dict.get,re.match) before using it. - Do not use
Noneand0or""interchangeably. They carry different meanings. - When you meet
'NoneType' object has no attribute, trace back to where theNonewas created.
Exercise
What do the two print calls output, and why? def total(prices): if prices: return sum(prices) print(total([4, 6])) print(total([]))
Show answer
The first call prints 10. The second prints None. For an empty list, if prices: is false, so the function reaches its end without executing a return statement, and Python returns None implicitly. Adding return 0 after the if block would make the empty case return 0.
Exercise
A learner writes names = ["bo", "al"] and then names = names.sort(). Later, names[0] fails. What is the error message, and how should the code be fixed?
Show answer
names.sort() sorts the list in place and returns None, so names is now None. Then names[0] raises TypeError: 'NoneType' object is not subscriptable. Fix it by calling names.sort() as a standalone statement, or by writing names = sorted(names).
Exercise
Given config = {"timeout": None}, both config.get("timeout") and config.get("retries") return None. How can you tell whether a key is present but set to None, or absent?
Show answer
Use the in operator: "timeout" in config is True and "retries" in config is False. Alternatively, call config.get(key, sentinel) with a private sentinel = object() and compare the result with is.