I try to restrict the 'parameter' type to be int or list like the function 'f' below. However, Pycharm does not show a warning at the line f("weewfwef") about wrong parameter type, which means this (parameter : [int, list]) is not correct.
In Python, is it possible to restrict the type of a python function parameter to two possible types?
def f(parameter : [int, list]):
if len(str(parameter)) <= 3:
return 3
else:
return [1]
if __name__ == '__main__':
f("weewfwef")
The term you're looking for is a union type.
from typing import Union
def f(parameter: Union[int, list]):
...
Union
is not limited to two types. If you ever have a value which is one of several known types, but you can't necessarily know which one, you can use Union[...]
to encapsulate that information.
Try out typing.Union
from typing import Union
def f(parameter : Union[int,list]):
if len(str(parameter)) <= 3:
return 3
else:
return [1]
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