None and Optional

suggest change

None is Python's "no value" object. Functions return it when they have nothing to return, APIs use it to say "not found" or "not set", and JSON null becomes None when you parse it.

Optional is the type hint side of the same story: int | None (or the older Optional[int]) tells readers and type checkers that a value may be missing, and forces code that uses it to handle that case.

This article covers:

What None is

None is the only instance of the type NoneType. There is exactly one None object in a running program:

print(type(None))
print(None is None)
print(id(None) == id(None))

a = None
b = None
print(a is b)
<class 'NoneType'>
True
True
True

None is falsy, it prints as None, and its repr is also None:

print(bool(None))
print(str(None), repr(None))
print([None, 1, "x"])
False
None None
[None, 1, 'x']

NoneType is available as types.NoneType (Python 3.10+), which is occasionally useful for isinstance checks:

import types

print(isinstance(None, types.NoneType))
print(isinstance(0, types.NoneType))
True
False

Functions return None by default

A function that ends without a return, or uses a bare return, returns None:

def greet(name):
    print(f"Hello, {name}")

def check(x):
    if x < 0:
        return
    print("non-negative")

result = greet("Ann")
print(result)
print(check(-1))
Hello, Ann
None
None

This is the source of a classic bug: many methods that modify an object in place return None, not the modified object.

nums = [3, 1, 2]
nums = nums.sort()   # sort() sorts in place and returns None
print(nums)
None

Use nums.sort() on its own line, or sorted(nums) which returns a new list. The same applies to list.append, list.reverse, dict.update, random.shuffle and others.

Testing for None: use is

Always compare with is None / is not None:

def describe(value):
    if value is None:
        return "missing"
    return f"got {value!r}"

print(describe(None))
print(describe(0))
print(describe(""))
missing
got 0
got ''

There are two reasons to prefer is over ==.

== can be overridden. A class can define __eq__ to return anything, including True when compared with None. is checks identity and can't be fooled:

class AlwaysEqual:
    def __eq__(self, other):
        return True

x = AlwaysEqual()
print(x == None)
print(x is None)
True
False

Libraries like NumPy and pandas overload == to work element-wise, so arr == None returns an array, not a bool. Linters (ruff rule E711, pycodestyle) flag == None for this reason.

is None is also slightly faster, because it's a pointer comparison and doesn't call any method.

is None vs truthiness

if not value: is true for None, but also for 0, 0.0, "", [], {} and any other falsy value. Use it only when all of those should be treated the same:

def set_volume(level=None):
    if not level:          # bug: 0 is a valid volume
        level = 50
    return level

print(set_volume())
print(set_volume(0))
50
50
def set_volume(level=None):
    if level is None:      # correct: only a missing value gets the default
        level = 50
    return level

print(set_volume())
print(set_volume(0))
50
0

The same pitfall exists with x or default, which replaces every falsy value, not only None. See Testing if an object is None and assigning it.

Python has no ?? (null-coalescing) operator. The idiomatic replacement is a conditional expression:

timeout = 0
effective = timeout if timeout is not None else 30
print(effective)
0

None as a default argument

Default values are evaluated once, when the function is defined. Using a mutable default such as [] shares one list between all calls. The standard fix is to default to None and create the object inside the function:

def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

print(add_item("a"))
print(add_item("b"))
print(add_item("c", ["x"]))
['a']
['b']
['x', 'c']

More on this in Defining a function with optional mutable arguments.

When None is a valid value: sentinels

Sometimes None is a legitimate value, so you can't use it to mean "argument not provided". For example, a cache that can store None results, or an update() function where passing None means "clear this field".

Create a unique sentinel object and compare against it with is:

_MISSING = object()

def update_user(user, *, email=_MISSING, phone=_MISSING):
    if email is not _MISSING:
        user["email"] = email
    if phone is not _MISSING:
        user["phone"] = phone
    return user

user = {"email": "ann@example.com", "phone": "555-0100"}
print(update_user(dict(user), phone=None))     # clear phone
print(update_user(dict(user), email="a@b.c"))  # phone untouched
{'email': 'ann@example.com', 'phone': None}
{'email': 'a@b.c', 'phone': '555-0100'}

The same trick distinguishes "key missing" from "key present with value None" when reading a dict:

_MISSING = object()
data = {"a": None}

for key in ("a", "b"):
    value = data.get(key, _MISSING)
    if value is _MISSING:
        print(key, "-> not present")
    else:
        print(key, "->", value)
a -> None
b -> not present

key in data works too, but get with a sentinel does a single lookup.

Optional type hints

When a value can be None, say so in its type hint. Since Python 3.10 the preferred spelling is a union with None:

def find_user(user_id: int) -> str | None:
    users = {1: "ann", 2: "bob"}
    return users.get(user_id)

print(find_user(1))
print(find_user(3))
ann
None

str | None means "a str or None". Before Python 3.10 you write the same thing with the typing module:

from typing import Optional, Union

def find_user(user_id: int) -> Optional[str]: ...
def find_user2(user_id: int) -> Union[str, None]: ...

All three spellings are equivalent to type checkers. Optional[str] is still common in older code bases; new code should use str | None. If you need the | syntax on Python 3.8 or 3.9, add from __future__ import annotations at the top of the module so annotations aren't evaluated at runtime.

"Optional" does not mean "optional argument"

The name Optional is misleading. Optional[int] means "may be None". It says nothing about whether the caller can omit the argument. These are different things:

def f1(x: int | None): ...        # required, but may be None
def f2(x: int = 0): ...           # optional, but never None
def f3(x: int | None = None): ... # optional, and may be None

f1() without arguments is a TypeError. f2(None) is a type error reported by the checker.

Type checkers used to accept def f(x: int = None) and silently treat it as int | None ("implicit Optional"). PEP 484 was changed to forbid that, and mypy rejects it by default since version 0.990:

def f(x: int = None) -> int:
    return x or 0
$ mypy app.py
app.py:1: error: Incompatible default for parameter "x" (default has type "None", parameter has type "int")  [assignment]
app.py:1: note: PEP 484 prohibits implicit Optional. Accordingly, mypy has changed its default to no_implicit_optional=True
app.py:1: note: Use https://github.com/hauntsaninja/no_implicit_optional to automatically upgrade your codebase
Found 1 error in 1 file (checked 1 source file)

Write x: int | None = None explicitly.

Type checkers make you handle None

The real value of X | None shows up when you run a type checker such as mypy or pyright. They refuse to let you use the value as X until you've ruled out None:

def find_user(user_id: int) -> str | None:
    return {1: "ann"}.get(user_id)

name = find_user(1)
print(name.upper())
$ mypy app.py
app.py:5: error: Item "None" of "str | None" has no attribute "upper"  [union-attr]
Found 1 error in 1 file (checked 1 source file)

This is the bug that would otherwise crash at runtime with AttributeError: 'NoneType' object has no attribute 'upper'.

Narrowing

After a check, the type checker "narrows" the type inside the branch:

def greeting(name: str | None) -> str:
    if name is None:
        return "Hello, stranger"
    # here the type of name is str
    return "Hello, " + name.title()

print(greeting(None))
print(greeting("ann"))
Hello, stranger
Hello, Ann

Checks that narrow X | None to X:

assert is handy when you know the value can't be None at that point, for example right after initialization. Keep in mind asserts are removed when Python runs with -O, so don't use them to validate input:

import re

m = re.match(r"(\d+)-(\d+)", "10-20")
assert m is not None
start, end = m.groups()
print(start, end)
10 20

Narrowing works on local variables. For attributes, a checker may forget the narrowing after a function call because the call could have changed the attribute. Copy the attribute to a local variable first:

from dataclasses import dataclass

@dataclass
class Node:
    value: int
    next: "Node | None" = None

def second_value(node: Node) -> int | None:
    nxt = node.next
    if nxt is None:
        return None
    return nxt.value

print(second_value(Node(1, Node(2))))
print(second_value(Node(1)))
2
None

Optional fields

Use X | None with a None default for fields that may be absent:

from dataclasses import dataclass

@dataclass
class User:
    name: str
    email: str | None = None
    age: int | None = None

u = User("ann", age=31)
print(u)
contact = u.email if u.email is not None else "no email"
print(contact)
User(name='ann', email=None, age=31)
no email

Return None or raise an exception?

Both are valid ways to report "no result". Pick based on how expected the situation is:

A common approach is to offer both, like dict.get vs dict[key]:

class UserRepo:
    def __init__(self) -> None:
        self._users = {1: "ann", 2: "bob"}

    def find(self, user_id: int) -> str | None:
        return self._users.get(user_id)

    def get(self, user_id: int) -> str:
        user = self.find(user_id)
        if user is None:
            raise KeyError(f"no user with id {user_id}")
        return user

repo = UserRepo()
print(repo.find(3))
try:
    repo.get(3)
except KeyError as e:
    print("error:", e)
None
error: 'no user with id 3'

Avoid functions that return None on some error paths and raise on others. Callers then have to handle both, and usually forget one.

Useful patterns

Default values from lookups

Many standard functions take a default and return it instead of raising:

config = {"host": "localhost"}

print(config.get("port"))          # None if missing
print(config.get("port", 8080))    # default if missing

nums = [1, 3, 5]
first_even = next((n for n in nums if n % 2 == 0), None)
print(first_even)

class Obj: pass
print(getattr(Obj(), "missing", None))
None
8080
None
None

Note that config.get("port", 8080) returns the default only when the key is missing. If the key exists with value None, you get None.

Filtering out None

values = [3, None, 0, None, 7]

print([v for v in values if v is not None])
print(list(filter(None, values)))   # also drops 0!
[3, 0, 7]
[3, 7]

filter(None, ...) removes all falsy values, so it drops 0 as well. Use the explicit comprehension when 0, "" or False are meaningful.

Sorting values that contain None

None can't be compared with numbers or strings, so sorting a mixed list fails:

scores = [70, None, 85, None, 60]
try:
    sorted(scores)
except TypeError as e:
    print(e)
'<' not supported between instances of 'NoneType' and 'int'

Use a key that puts None first or last. Tuples compare element by element, and False < True:

scores = [70, None, 85, None, 60]

print(sorted(scores, key=lambda s: (s is None, s or 0)))   # None last
print(sorted(scores, key=lambda s: (s is not None, s or 0)))  # None first
[60, 70, 85, None, None]
[None, None, 60, 70, 85]

Calling a method only if the value isn't None

Python has no ?. operator. Spell it out with a conditional expression:

import re

m = re.search(r"\d+", "order 1234")
number = int(m.group()) if m is not None else None
print(number)

m = re.search(r"\d+", "no digits")
number = int(m.group()) if m is not None else None
print(number)
1234
None

With the walrus operator (Python 3.8+) you can combine the call and the check:

import re

for line in ["id=42", "no id here"]:
    if (m := re.search(r"id=(\d+)", line)) is not None:
        print("found", m.group(1))
    else:
        print("not found")
found 42
not found

None and JSON

json maps JSON null to None and back:

import json

data = json.loads('{"name": "ann", "email": null}')
print(data)
print(data["email"] is None)
print(json.dumps({"phone": None}))
{'name': 'ann', 'email': None}
True
{"phone": null}

When reading JSON, a key can be missing or present with null. data.get("email") returns None in both cases; use "email" in data if the difference matters.

Summary

Task Use
Test for None x is None, x is not None
Default when value is None x if x is not None else default
Mutable default argument def f(items=None) + if items is None: items = []
None is a valid value a sentinel _MISSING = object()
Type hint for "may be None" X | None (3.10+), Optional[X] before that
Optional argument that may be None x: X | None = None
Tell the type checker it's not None if x is None: return, assert x is not None
First match or None next((v for v in items if cond(v)), None)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents