Sub topic 10
Restricting Values with Literal and Final
This chapter assumes you can annotate functions and variables, read X | None unions, and run mypy or pyright on a script. It covers two tools from the typing module. Literal limits a value to specific constants. Final marks a name that must not be reassigned.
Why restrict values
A parameter typed str accepts any string. Often only a few strings are valid, such as "r" and "w" for a file mode. Without a tighter type, a typo like "x" passes the type check and fails later, or never fails and silently does the wrong thing.
Literal lets you say "exactly these values." A static checker (mypy or pyright) then reports any other value before the program runs.
Literal basics
Literal[...] takes one or more constant values. The allowed kinds are:
intvalues such as1or-3strandbytesvalues such as"r"orb"x"boolvalues,TrueandFalseNone- members of an
enum.Enum - other
Literaltypes, which are flattened into one
Floats are not allowed. Literal[1.5] is an error.
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. This call would be reported by the checker:
open_log("app.log", "x") # error: "x" is not "r" or "w"Python still runs it. As the earlier chapter on runtime behavior explained, the interpreter does not enforce hints. Literal protects you only when you run a checker.
Combining literals
Literal["r", "w"] means the same as Literal["r"] | Literal["w"]. You can also write several Literal types in a union with other types:
from typing import Literal
def parse(value: Literal["auto"] | int) -> int:
if value == "auto":
return 0
return value
print(parse("auto"))
print(parse(5))Here the argument is either the exact string "auto" or any int. Notice that the if check narrows the type. After value == "auto" returns, the checker knows value is an int.
Literal and type narrowing
Checkers narrow a Literal union when you compare against its members. This lets you handle every case and find the ones you forgot.
from typing import Literal, assert_never
Shape = Literal["circle", "square"]
def sides(shape: Shape) -> int:
if shape == "circle":
return 0
elif shape == "square":
return 4
else:
assert_never(shape)
print(sides("square"))assert_never is in typing from Python 3.11. In the final else branch the checker has removed both members, so shape has the type Never. If you later add "triangle" to Shape and forget a branch, the checker reports an error at assert_never. At runtime, assert_never raises an error if it is ever reached.
Where Literal values come from
A common surprise is that a plain str variable does not match a Literal parameter, even when it holds the right text.
from typing import Literal
Mode = Literal["r", "w"]
def open_log(path: str, mode: Mode) -> None:
print(path, mode)
def run(user_mode: str) -> None:
open_log("app.log", user_mode) # error: str is not ModeThe checker only knows user_mode is some str. To fix it, narrow the value first, or validate and cast:
from typing import Literal, get_args
Mode = Literal["r", "w"]
def open_log(path: str, mode: Mode) -> None:
print(path, mode)
def run(user_mode: str) -> None:
if user_mode == "r" or user_mode == "w":
open_log("app.log", user_mode)
else:
raise ValueError(f"bad mode: {user_mode}")
print(get_args(Mode))
run("w")Checkers narrow str to the matching literal after an == check. typing.get_args(Mode) returns ("r", "w"), which is useful when you want to build a runtime check from the same list the type uses.
By contrast, a variable assigned a literal in the same scope keeps its literal type only in some cases. mode = "r" makes mode a str in mypy unless you declare it Final or annotate it with Literal. This leads to Final.
Final
Final tells the checker that a name is assigned once and never rebound. It applies to module variables, class attributes, and local variables.
from typing import Final
MAX_RETRIES: Final = 3
TIMEOUT: Final[float] = 2.5
MAX_RETRIES = 4 # error: cannot assign to final nameWith Final and no explicit type, the checker infers the type from the value. With a literal value, it infers a Literal type. So MAX_RETRIES: Final = 3 is treated as Literal[3], and can be passed where Literal[3] is required. A plain MAX_RETRIES: int = 3 could not.
from typing import Final, Literal
LEVEL: Final = "debug"
def set_level(level: Literal["debug", "info"]) -> None:
print(level)
set_level(LEVEL)Final in classes
In a class, Final blocks reassignment in subclasses and on instances.
from typing import Final
class Config:
VERSION: Final = "1.0"
def __init__(self) -> None:
self.name: Final = "default"
class Child(Config):
VERSION = "2.0" # error: cannot override final attributeA class attribute declared Final inside the class body must be assigned there or in __init__.
Final decorators
The same module provides @final, a lowercase decorator, for classes and methods. It is a related but separate feature.
from typing import final
@final
class Token:
pass
class Special(Token): # error: cannot subclass final class
passUse @final on a method to forbid overriding it. The capitalized Final applies to names. The lowercase final applies to classes and methods.
What Final does not do
Final is not immutability. It stops rebinding the name, not changes to the object.
from typing import Final
ITEMS: Final = [1, 2, 3]
ITEMS.append(4) # allowed
ITEMS = [5] # error
print(ITEMS)For an unchangeable collection, use a type that has no mutating methods, such as tuple[int, ...] or frozenset[int].
Also, Final does not stop assignment at runtime. The interpreter runs MAX_RETRIES = 4 without complaint. Only the checker reports it.
Comparison
| Feature | Applies to | Question it answers | Enforced by |
|---|---|---|---|
| `Literal[...]` | A value's type | Which exact values are allowed? | Static checker |
| `Final` | A name | Can this name be reassigned? | Static checker |
| `@final` | A class or method | Can this be subclassed or overridden? | Static checker |
| `Enum` | A class of values | Which named values exist? | Runtime and checker |
Common errors
- Using a variable inside
Literal.Literal[x]is invalid. Only constants are allowed. - Passing a
strvariable to aLiteralparameter. Narrow it with a comparison first. - Expecting
Finalto freeze a list or dict. It only prevents rebinding. - Expecting runtime errors. Neither feature raises anything when the program runs, apart from
assert_neverif reached. - Mixing
FinalandLiteralroles.Finalgoes on the name.Literalgoes in the type.
Choosing between them
Prefer Literal for small, fixed sets of string or integer options, especially in function arguments. Prefer an Enum when the values need methods, iteration, or a runtime check. Use Final for constants and for class attributes that subclasses must not change.
Exercise
Given LEVEL: Final = "debug" and a function set_level(level: Literal["debug", "info"]), does set_level(LEVEL) pass a type check? Would it pass if LEVEL were declared LEVEL: str = "debug"?
Show answer
With Final, the checker infers Literal["debug"] for LEVEL, so the call passes. With LEVEL: str = "debug", the type is the wider str, so the checker reports an error because str is not one of the allowed literals.
Exercise
Why does ITEMS: Final = [1, 2, 3] still allow ITEMS.append(4), and what type could you use to prevent the change?
Show answer
Final only forbids rebinding the name ITEMS. The list object stays mutable. Annotating with an immutable type such as tuple[int, ...] (and using a tuple value) means the checker reports append as an error.