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.

Easy Python 3.8+ Aug 9, 2026 Testing & modern typing 15 views 0 copies

Python code

16 lines
Python 3.8+
from 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

stdout
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

  1. Use `Literal[1, 2, 3]` for constrained integer values instead of strings
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Testing & modern typing

Related tutorials and quizzes for this topic.