Python 3 type hint for string options [duplicate]

Option 1: Literal

You can do that with literal types.

from typing import Literal
# from typing_extensions import Literal # Python 3.7 or below

def func(method: Literal['simple_method', 'some_other_method']):
    ...

Python 3.8

Thanks to the PEP 586, the Literal is already included by default in the Python 3.8 typing module.

Option 2: Enum

If you’d rather not use type hints, you could also consider enums like so:

from enum import Enum
class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

Once you have an enum with all the possible choices, you can hint the function in order to accept only your custom enum. More info here

Example:

from typing import NewType

Colors = NewType('Colors', Color)

Leave a Comment