Sub topic 2
Unions and Values That May Be `None`
Assume you know Python functions, variables, list, dict, and basic package commands. This chapter uses Python 3.10 or later, where | joins types.
Unions and Optional Values
A union says that a value may have one of several types. For example, int | str means an integer or a string. None is Python's single value for “no result,” so str | None describes a string that may be absent.
def find_user(user_id: int, users: dict[int, str]) -> str | None:
return users.get(user_id)
name = find_user(1, {1: "Ada"})The return annotation tells readers and static type checkers that name might be None. Older code may write Optional[str], which means the same thing.
Narrowing Types with Checks
Type narrowing is using a condition to reduce a broad type to a more specific one. Check for None before calling string methods:
if name is not None:
print(name.upper())
else:
print("User not found")Inside the first branch, a checker knows that name is a str. Do not rely only on a truthiness check when empty strings are valid values.
`Any`, `object`, and Gradual Typing
Any disables most type checking for a value. Use it at uncertain boundaries only, because operations on Any are accepted without proof.
object means any Python object, but it preserves checking. You must test or narrow an object before using type-specific operations.
def describe(value: object) -> str:
if isinstance(value, str):
return value.upper()
return repr(value)Adding hints gradually is safer when you replace Any with precise types or object plus checks.
Callable Types
A Callable annotation describes a function passed as an argument.
from collections.abc import Callable
def apply(func: Callable[[int], int], value: int) -> int:
return func(value)
print(apply(lambda n: n * 2, 21))This requires one integer parameter and an integer result.
Type Aliases
A type alias gives a complex type a readable name.
from collections.abc import Callable
Formatter = Callable[[str], str]
def format_name(value: str, formatter: Formatter) -> str:
return formatter(value)Aliases reduce repetition, but choose names that describe the role of the type.
Exercise
Why must code check name is not None before calling name.upper()?
Show answer
Because name has type str | None; the check proves to a static checker that this branch contains a str.