Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Literal Type: Restricting Values with typing.Literal

Python's typing.Literal restricts a value to a fixed set. See how type checkers enforce it, how to combine it with unions and overloads, and when runtime validation is still needed.

~4 min readPython
#typing#type hints#mypy#static analysis
Illustration of a Python function parameter restricted to a small set of literal string values.

Python's typing.Literal type lets you declare that a value must be one of a fixed set of allowed values. Type checkers such as Mypy and Pyright can then reject calls that pass anything outside that set. The annotation itself does not change runtime behavior. typing.Literal is available in Python 3.8 and later; on earlier versions, import it from typing_extensions.

What the Literal Type Solves

A function parameter annotated as str accepts any string, and an int parameter accepts any integer. Many functions, however, only make sense for a small set of exact values. The Literal type from the typing module lets you declare that a parameter must be one of those specific values, and type checkers will reject anything else.

python
from typing import Literal def set_log_level(level: Literal['DEBUG', 'INFO', 'WARNING', 'ERROR']) -> None: print(f'Log level set to {level}')

Calling set_log_level('TRACE') is a static type error because TRACE is not part of the declared literal set. This moves validation from runtime checks into the type system, catching invalid arguments before the code runs.

Basic Syntax and Supported Value Types

Literal can be parameterized with strings, bytes, integers, booleans, enum members, and None. Floats and arbitrary expressions are not supported; the allowed value types are hashable.

python
from typing import Literal Mode = Literal['read', 'write', 'append'] Port = Literal[8080, 8443] Flag = Literal[True]

You can assign a Literal alias to a variable and reuse it across multiple function signatures. This keeps the allowed set in one place.

python
LogLevel = Literal['DEBUG', 'INFO', 'WARNING', 'ERROR'] def configure_logger(level: LogLevel) -> None: ... def set_global_level(level: LogLevel) -> None: ...

Duplicate values in a Literal are collapsed by the type checker. Literal['a', 'a'] is equivalent to Literal['a'].

How Type Checkers Enforce Literal

Mypy, Pyright, and other static type checkers enforce Literal during analysis. The key rule is that a value typed as a broader type cannot be passed where a Literal is expected, even if the actual runtime value happens to match.

python
def choose(option: Literal['left', 'right']) -> None: ... user_input: str = 'left' choose(user_input) # error: Argument 1 has incompatible type 'str'

The type checker cannot prove that user_input is restricted to 'left' or 'right', so it rejects the call. To satisfy the checker, you must narrow the value first:

python
if user_input in ('left', 'right'): choose(user_input) # OK: narrowed to Literal['left', 'right']

This narrowing behavior is important in real codebases. Functions that read from configuration files, environment variables, or user input produce broad types like str, and you need an explicit narrowing step before passing those values to a Literal-typed parameter.

Combining Literal with Union and Optional

Literal composes with Union and Optional. A common use is an optional parameter with a few known values.

python
from typing import Literal, Optional def parse(data: str, format: Optional[Literal['json', 'yaml', 'toml']] = None) -> dict: if format is None: format = 'json' return {}

Here Optional[...] makes the parameter optional. The function can be called as parse(data) or parse(data, 'yaml'), but not parse(data, 'xml').

Be careful when mixing Literal with a broader type in a Union. For example, Union[Literal['r', 'rb'], str] is just str to a type checker, so it does not constrain callers. If the allowed set must be fixed, use Literal alone or an Enum.

Runtime Behavior: Literal Is Not a Runtime Constraint

Literal is not enforced at runtime. The annotation is stored in function metadata, but Python does not use it for validation or raise errors based on it. If you need runtime enforcement, you must write it yourself.

python
from typing import Literal, get_args Mode = Literal['fast', 'safe'] ALLOWED_MODES = get_args(Mode) def set_mode(mode: Mode) -> None: if mode not in ALLOWED_MODES: raise ValueError(f'Invalid mode: {mode}')

get_args() returns the tuple ('fast', 'safe') at runtime, which you can use for explicit validation. This pattern is useful when the same allowed set must be enforced both statically and at runtime, such as in a library that accepts untrusted input.

Computing get_args() once at module load also avoids repeating the allowed set in the validation logic.

Using Literal for Return Types and Overloads

Literal return types are useful for factory functions and discriminated unions. A function that returns a Literal tells callers exactly which value to expect.

python
from typing import Literal, overload @overload def load(source: Literal['file']) -> bytes: ... @overload def load(source: Literal['network']) -> str: ... def load(source: Literal['file', 'network']): if source == 'file': return b'file contents' return 'network response'

With overloads, the return type depends on the literal argument. Calling load('file') gives bytes; calling load('network') gives str. This makes the function's contract explicit.

Common Mistakes and Edge Cases

Literal[1.5] is not allowed. PEP 586 restricts valid literal types to strings, bytes, integers, booleans, enum members, and None; float values are not supported.

Literal[None] is redundant. Use None directly in a Union instead of Literal[None]. The two are equivalent, but None is clearer.

Boolean literals have a subtle interaction with bool. Literal[True] is a subtype of bool, but Literal[True, False] is equivalent to bool in most type checkers. If you need to distinguish between True and False as distinct literal values, use them separately rather than relying on bool.

Literal values must be hashable. Lists, dictionaries, and sets cannot appear inside Literal. Only strings, bytes, integers, booleans, enum members, and None are valid.

Maintainability and Production Considerations

Literal types make APIs self-documenting. A reader sees exactly which values a function accepts without reading the implementation. When the allowed set changes, type checkers can flag call sites that pass a removed literal value, which makes refactoring safer.

The tradeoff is coupling. If a Literal set grows large or changes frequently, every call site that depends on the exact values becomes part of the change surface. For a small, stable set like Literal['debug', 'info', 'error'], Literal is the right choice. For a set that grows beyond a handful of values or needs associated metadata, an Enum is often more maintainable.

python
from enum import Enum class LogLevel(Enum): DEBUG = 'debug' INFO = 'info' ERROR = 'error' def configure_logger(level: LogLevel) -> None: ...

An Enum gives you a single definition, a way to validate a raw value at runtime with LogLevel(value), and the ability to attach attributes to each member. Literal gives you static checking with less ceremony. The decision depends on whether the values need runtime behavior beyond simple equality.

When Literal is used across module boundaries, keep the alias in a shared types module. This avoids duplicating the literal set in every signature and makes the intent visible in one place.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.