Sub topic 5
Union types and optional values
This chapter assumes you can annotate functions and variables, run mypy or Pyright from the command line, and read their error output. It also assumes Python 3.10 or newer, so that int | str works at runtime.
What a union type is
A union type says a value may be one of several types. The annotation int | str accepts an int or a str, and nothing else. The checker then requires that every use of the value is valid for each possible member.
You can spell a union in several ways:
| Spelling | Meaning | Notes | Column |
|---|---|---|---|
| `int \ | str` | an int or a str | Preferred. Works at runtime from Python 3.10. |
| `Union[int, str]` | the same type | Older form from `typing`. Needed only for Python 3.9 and earlier. | |
| `Optional[int]` | `int \ | None` | The name suggests an optional argument, but it only means "may be None". |
| `int \ | None` | an int or None | The clearest way to write an optional value. |
Order and nesting do not matter. int | str equals str | int, and int | (str | None) is flattened to int | str | None.
None as the most common union member
Most unions in real code contain None. The standard library returns them often. For example, dict.get returns the value type or None, and re.match returns a match object or None.
ages: dict[str, int] = {"ada": 36}
age = ages.get("ada")
print(age + 1)The checker infers int | None for age. Adding 1 would crash with a TypeError if the key were missing, so both tools report it:
mypy: Unsupported operand types for + ("None" and "int") [operator]
pyright: Operator "+" not supported for "None" (reportOptionalOperand)With strict_optional (on by default in mypy) and in Pyright, None is never silently accepted where int is expected. This is the check that catches the most bugs in typed Python.
The rule for using a union
The checker accepts an operation on a union only if it is valid for every member. If any member fails, the whole expression is an error.
def shout(name: str | None) -> str:
return name.upper()Here str has .upper() but None does not. The tools report it under different names:
mypy: Item "None" of "str | None" has no attribute "upper" [union-attr]
pyright: "upper" is not a known attribute of "None" (reportOptionalMemberAccess)The same rule applies to int | str. Calling .upper() fails because int has no such method. Calling str(x) works because it is valid for both.
Optional does not mean "may be omitted"
int | None describes the value's type. It says nothing about whether a caller may leave the argument out. An argument is omittable only when it has a default.
def retry(count: int | None) -> int:
return 3 if count is None else count
retry(None) # accepted
retry() # error: missing argument, even though None is allowedTo make the argument omittable, give it a default:
def fetch(url: str, timeout: float | None = None) -> str:
limit = 30.0 if timeout is None else timeout
return f"GET {url} (timeout {limit}s)"Do not write timeout: float = None. This is called an implicit optional. It lies about the type, and modern mypy and Pyright both reject it by default.
Removing None safely
The checker only lets you use the narrower type once you have shown it which member you hold. This is called narrowing. The next chapter covers it in depth, but you need three basic forms now.
def describe(value: int | str | None) -> str:
if value is None:
return "nothing"
if isinstance(value, int):
return f"number {value}"
return f"text {value.upper()}"After the None check, value is int | str. After the isinstance check, the remaining type is str, so .upper() is accepted. Use is None and is not None for None checks, since None is a singleton.
The checker also narrows when you assign to a variable that has a declared union type:
value: int | str = 3
print(value.bit_length()) # accepted: the checker narrowed value to intIf you later assign a str to value, the narrowed type changes to str.
A bug the checker cannot see
Truthiness checks look like narrowing, and they do remove None. They also remove every other falsy value, which can change behavior.
def listen(port: int | None = None) -> int:
return port or 8080This type-checks, but listen(0) returns 8080 because 0 is falsy. Port 0 is a real value that means "pick any free port". Use an explicit is None check when 0, "", or an empty list are valid inputs.
def listen(port: int | None = None) -> int:
return 8080 if port is None else portDesigning with unions
Unions in return types push work onto every caller. A function that returns str | None forces each call site to handle None. That is correct when "no result" is a normal outcome, such as a lookup that may miss. It is a poor choice when None signals a failure the caller cannot sensibly handle. In that case, raise an exception and return the plain type.
def find_user(user_id: int, users: dict[int, str]) -> str:
try:
return users[user_id]
except KeyError:
raise LookupError(f"no user {user_id}") from NoneSome further guidelines:
- Keep unions small. A union of five unrelated types usually means the function does too much.
- Avoid
Anyin a union.int | Anycollapses to a type that accepts almost anything, which defeats the check. - Prefer
T | Noneover a sentinel such as-1or"". A sentinel has the same type as real values, so the checker cannot force callers to test for it. - On Python 3.9 or earlier, put
from __future__ import annotationsat the top of the module to useX | Yin annotations. Runtime expressions such asisinstance(x, int | str)still need 3.10.
Common errors
- Using the result of
dict.getorre.matchdirectly. Check forNonefirst, or usedict[key]when a missing key is a bug. - Checking an attribute instead of the variable. After
if self.name is not None, a call to another method may changeself.name. mypy and Pyright still narrowself.namein this case, so copy it to a local variable if you need certainty. - Expecting narrowing to survive a function boundary. A
Nonecheck inside a helper such asis_valid(x)does not narrowxin the caller, unless the helper is declared as aTypeGuardorTypeIs. - Reading
Optional[int]as "optional parameter". The type and the default are separate. - Silencing with
# type: ignore. The fix is nearly always aNonecheck, not an ignore comment.
Exercise
The function below fails type checking. Name the two error messages (in spirit) and rewrite it so it passes while still returning 0 for a stored count of 0. def total(counts: dict[str, int], key: str) -> int: count = counts.get(key) return count + 1
Show answer
counts.get(key) has type int | None, so count + 1 is reported as an unsupported operand for None (mypy [operator], Pyright reportOptionalOperand). Fix it with an explicit None check, not or:
def total(counts: dict[str, int], key: str) -> int:
count = counts.get(key)
if count is None:
return 1
return count + 1
An is None test keeps a stored 0 as 0 and returns 1 only for a missing key.
Exercise
Why is def run(retries: int = None) -> None: a problem, and what is the correct annotation if None should mean "use the default"?
Show answer
The annotation says int, but the default is None, which is not an int. Both checkers reject this implicit optional by default. Write def run(retries: int | None = None) -> None: so that the declared type matches every value the parameter can hold.