Types

Literal and Final

Literal restricts exact values, while Final marks names that should not be rebound.

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 write
LITERAL[…]x'red''green''blue'
Literal narrows a slot to a fixed set of constant values; Final says the binding will not change.

Final 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 read

The 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

debug

Notes

See also

Run the complete example

Example code

Expected output

opening for read
opening for write
debug

Execution time appears here after you run the example.