Types
Literal and Final
Literal describes exact allowed values. A type checker can reject "debug" as a Mode even though it is an ordinary string at runtime.
Source
from typing import Final, Literal
Mode = Literal["read", "write"]
def open_label(mode: Mode) -> str:
return f"opening for {mode}"
print(open_label("write"))Output
opening for writeFinal marks a name that should not be rebound. It is stronger documentation than the all-caps constant convention because static tools can flag reassignment.
Source
DEFAULT_MODE: Final[Mode] = "read"
print(open_label(DEFAULT_MODE))Output
opening for readThe annotation is not a runtime lock. Python still rebinds the name; the mistake is that a type checker and human reader should reject the design.
Source
DEFAULT_MODE = "debug"
print(DEFAULT_MODE)Output
debugNotes
Literalnarrows values to a small exact set.Finalprevents rebinding in static analysis, not at runtime.- Use enums when the option set needs names, behavior, or iteration over members.
See also
- related: Type Hints
- prerequisite: Constants
- related: Union and Optional Types
- related: Overloads
Run the complete example
Expected output
opening for read
opening for write
debug
Execution time appears here after you run the example.