Sub topic 3
Restricting values with Literal
This chapter assumes you know basic Python, simple type hints such as int and str, and that a static type checker such as mypy or pyright reads annotations separately from running the code. It also assumes you have seen TypedDict from the previous chapter.
Why a plain `str` is too loose
Many functions accept only a few specific strings. A file mode might be "r", "w" or "a". If you annotate the parameter as str, the checker accepts a typo such as "x" or "rw". The mistake shows up later, as a bug at runtime.
A Literal type says that a value must be one of the exact constants you list. The checker then rejects anything else.
A first example
from typing import Literal
Mode = Literal["r", "w", "a"]
def open_log(path: str, mode: Mode) -> 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 normallyMode is a type alias. It names the type Literal["r", "w", "a"] so you can reuse it. The call with "r" passes the check. The call with "x" is reported as an error by mypy or pyright, because "x" is not one of the three listed values.
The last comment matters. Python itself does not stop the second call. The program prints its message and carries on. Literal is information for the checker and for readers. It is not a runtime guard.
What the checker sees
Think of a Literal as a very small type. The type str contains every string. The type Literal["r"] contains exactly one string, "r". Because of this, every Literal of strings is also a str. You can pass a Mode value to any function that takes a str. The reverse does not hold. A plain str variable cannot go where a Mode is expected, because the checker does not know which string it holds.
from typing import Literal
Mode = Literal["r", "w", "a"]
def open_log(path: str, mode: Mode) -> None:
print(f"opening {path} with mode {mode}")
chosen = input("mode? ")
open_log("app.log", chosen) # rejected: str is not ModeThis is a common surprise. The fix is not to cast the value silently. Compare it against the allowed values first, and the checker will accept it, as a later chapter on narrowing shows.
Literal inside other types
You can use Literal anywhere a type goes. That includes fields of a TypedDict.
from typing import Literal, TypedDict
class Job(TypedDict):
name: str
status: Literal["queued", "running", "done"]
job: Job = {"name": "backup", "status": "queued"}
bad: Job = {"name": "backup", "status": "paused"} # rejected by a type checkerThe checker now knows that status has three possible values. A misspelled status in a dictionary literal is reported at the line where you wrote it, not when some other code reads it.
Which values are allowed
Literal accepts a limited set of constants:
| Kind of value | Example |
|---|---|
| Strings | `Literal["r", "w"]` |
| Integers | `Literal[0, 1, 2]` |
| Booleans | `Literal[True]` |
| Bytes | `Literal[b"GET"]` |
| Enum members | `Literal[Color.RED]` |
| `None` | `Literal[None]` |
Floats are not allowed, and neither are variables or computed expressions such as Literal[1 + 1]. The values must be written out in the annotation.
How it works internally
Both paths end with the program running. The checker is a separate tool you run before the program, and it does not change what Python does.
Common errors
- Passing a
strvariable where aLiteralis expected. The checker cannot prove which string it holds. - Writing
Literal["r", "w"]and expecting a value like"rw"to be accepted. Each listed value is separate, and only those exact values match. - Using a float or an expression inside
Literal. Only the constant kinds in the table are allowed. - Assuming the type is enforced at runtime. It is not.
Exercise
Given Level = Literal[1, 2, 3] and def set_level(level: Level) -> None: ..., which of these calls does a type checker reject: set_level(2), set_level(4), or n = int(input()); set_level(n)? Explain why.
Show answer
It rejects set_level(4), because 4 is not one of the listed values. It also rejects set_level(n), because n is a plain int and the checker cannot know it is 1, 2 or 3. Only set_level(2) is accepted.