Sub topic 5
Literal aliases, unions and allowed value kinds
This chapter assumes you can write a basic Literal[...] annotation and run a checker such as mypy or pyright. Here you will name literal types, combine them, and learn which kinds of values Literal accepts.
Naming a set of values with an alias
A long Literal[...] is awkward to repeat in every signature. Assign it to a name once and reuse it. This is a type alias.
from typing import Literal
ReadMode = Literal["r", "rb"]
WriteMode = Literal["w", "wb", "a"]
Mode = ReadMode | WriteMode
def open_log(path: str, mode: Mode) -> None:
print(f"opening {path} with mode {mode}")
open_log("app.log", "rb") # accepted
open_log("app.log", "x") # rejected by a type checkerMode is a union of two literal types. The checker treats it as the same type as Literal["r", "rb", "w", "wb", "a"]. The | operator on types needs Python 3.10 or later. On older versions, use Union[ReadMode, WriteMode].
You can also put an alias inside another Literal. The checker flattens it:
from typing import Literal
ReadMode = Literal["r", "rb"]
AnyMode = Literal[ReadMode, "w"] # same as Literal["r", "rb", "w"]Mixing literals with other types
A union can combine a Literal with an ordinary type. The most common case is a value that can also be missing.
from typing import Literal
LogLevel = Literal["debug", "info", "error"]
def configure(level: LogLevel | None = None) -> str:
return level or "info"
print(configure())
print(configure("debug"))Other mixes work too. int | Literal["auto"] accepts any integer and the single string "auto". The checker keeps both parts separate, so it can still narrow the union later.
Which values Literal accepts
Literal takes a small set of constant kinds:
| Kind | Example |
|---|---|
| `int` | `Literal[404]` |
| `str` | `Literal["r"]` |
| `bytes` | `Literal[b"ok"]` |
| `bool` | `Literal[True]` |
| Enum member | `Literal[Color.RED]` |
| `None` | `Literal[None]` |
from enum import Enum
from typing import Literal
class Color(Enum):
RED = 1
BLUE = 2
Status = Literal[200, 404]
Answer = Literal["yes", "no", None]
Primary = Literal[Color.RED, Color.BLUE]Floats are not allowed, so Literal[1.5] is an error. Computed values and variables are also invalid. Literal[1 + 1] and Literal[some_name] are errors, because the checker needs the value written out. The one exception is an alias to another Literal, shown above.
Reusing the values at runtime
A Literal is an annotation, so you cannot loop over it directly. To get the allowed values as a tuple, use typing.get_args. This is useful for validating text from outside your program.
from typing import Literal, cast, get_args
Mode = Literal["r", "w", "a"]
VALID_MODES = get_args(Mode)
def parse_mode(text: str) -> Mode:
if text not in VALID_MODES:
raise ValueError(f"bad mode: {text!r}")
return cast(Mode, text)
print(VALID_MODES)
print(parse_mode("w"))The checker cannot see that text in VALID_MODES proves the value is a Mode. That is why the example uses cast. The cast call does nothing at runtime. It only tells the checker to trust you, so the if check above it is what keeps the program safe.
Common mistakes
- Plain strings are too wide. A parameter typed
straccepts any string, so a function that needs aModewill reject a variable the checker has inferred asstr. Annotate the variable asMode, or mark itFinalwhen you assign a constant. - Wrong union operator at runtime. Using
Literal["a"] | Nonein an annotation that is evaluated on Python 3.9 raises aTypeError. UseOptional[...]there. - Expecting runtime errors. Passing
"x"toopen_logstill runs. Only the checker complains.
Exercise
Write an alias Size that allows exactly "small", "medium" and "large", then a function order(size: Size | None). Which of these calls would a checker reject: order("small"), order(None), order("huge"), order(3)?
Show answer
Define Size = Literal["small", "medium", "large"]. The checker rejects order("huge") and order(3). "huge" is not one of the three allowed strings, and 3 is an int, not a Size or None. It accepts order("small") and order(None).