Constrain string options
A function accepts only a documented set of file-mode strings.
Python · Type Alias
typing.Literal expresses that an annotated value must equal one of a specified set of literals. It is useful for statically checking constrained strings, numbers, booleans, and similar fixed choices.
Literal[...] builds a type containing specific literal values. Type checkers can use that set to validate annotated arguments and return values, while Python itself does not enforce the restriction during execution.
Literal[value, ...]| Name | Type | Description |
|---|---|---|
values | literal values | One or more literal values accepted by the type form; type checkers may restrict what qualifies. |
A special typing form describing the supplied literal values.
from typing import Literal
Mode = Literal["r", "rb", "w", "wb"]
def open_helper(file: str, mode: Mode) -> str:
return f"opening {file} in {mode} mode"
print(open_helper("data.txt", "rb"))The alias restricts mode to the documented literal values for static type checkers; the function remains ordinary Python at runtime.
A function accepts only a documented set of file-mode strings.
A function always returns a known boolean literal such as True.
A public API models a finite protocol or configuration vocabulary.
Literal describes a type whose value is equivalent to one of the listed literals. A type checker can therefore reject an argument such as a mode string that is not in the declared set.
Follow-up: How does Python enforce this at runtime? It does not; the restriction is intended for type-checking tools, and runtime arguments are not automatically validated.
A Literal must have one or more literal values as arguments. For example, Literal["r", "w"] permits exactly those declared values for static analysis.
Follow-up: What if the same literal appears twice? Redundant arguments are skipped when Literal types are compared.
Literal types can be nested, and nested literals are generally flattened, so Literal[Literal[1, 2], 3] compares as Literal[1, 2, 3]. This flattening exception does not apply when a nested Literal is referenced through a type alias.
Follow-up: Does argument order affect equality? No; Literal comparisons ignore argument order.
typing.Anytyping.TypeAliasTypePEP 586