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:

  1. from typing import overload, Union, Literal
  2.  
  3. # The first two overloads use Literal[...] so we can
  4. # have precise return types:
  5.  
  6. @overload
  7. def fetch_data(raw: Literal[True]) -> bytes: ...
  8. @overload
  9. def fetch_data(raw: Literal[False]) -> str: ...
  10.  
  11. # The last overload is a fallback in case the caller
  12. # provides a regular bool:
  13.  
  14. @overload
  15. def fetch_data(raw: bool) -> Union[bytes, str]: ...
  16.  
  17. def fetch_data(raw: bool) -> Union[bytes, str]:
  18. # Implementation is omitted
  19. ...
  20.  
  21. reveal_type(fetch_data(True)) # Revealed type is 'bytes'
  22. reveal_type(fetch_data(False)) # Revealed type is 'str'
  23.  
  24. # Variables declared without annotations will continue to have an
  25. # inferred type of 'bool'.
  26.  
  27. variable = True
  28. 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.