Sub topic 5
Unions and values that may be None
This chapter assumes you can write annotated functions (name: str, -> int), that you know list[int] and dict[str, int], and that you can run mypy or pyright on a file. It covers how to say "this value is one of several types," and how to say "this value might be None."
Union types
A union type says a value can be any one of several types. Write it with the | operator:
def parse_port(value: str | int) -> int:
if isinstance(value, str):
return int(value)
return value
print(parse_port("8080"))
print(parse_port(80))The checker treats value as str | int at the top of the function. Inside the if, it knows the value is a str. After the if returns, only int is left, so return value matches the declared return type.
A union only allows operations that work for every member. If value is str | int, then value + 1 is an error, because str + int fails. You must first separate the cases, as isinstance does above. The next chapter covers narrowing in detail.
A few properties of unions:
- Order does not matter.
int | strandstr | intare the same type. - Unions flatten.
(int | str) | bytesisint | str | bytes. - A single type is a union of one. Anything that accepts
int | stralso accepts a plainint.
Spelling a union
The | syntax needs Python 3.10 or later. Older code uses the typing module, and you will see both forms.
| Meaning | Python 3.10+ | Any version | Column |
|---|---|---|---|
| int or str | `int \ | str` | `Union[int, str]` |
| str or None | `str \ | None` | `Optional[str]` |
Optional[X] is shorthand for Union[X, None]. The two spellings are identical to a checker. Prefer X | None in new code, because it reads the same way for every union.
On Python 3.7 to 3.9 you can still use | in annotations by adding from __future__ import annotations at the top of the module. This postpones evaluation of annotations, so the | is never executed. It does not help where a type is evaluated at runtime, for example in an alias assignment such as Port = int | str. Use Union there.
Values that may be None
None is a value with its own type, NoneType. Many standard functions return it on failure: dict.get, re.match, os.environ.get, and shutil.which. Writing X | None in a return type tells callers they must handle that case.
def find_user(user_id: int, users: dict[int, str]) -> str | None:
return users.get(user_id)
name = find_user(1, {1: "Ada"})
if name is not None:
print(name.upper())Without the if, the checker rejects the call:
def find_user(user_id: int, users: dict[int, str]) -> str | None:
return users.get(user_id)
name = find_user(2, {1: "Ada"})
print(name.upper())mypy reports an error like Item "None" of "str | None" has no attribute "upper" [union-attr]. Pyright says "upper" is not a known attribute of "None". At runtime, this script fails with AttributeError: 'NoneType' object has no attribute 'upper', because user 2 does not exist. The checker found the bug before the program ran.
flowchart TDThe diagram below shows how the checker follows the value through the code.
None as a default argument
A common use of X | None is a parameter that callers may leave out:
def connect(host: str, timeout: float | None = None) -> str:
if timeout is None:
timeout = 5.0
return f"{host} (timeout {timeout}s)"
print(connect("example.com"))
print(connect("example.com", 2.5))After the if block, the checker knows timeout is a float, because the assignment replaced None on the only path where it could still be None.
Note what the annotation does and does not mean. timeout: float | None says the value may be None. It does not make the parameter optional. A parameter is optional only when it has a default. def f(x: int | None) still requires the caller to pass x, even if the value is None. This is why the word Optional confuses people, and one more reason to prefer | None.
Use None as the default for mutable values such as lists, then create the list inside the function:
def add_tag(tag: str, tags: list[str] | None = None) -> list[str]:
if tags is None:
tags = []
tags.append(tag)
return tags
print(add_tag("a"))
print(add_tag("b"))Each call gets its own list. A default of [] would be shared between calls.
Common errors
- Truthiness instead of
is None.if count:treats0,"", and[]likeNone. Forcount: int | None, the value0is valid data. Useif count is not None:whenNoneis the only case you mean to exclude. Checkers accept both, so the bug appears only at runtime. - Using
==with None. Writex is None, notx == None. Narrowing works withis, and==can be overridden by a class. - Using
dict.getwith a default.users.get(1, "unknown")has typestr, notstr | None. Providing a default removes theNonecase from the result type. - Returning a wide union. A function returning
int | str | list[int] | Nonepushes the work onto every caller. If failure is exceptional, raise an exception and return one type. UseX | Nonewhen "not found" is a normal outcome. - Using
Optionalto mean "has a default". As shown above, these are separate ideas. - Calling
isinstancewith a union on old Python.isinstance(x, int | str)works on 3.10+. On earlier versions, pass a tuple:isinstance(x, (int, str)).
Choosing between a union and its alternatives
Use a union when a value really can have different types, such as a configuration value that accepts a string or an integer. Use X | None when absence is a normal result. Raise an exception when absence is a failure the caller cannot sensibly continue from. Use a default value, such as an empty string or 0, only when that value is a real answer and not a way to hide a missing one.
Exercise
A function is declared def total(values: list[int] | None = None) -> int:. Write the body so that it returns 0 when values is None and the sum otherwise, and say why if not values: is a worse test than if values is None: in a function that must distinguish the two cases.
Show answer
Body: if values is None: return 0 followed by return sum(values). The test if not values: is also true for an empty list, so it would treat [] and None the same. For total the result happens to be 0 either way, but in a function that must tell "not provided" from "provided but empty," is None keeps the two cases separate.
Exercise
Given def lookup(key: str, table: dict[str, int]) -> int | None:, the call lookup("a", {"a": 1}) + 1 is flagged by a checker even though the key exists. Why, and how do you fix the caller?
Show answer
The checker reasons from the declared return type, not from the runtime data. The type is int | None, and None + 1 is invalid, so the addition is an error. Store the result in a variable and test it, for example result = lookup("a", {"a": 1}) then if result is not None: print(result + 1).