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.
Python does not natively support excluding types, but you could add an if statement and then use raise just inside the function that displays an error if a certain type is passed in.
def function_except_str(x: Iterable):
if type(x) is str:
raise Exception("Invalid argument passed into function")
else:
pass
Yes, it is possible. You can use TypeVar class. Refer to this solution.
from typing import TypeVar, Union
T = TypeVar('T', bound=Iterable)
def func(arg: Union[T, str]) -> T:
if isinstance(arg, str):
raise ValueError("arg must not be a str")
return arg
func will take argument arg in parameter that should be iterable or a String. But type String will throw a value error, this will ensure that input is an iterable.