Sub topic 3
Restricting values with Literal
This chapter assumes you can write Python functions and annotate them with str, int and Optional. It also assumes you know that a checker such as mypy or pyright reads annotations without running your program. If those ideas are new, review them first.
The problem: str allows too much
Suppose a function opens a log file in one of three modes: read, write or append. The obvious annotation is str:
def open_log(path: str, mode: str) -> None:
print(f"opening {path} with mode {mode}")A checker accepts open_log("app.log", "banana"), because "banana" is a str. The mistake shows up later, when the value reaches code that only understands "r", "w" and "a". A typo can travel through several functions before anything fails.
The annotation should say which strings are valid. That is what Literal does.
What Literal means
typing.Literal builds a type from specific constant values. The type Literal["r", "w", "a"] contains exactly three values: the strings "r", "w" and "a". Read the brackets as "one of these".
from typing import Literal
def open_log(path: str, mode: Literal["r", "w", "a"]) -> None:
print(f"opening {path} with mode {mode}")
open_log("app.log", "r") # accepted
open_log("app.log", "x") # rejected by a type checker, still runs normallyA checker reports an error on the last call. For example, mypy says the argument has type Literal['x'] but the parameter expects Literal['r', 'w', 'a']. The checker treats the call open_log("app.log", "x") as a mistake. Python itself runs it and prints opening app.log with mode x.
How the checker decides
For each call, the checker works out the type of the argument expression and asks whether that type fits the parameter type. A string literal written directly in the call has the precise type Literal["x"]. That type is not one of the three allowed values, so the call fails.
The third branch catches many learners out. A plain str is rejected even if it happens to hold "r" at runtime. The checker reasons about types, not about values it cannot see.
Literal is a subtype of its base type
Literal["r"] is narrower than str. Every value of the first type is also a str, so you can pass a literal value anywhere a str is expected. The reverse is not allowed.
from typing import Literal
def shout(text: str) -> str:
return text.upper()
def read_only(mode: Literal["r"]) -> None:
print(shout(mode)) # fine: Literal["r"] is a str
read_only("r")The same rule applies to the other base types. Literal[404] fits int, and Literal[True] fits bool. This is why you can narrow a parameter from str to a Literal without breaking existing callers who pass constants.
Why a str variable fails
The most common Literal error comes from values that are computed rather than written out. Here the string comes from the user:
from typing import Literal
def open_log(path: str, mode: Literal["r", "w", "a"]) -> None:
print(f"opening {path} with mode {mode}")
raw = input("mode? ")
open_log("app.log", raw) # error: "str" is not "Literal['r', 'w', 'a']"input() returns str, and the checker cannot know which characters the user will type. The error is correct. The checker is telling you that you never verified the value.
There are three ways to resolve it, from safest to least safe.
- Validate the value at runtime, then tell the checker the result is safe.
- Make the value a constant with a literal type.
- Cast without checking, which hides the problem instead of fixing it.
Validate, then narrow with cast
typing.get_args returns the values inside a Literal. You can use it to check input against the same list the type uses, so the two cannot drift apart.
from typing import Literal, cast, get_args
Mode = Literal["r", "w", "a"]
def parse_mode(raw: str) -> Mode:
if raw not in get_args(Mode):
raise ValueError(f"invalid mode: {raw!r}")
return cast(Mode, raw)
def open_log(path: str, mode: Mode) -> None:
print(f"opening {path} with mode {mode}")
open_log("app.log", parse_mode("w"))Mode here is a name for a Literal type. Giving such a type a name is useful, and a later chapter covers aliases and unions in more detail. The important line is cast(Mode, raw). At runtime cast returns its argument unchanged. It only instructs the checker to treat the value as Mode. That is safe here because the check on the line above guarantees it.
Constants with Final
A name marked Final can never be reassigned, so the checker can keep its exact value as the type:
from typing import Final, Literal
def open_log(path: str, mode: Literal["r", "w", "a"]) -> None:
print(f"opening {path} with mode {mode}")
DEFAULT_MODE: Final = "a"
open_log("app.log", DEFAULT_MODE) # accepted: type is Literal["a"]Without Final, a checker treats a module-level DEFAULT_MODE = "a" as a plain str, because another part of the program could assign a different string to it later. Checkers differ in how much they remember about a variable's last assigned value, so do not rely on that behavior. Final is explicit and works the same everywhere.
Which values Literal accepts
The values inside Literal[...] must be written as constants. You cannot put a variable or a computed expression in the brackets.
| Kind of value | Example |
|---|---|
| String | `Literal["r", "w"]` |
| Integer | `Literal[200, 404]` |
| Boolean | `Literal[True]` |
| Bytes | `Literal[b"GET"]` |
| None | `Literal[None]` |
| Enum member | `Literal[Color.RED]` |
Floats are not allowed. Literal[1.5] is an error, so a fixed set of decimal values needs a different design. A later chapter covers these kinds and how to combine them.
Literals of different kinds can share one type, as in Literal["auto", 0, None]. This is legal, but a mixed set is usually a sign that the parameter is doing two jobs.
Literal compared with Enum
An Enum also gives you a closed set of values, so choose between them deliberately.
Literalkeeps the values as plain strings or numbers. A caller writes"r", and JSON, configuration files and dictionaries already contain such values. This fitsTypedDictwell, which this tutorial combines withLiterallater.Enumcreates real objects with names, methods and a runtime check on construction. Callers must import the enum class and convert values coming from outside.
If the values arrive from outside as raw strings, Literal avoids a conversion step. If you want runtime enforcement and behavior attached to each value, use Enum.
Common mistakes
- Expecting runtime enforcement.
open_log("app.log", "x")runs without error. Add a check such asparse_modewhere untrusted data enters the program. - Passing a
strvariable. Validate the value, or useFinalfor constants, as shown above. - Putting a variable in the brackets.
Literal[MODE_NAME]is invalid unless the name refers to an enum member. Write the constant itself. - Keeping two copies of the list. If you write the allowed values once in the type and again in a tuple, they can disagree. Derive the runtime list from the type with
get_args. - Using a huge Literal. Dozens of values are hard to maintain and read. If the set is open-ended,
strplus validation is the better design.
Exercise
A function set_level(level: Literal["debug", "info", "warning"]) is called as set_level(user_text), where user_text = input(). The checker reports an error. Explain why, and write a small function parse_level(raw: str) that fixes the problem so the call set_level(parse_level(user_text)) passes the checker and rejects bad input when the program runs.
Show answer
input() returns a plain str. A str could be any text, so it is not a member of the three-value Literal type, and the checker rejects it. The fix validates the value at runtime and then narrows the type:
from typing import Literal, cast, getargs
Level = Literal["debug", "info", "warning"]
def parselevel(raw: str) -> Level:
if raw not in getargs(Level):
raise ValueError(f"invalid level: {raw!r}")
return cast(Level, raw)
The cast is safe because the if raises for every value outside the allowed set. `getargs(Level)` keeps the runtime list and the type in sync.
Exercise
Given ANSWER: Final = 42 and a parameter typed Literal[42, 43], does the call f(ANSWER) pass the checker? What changes if you remove Final and write ANSWER = 42 at module level?
Show answer
With Final, the checker infers the type Literal[42], which is one of the allowed values, so the call passes. Without Final, the name can be reassigned elsewhere, so most checkers treat it as a plain int. A plain int is not a member of Literal[42, 43], so the call is usually reported as an error. Behavior differs between checkers, which is why Final is the dependable choice.