Literal types
Literal types let you indicate that an expression is equal to some specificprimitive value. For example, if we annotate a variable with type Literal["foo"]
,mypy will understand that variable is not only of type str
, but is alsoequal to specifically the string "foo"
.
This feature is primarily useful when annotating functions that behavedifferently based on the exact value the caller provides. For example,suppose we have a function fetch_data(…)
that returns bytes
if thefirst argument is True
, and str
if it’s False
. We can construct aprecise type signature for this function using Literal[…]
and overloads:
- from typing import overload, Union, Literal
- # The first two overloads use Literal[...] so we can
- # have precise return types:
- @overload
- def fetch_data(raw: Literal[True]) -> bytes: ...
- @overload
- def fetch_data(raw: Literal[False]) -> str: ...
- # The last overload is a fallback in case the caller
- # provides a regular bool:
- @overload
- def fetch_data(raw: bool) -> Union[bytes, str]: ...
- def fetch_data(raw: bool) -> Union[bytes, str]:
- # Implementation is omitted
- ...
- reveal_type(fetch_data(True)) # Revealed type is 'bytes'
- reveal_type(fetch_data(False)) # Revealed type is 'str'
- # Variables declared without annotations will continue to have an
- # inferred type of 'bool'.
- variable = True
- reveal_type(fetch_data(variable)) # Revealed type is 'Union[bytes, str]'
Note
The examples in this page import Literal
as well as Final
andTypedDict
from the typing
module. These types were added totyping
in Python 3.8, but are also available for use in Python 2.7and 3.4 - 3.7 via the typing_extensions
package.