Using Literal
in Python 3.8 and later
from typing import Literal
Using Literal
in all Python versions (1)
Literal
was added to typing.py
in 3.8, but you can use Literal
in older versions anyway.
First install typing_extensions
(pip install typing_extensions
) and then
from typing_extensions import Literal
This approach is supposed to work also in Python 3.8 and later.
Using Literal
in all Python versions (2)
For completeness, I’m also adding the try-except approach to import Literal
:
try:
from typing import Literal
except ImportError:
from typing_extensions import Literal
This should also work for all Python versions, given that typing_extensions
is installed if you’re using Python 3.7 or older.