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']):
...
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With