Reputation: 411
I have a function:
def f(a: Sequence[str], b: Sequence[str]) -> List[str]:
return list(set(a) - set(b))
a = ['a', 'b', 'c']
b = ['b', 'c']
f(a, b)
But this function can be applicable not only for str
type but for other types that can be comparable (int, float, etc.). In this case how to set up type hints for a
and b
parameters?
Upvotes: 1
Views: 1515
Reputation: 1224
You should use the Any
Type if you are not sure
from typing import Any
def f(a: Sequence[Any], b: Sequence[Any]) -> List[Any]:
return list(set(a) - set(b))
a = ['a', 'b', 'c']
b = ['b', 'c']
f(a, b)
If you want to make it applicable only to those three types (int, float, str), you should use Union:
from typing import Union
def f(a: Sequence[Union[str, int, float]], b: Sequence[Union[str, int, float]]) -> List[Union[str, int, float]]:
return list(set(a) - set(b))
a = ['a', 'b', 'c']
b = ['b', 'c']
f(a, b)
As of python 3.10 the union type can be omitted and you can write it directly like so:
a: Sequence[str|int|float]
Upvotes: 2