Sub topic 10
Restricting values with Literal and Final
This chapter assumes you can annotate parameters and return types, read X | None unions, and run mypy or pyright on a file. Both tools are static checkers: they read your code without running it. Literal and Final give them two more facts to check: which exact values a variable may hold, and which names must never be reassigned.
Literal: allowed values, not just a type
A parameter annotated str accepts any string. Many APIs accept only a few specific strings, such as a file mode. Literal lists the exact values allowed.
from typing import Final, Literal
MAX_RETRIES: Final = 3
Mode = Literal["r", "w"]
def open_log(path: str, mode: Mode) -> None:
print(f"opening {path} in {mode} mode")
open_log("app.log", "r")The call passes "r", which is in Mode, so the checker accepts it. A call such as open_log("app.log", "x") is reported as an error. The interpreter still runs it, because hints are not enforced at runtime.
Literal accepts int, str, bytes, bool, None, enum members, and other literal types. It does not accept variables or expressions. Write Literal[1, 2, 3], not Literal[range(3)].
Literal as a union
Literal["r", "w"] means the same as Literal["r"] | Literal["w"]. You can combine it with other types: Literal["auto"] | int accepts the string "auto" or any integer. Name a literal type with an alias, as Mode does above, when you use it in several places.
Where checkers complain
A checker tracks the literal value of a constant, but it often widens a plain variable to str.
from typing import Literal
Mode = Literal["r", "w"]
def open_log(path: str, mode: Mode) -> None:
print(f"opening {path} in {mode} mode")
def run(user_mode: str) -> None:
open_log("app.log", user_mode) # error: str is not Mode
def run_checked(user_mode: str) -> None:
if user_mode == "r" or user_mode == "w":
open_log("app.log", user_mode) # accepted by pyright; mypy may still report an errorA runtime string cannot be proven to be "r" or "w" without a check. Support for narrowing by == differs between checkers, so test your own tool. Mypy may need a cast, or a validating function that returns Mode.
Final: names that must not change
Final marks a name that should be assigned once. The checker reports any later assignment.
from typing import Final
MAX_RETRIES: Final = 3
MAX_RETRIES = 5 # error: cannot assign to final nameWithout a type argument, the checker infers the type from the value. Here it infers int. You can also write Final[int]. When the value is a simple literal, a Final name keeps its exact literal type, so MAX_RETRIES can be passed where Literal[3] is expected.
Final is not enforced at runtime. The reassignment above runs without error. It also does not make objects immutable: ITEMS: Final = [] still lets you call ITEMS.append(1). It only blocks rebinding the name.
You can also use Final on class attributes, and a subclass may not override them.
Common mistakes
- Expecting a runtime error. Neither feature raises an exception.
- Passing a plain
strvariable to aLiteralparameter without narrowing or validating it first. - Assuming
Finalfreezes a list or dict. It only protects the name.
Exercise
Given Mode = Literal["r", "w"], a function open_log(path: str, mode: Mode), and a variable choice: str = input(), why does a checker reject open_log("a.log", choice), and what is one way to fix it?
Show answer
The checker knows choice is some str, not necessarily "r" or "w", so it cannot prove the value is allowed. Fix it by checking the value first (if choice == "r" or choice == "w":, if your checker narrows on this), by validating it in a helper that returns Mode, or by using typing.cast.
Exercise
What does ITEMS: Final = [] prevent, and what does it allow?
Show answer
It prevents rebinding the name ITEMS, for example ITEMS = [1]. It still allows changing the list, such as ITEMS.append(1), because Final does not make the object immutable.