Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

typing.Literal

Restrict a static type to particular literal values.

Version: Python 3.14; repository image, production runtime not attested

Syntax

mode: Literal["read", "write"]

Restrict a static type to particular literal values.

The type checker can distinguish equal values of different types, such as the integer zero and Boolean False. A Literal annotation does not validate function arguments at runtime.

The sample inspects the allowed strings and calls the function with an unlisted mode.

Examples

from typing import Literal, get_args
Mode = Literal["read", "write"]
def label(mode: Mode) -> str:
    return mode.upper()
print(get_args(Mode), Literal[0] == Literal[False])
print(label("other"))

Result

('read', 'write') False
OTHER

The sample inspects the allowed strings and calls the function with an unlisted mode.

Sources