Sub topic 5
Union types and optional values
This chapter assumes you can write annotated functions, run mypy or Pyright, and use Python 3.10 or newer. The X | Y syntax is evaluated at runtime, so it needs 3.10 or newer.
What a union type is
A union type says a value can be one of several types. You write it with |:
def describe(value: int | str) -> str:
return f"got {value}"
describe(3)
describe("three")
describe(3.5) # flagged: float is not int | strThe checker accepts int and str arguments and rejects float. Older code spells this Union[int, str] from typing. Both forms mean the same thing, and the | form is the better choice on current Python.
Optional values and None
Many functions return a value or nothing. In a type, "nothing" is None, so an optional value is a union with None:
def find_user(user_id: int) -> str | None:
users = {1: "Ada", 2: "Grace"}
return users.get(user_id)Optional[str] from typing is an older spelling of str | None. The name misleads, because it describes a value that may be None. It does not mark a parameter as skippable. A parameter with a default still needs its own = None.
def greet(name: str | None = None) -> str:
return "Hello, " + (name or "stranger")What the checker lets you do with a union
The checker only allows operations that are valid for every member of the union. This is the most common source of errors in this chapter:
def shout(user_id: int) -> str:
name = find_user(user_id)
return name.upper() # flagged: "None" has no attribute "upper"At runtime this works for ids 1 and 2 and crashes with AttributeError for any other id. The checker reports the problem without running the program. mypy words it as Item "None" of "str | None" has no attribute "upper". Pyright reports that upper is not a known attribute of None.
Handling each case
Check for None before using the value. The next chapter covers narrowing in detail, but the basic pattern is:
def shout(user_id: int) -> str:
name = find_user(user_id)
if name is None:
return ""
return name.upper()After the if, the checker knows name is a str. Other ways to resolve the union include a default (name or "") and raising an exception when None is not acceptable.
Common mistakes
- Using
assert x is not Nonein code that runs with-O. Python removes assertions under-O. The checker still narrows, but the runtime guard is gone. - Returning
Noneimplicitly. If a branch falls off the end of a function declared-> str, the checker reports a missing return. - Widening a return type to avoid errors. Declaring
-> str | Nonepushes aNonecheck onto every caller. Return a plainstrwhen you can.
Unions at a glance
Exercise
A function is declared def load(path: str) -> dict[str, int] | None. The caller writes len(load("a.json")). Will mypy or Pyright accept it? Explain, and show one fix.
Show answer
Neither accepts it. len needs a sized value, and None has no length, so the union fails for the None member. One fix is to check first: data = load("a.json") then if data is not None: print(len(data)). Another is len(load("a.json") or {}).