Python Glossary Русский

Python 3.8+Annotations & typingterm

Literal[v1, v2]

literal

A type that admits only the given literal values. Lets mypy/pyright check that an allowed value is passed.

Syntax

from typing import Literal
Literal['read', 'write']
Literal[1, 2, 3]

Literal exists only for the type checker: nothing is verified at runtime, and open_file('f.txt', 'x') runs happily unless you actually run mypy or pyright. The other catch is that only literals themselves go inside the brackets (strings, ints, bools, None, Enum members) — no variables or expressions; and a value stashed in an ordinary variable is inferred as str rather than as the literal, so passing it gets rejected. Annotate that variable with the alias type or mark it Final.

Examples

from typing import Literal
Mode = Literal['r', 'w', 'a']
def open_file(path: str, mode: Mode) -> None:
    print(f'open {path} as {mode}')
open_file('f.txt', 'r')  # → open f.txt as r
open_file('f.txt', 'w')  # → open f.txt as w
from typing import Literal
Direction = Literal['N', 'S', 'E', 'W']
def move(d: Direction) -> str:
    return f'Moving {d}'
print(move('N'))  # → Moving N
print(move('S'))  # → Moving S

See also

Open in the full glossarydocs.python.orgReport an inaccuracy