Skip to main content

How to Allow Only Certain Values in a Python Type Hint with Literal

· 4 min read
Jagdish Kumawat
Founder @ Dewiride

When a parameter only makes sense with a few exact values, such as a coffee size, typing.Literal writes that list into the type hint. A type checker then flags any other value before the code runs. This guide shows what Literal does and what it doesn't, with real output from Python 3.15.2 and mypy 2.4.1.

Syntax​

Syntax
from typing import Literal

<Name> = Literal[<value1>, <value2>, ...]


def <function>(<parameter>: <Name>) -> ...:
...
PartWhat it means
Literal[<value1>, <value2>, ...]A type whose only allowed values are the ones listed: strings, numbers, True/False, None or enum members
<Name> = ...Optional: a name for the type, so several hints can share it
<parameter>: <Name>Uses the type in a hint, here on a function parameter

Python's typing documentation calls it a "Special typing form to define 'literal types'" that "can be used to indicate to type checkers that the annotated object has a value equivalent to one of the provided literals." The key words are to type checkers: the same page states that "The Python runtime does not enforce function and variable type annotations."

Prerequisites​

  • uv and Python. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with uv init. uvx runs mypy without adding it to the project.

Step 1: Write the Script​

coffee.py
from typing import Literal, get_args

Size = Literal["small", "medium", "large"]


def order_coffee(size: Size) -> str:
return f"One {size} coffee"


print(order_coffee("medium"))
print(order_coffee("huge"))
print(get_args(Size))

The coffee.py script in a macOS-style code window: Size is Literal of small, medium and large, order_coffee takes a Size, and the script orders a medium, then a huge coffee, then prints get_args(Size).

The second order uses "huge", which isn't in the list. get_args() returns the values a Literal allows.

Step 2: Run It, Then Check It with mypy​

Terminal
uv run python coffee.py
uvx mypy coffee.py
Output
One medium coffee
One huge coffee
('small', 'medium', 'large')
Installed 6 packages in 27ms
coffee.py:11: error: Argument 1 to "order_coffee" has incompatible type "Literal['huge']"; expected "Literal['small', 'medium', 'large']" [arg-type]
Found 1 error in 1 file (checked 1 source file)

The output in a terminal: Python prints One medium coffee, One huge coffee and the tuple of allowed sizes, then mypy reports line 11's incompatible type Literal huge against the expected Literal small, medium, large.

Python ran the "huge" order without complaint. mypy, a type checker, read the hint and reported line 11 before anything ran. Installed 6 packages is uvx fetching mypy the first time.

Common Mistakes​

MistakeWhat happensDo this instead
Expecting Python to reject a wrong valueIt doesn't: One huge coffee printedRun a type checker, or check the value yourself with get_args()
Writing Literal("small", "medium") with parenthesesTypeError: Cannot instantiate typing.LiteralUse square brackets: Literal["small", "medium"]

Troubleshooting​

SymptomLikely causeFix
mypy reports incompatible type "Literal['huge']"A value outside the list is passedPass one of the listed values, or add the new value to the Literal
mypy reports incompatible type "str" for a variable that holds "medium"mypy reads size = "medium" as a plain strGive the variable the type too: size: Size = "medium"

FAQ​

Should I use Literal or an Enum?​

Literal keeps plain values such as strings, which is handy for settings and JSON. An Enum makes a real class with members you can loop over. Both work in type hints.

Can a Literal hold numbers?​

Yes. Literal[1, 2, 3] allows those integers, and you can mix types, such as Literal["auto", 0].

Conclusion​

Literal["small", "medium", "large"] documented the allowed sizes, Python ran a "huge" order anyway, and mypy caught it on line 11. get_args() returned the three sizes for any check you write yourself.

Additional Resources​