In Python, is it possible to declare a type hint that excludes certain types from matching? For example, is there a way to declare a type hint that is "typing.Iterable except not str" or the like?
In Python, is it possible to declare a type hint that excludes certain types from matching? For example, is there a way to declare a type hint that is "typing.Iterable except not str" or the like?
python type hinting does not support excluding types, however you can use Union type to specify the types you want to get.
So something like:
def x(x: Iterable[Union[int, str, dict]]):
pass
x([1]) # correct
x([1, ""]) # correct
x([None]) # not correct
A way to make Union[] shorter if you want to get all types except something you can do:
expected_types = Union[int, str, dict]
def x(x: Iterable[expected_types]):
pass
This works just like the above code.