Express Fixed Choices with Literal and Final
Core idea
Literal specifies particular permitted values in a static type, such as Literal["small", "large"]. Final marks a name that should not be reassigned after initialization. Final does not make an object immutable, and neither hint automatically rejects invalid runtime input.
from typing import Literaldef slots(mode: Literal['small', 'large']) -> int: if mode == 'small': return 2 if mode == 'large': return 8 raise ValueError('unknown mode')print(slots('large'))The explicit raise handles unexpected runtime values; Literal documents the allowed choices.
Final binding versus contents
from typing import FinalLABELS: Final[list[str]] = ['A']LABELS.append('B')print(LABELS)The name still refers to the same mutable list.
Common mistake
A Final name is not a frozen container. Use an immutable representation when you need immutable contents, and validate externally supplied literal choices explicitly.
Practice
Replace LABELS with a tuple of strings; compare rebinding with content mutation.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Literal and Final
Check your understanding of literal and final.
What is printed?
from typing import Literaldef f(x: Literal['a','b']): return xprint(f('a'))What is printed?
from typing import Finalxs: Final[list[int]] = [1]xs.append(2)print(len(xs))What does Literal[0, 1] express?
What does Final primarily prohibit for a name?