Issue
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']):
...
Solution
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)
Answered By - Owlzy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.