Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 type hint for string options [duplicate]

Let's say, I have a function with a string argument corresponding for a method name:

def func(method: str):
    if method not in ('simple_method', 'some_other_method'):
        raise ValueError('Unknown method')

Can I add all the possible supported options (strings) as a type hint for this argument? For instance, something like this (which doesn't work since there is no Str in typing):

from typing import Str

def func(method: Str['simple_method', 'some_other_method']):
    ...
like image 218
Vlad Starostin Avatar asked Sep 26 '19 10:09

Vlad Starostin


1 Answers

Its not possible just with the type hints, the correct way should be with 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)
like image 144
Owlzy Avatar answered Sep 19 '22 07:09

Owlzy