Python type hints - typing.Literal


Python tip:

You can use Literal to indicate that value can be one of the provided literals.

Static type checkers will report an error when the value doesn't match one of the provided literals.

https://mypy.readthedocs.io/en/stable/literal_types.html#literal-types

from typing import Literal

STATUS = Literal["ACTIVE", "DISABLED"]


class User:
    def __init__(self, username: str, status: STATUS):
        self.username = username
        self.status = status


user = User("[email protected]", "CREATED")

"""
mypy example.py
example.py:12: error: Argument 2 to "User" has incompatible type "Literal['CREATED']";
expected "Union[Literal['ACTIVE'], Literal['DISABLED']]"
Found 1 error in 1 file (checked 1 source file)
"""