Sub topic 5
Literal aliases, unions and allowed value kinds
This chapter assumes you know the basic form Literal["r", "w"] from the previous chapter. It also assumes you have run a checker such as mypy or pyright. Here you will name a set of constants once, combine sets, and learn which kinds of values Literal accepts. You will also see how to turn an ordinary str into a literal type safely.
Naming a set of values with an alias
A long Literal[...] repeated in many signatures is hard to maintain. Assign it to a name once and reuse the name. This is a type alias.
from typing import Literal
Mode = Literal["r", "w", "a"]
def open_log(path: str, mode: Mode) -> None:
print(f"opening {path} with mode {mode}")
def reopen_log(path: str, mode: Mode = "a") -> None:
open_log(path, mode)
reopen_log("app.log")Adding "x" to Mode updates every function that uses it. An alias is also a normal Python object at runtime, so you can inspect it, as shown later in this chapter.
Python 3.12 added a type statement, type Mode = Literal["r", "w", "a"]. It makes the alias explicit to checkers. On older versions, a plain assignment works, optionally annotated with TypeAlias from typing.
Combining literals with unions
Several literal types can be joined with | (Python 3.10+) or typing.Union. The result accepts any value from any member.
from typing import Literal
ReadMode = Literal["r", "rb"]
WriteMode = Literal["w", "wb"]
FileMode = ReadMode | WriteMode
def describe(mode: FileMode) -> str:
return "reading" if mode in ("r", "rb") else "writing"
print(describe("rb"))
print(describe("w"))The checker treats FileMode as if you had written Literal["r", "rb", "w", "wb"]. These forms are equivalent:
Literal["a"] | Literal["b"]andLiteral["a", "b"].Literal[Literal["a", "b"], "c"]andLiteral["a", "b", "c"]. ALiteralnested inside anotherLiteralis flattened.Literal["a"] | NoneandLiteral["a", None].
A union can also mix a literal with a wider type. Literal["auto"] | int accepts the string "auto" or any integer. This suits options that take either a keyword or a number. Narrowing such a value is covered in a later chapter.
Which values Literal accepts
Literal takes only values that the checker can read directly from the source code. The allowed kinds are:
| Kind | Example |
|---|---|
| Integer | `Literal[404]`, `Literal[-1]` |
| String | `Literal["r"]` |
| Bytes | `Literal[b"\x00"]` |
| Boolean | `Literal[True]` |
| Enum member | `Literal[Color.RED]` |
| None | `Literal[None]` |
Several things are not allowed:
floatvalues such asLiteral[1.5].- Expressions such as
Literal[1 + 2]. - Variables such as
Literal[some_name]. - Function calls such as
Literal[str(3)]. - Tuples, lists and other containers.
from enum import Enum
from typing import Literal
class Color(Enum):
RED = 1
GREEN = 2
Status = Literal[200, 404]
Marker = Literal[b"\x00"]
Choice = Literal[Color.RED, "auto", None]
print(Choice)Python does not complain about Literal[1.5] at runtime, because Literal stores whatever it receives. Only a type checker reports it. This is easy to miss when you only run the file.
Mixing kinds in one Literal is legal, as Choice shows. Keep such mixes small. A parameter that accepts "auto", None and one enum member is usually a sign that the API needs redesigning.
Two special cases are worth knowing:
Literal[True, False]is equivalent tobool, and checkers narrowboolas two literal members.- An enum with a fixed set of members is equivalent to a union of
Literalmembers for narrowing. If you control the values, anEnumis often clearer than strings.
A literal is a subtype of its base type
Literal["r"] is a subtype of str. You can pass a literal where a str is expected, but not the other way around. This difference causes most beginner errors with Literal.
from typing import Literal
Mode = Literal["r", "w", "a"]
def open_log(path: str, mode: Mode) -> None:
print(f"opening {path} with mode {mode}")
def show(text: str) -> None:
print(text)
mode: Mode = "r"
show(mode) # fine: Literal["r"] is a str
name = input("mode: ") # type is str
open_log("app.log", name) # rejected: str is not ModeThe last call is rejected because the checker only knows that name is a str, and that is wider than Mode. The program may run fine today and fail the day someone types "x".
Getting from str to a literal safely
A runtime check turns a str into a literal type if you tell the checker what the check proves. A TypeGuard function does this.
from typing import Final, Literal, TypeGuard, get_args
Mode = Literal["r", "w", "a"]
def is_mode(value: str) -> TypeGuard[Mode]:
return value in get_args(Mode)
def open_log(path: str, mode: Mode) -> None:
print(f"opening {path} with mode {mode}")
DEFAULT_MODE: Final = "r"
open_log("app.log", DEFAULT_MODE)
user_input = "w"
if is_mode(user_input):
open_log("app.log", user_input)
else:
print("unknown mode")The output is:
opening app.log with mode r
opening app.log with mode wThree points explain this code:
get_args(Mode)returns the tuple("r", "w", "a"). The list of allowed values lives in one place, the alias, and the runtime check reuses it.- Inside
if is_mode(user_input):the checker treatsuser_inputasMode. The guard is trusted, not verified. Ifis_modereturnedTruefor the wrong values, the checker would not notice. Finalwith no explicit type makes the checker infer the literal typeLiteral["r"]forDEFAULT_MODE. WithoutFinal, how a plain variable is inferred when you pass it to aLiteralparameter differs between checkers. When in doubt, annotate:mode: Mode = "r".
Reading the values of an alias at runtime
get_args returns the values of a plain Literal. For a union of literals, such as FileMode earlier, it returns the member Literal objects instead of the flat values. A small helper flattens them:
from typing import Literal, get_args, get_origin
ReadMode = Literal["r", "rb"]
WriteMode = Literal["w", "wb"]
FileMode = ReadMode | WriteMode
def literal_values(tp: object) -> tuple:
values: list = []
for arg in get_args(tp):
if get_origin(arg) is Literal:
values.extend(literal_values(arg))
else:
values.append(arg)
return tuple(values)
print(get_args(ReadMode))
print(literal_values(FileMode))The output is:
('r', 'rb')
('r', 'rb', 'w', 'wb')This helper is for runtime inspection only. Checkers do not run it, so the guard in the previous section is what carries type information.
Common errors
- Passing a
strvariable to aLiteralparameter. The fix is a guard, acast, or an annotation that carries the literal type from where the value was created. - Inferred container types.
modes = ["r", "w"]is inferred aslist[str], notlist[Mode]. Annotate it:modes: list[Mode] = ["r", "w"]. - Lost literal types after string methods.
mode.upper()returns a plainstr, even whenmodeis a literal. - Mutable-key surprises.
dict[Mode, int]accepts only literal keys on checkers. A dictionary built fromstrkeys does not match it. - Expecting runtime enforcement. Nothing stops
open_log("app.log", "x")from running. The next chapters cover what Python does and does not check at runtime.
Exercise
Which of these is rejected by a type checker as an argument to Literal, and why? (a) Literal[-3] (b) Literal[2.5] (c) Literal[None] (d) Literal[b"ok"]
Show answer
(b) Literal[2.5] is rejected, because float values are not allowed in Literal. The allowed kinds are int, str, bytes, bool, enum members and None. Negative integers such as -3 are allowed.
Exercise
Given Level = Literal["debug", "info"] and Extra = Literal["warning", "error"], write an alias AnyLevel that accepts all four strings, then write a TypeGuard function islevel(value: str) that returns True only for those four. Use getargs so the list is not repeated by hand. (Hint: for the guard, flatten the values.)
Show answer
AnyLevel = Level | Extra def islevel(value: str) -> TypeGuard[AnyLevel]: allowed = [v for part in getargs(AnyLevel) for v in getargs(part)] return value in allowed For a union of two Literal aliases, getargs(AnyLevel) returns the two member Literals, so get_args is applied again to each member to read the strings.