How to Use Literal Type Hints in Python
Use typing.Literal to restrict a function parameter to specific allowed string values and get static type checking.
Python code
16 linesfrom typing import Literal
def get_status_message(status: Literal["active", "inactive", "pending"]) -> str:
"""Return a message based on the status value."""
if status == "active":
return "Account is active"
elif status == "inactive":
return "Account is inactive"
else:
return "Account is pending"
if __name__ == "__main__":
print(get_status_message("active"))
print(get_status_message("inactive"))
print(get_status_message("pending"))
Output
Account is active
Account is inactive
Account is pending
How it works
The Literal type hint restricts a variable or parameter to one of the exact values listed in the brackets. At runtime, Python ignores type hints, so invalid values won't raise errors by default — the restriction is enforced by static type checkers like mypy or Pyright. Type checkers verify that all call sites pass one of the allowed literal values, catching typos early. This improves code clarity and reduces runtime validation needs for well-typed codebases.
Common mistakes
- Forgetting that Literal is runtime-inert — invalid values won't raise errors without a type checker
- Using Literal with dynamic values instead of only literal constants (e.g., variables) in type-checked code
- Mixing Literal with Optional or Union without wrapping in the right parentheses
Variations
- Use `Literal[1, 2, 3]` for constrained integer values instead of strings
- Combine with `Union[Literal['a'], Literal['b']]` for old Python versions before 3.8
Real-world use cases
- Restricting API route method parameters to a fixed set of allowed strings like get, post, put.
- Typing configuration keys or mode flags in a settings object to prevent typos at static analysis time.
- Defining command names in a CLI runner so only known subcommands compile cleanly.
Sponsored
More from Testing & modern typing
- Capture stdout and stderr with pytest capsys easy
- Characterization Test for Legacy Python Code medium
- Dataclass with Type Hints Fields in Python easy
- Dependency Injection in Python for Testability easy
- Design Data Helpers with Python TypedDict and Literal easy
- Fix and Test a Regression Bug in Python with Unit Tests easy
Keep learning
Related tutorials and quizzes for this topic.