在Python中,是否可以声明一个类型提示来排除某些类型的匹配?
例如,有没有办法声明一个类型提示为“
typing.Iterable
except not str
”之类的?
Python类型提示不支持排除类型,但是,您可以使用Union类型来指定您想要获取的类型。
所以类似:
def x(x: Iterable[Union[int, str, dict]]):
pass
x([1]) # correct
x([1, ""]) # correct
x([None]) # not correct
如果你想获得除你可以做的事情之外的所有类型,一种使
Union[]
更短的方法:
expected_types = Union[int, str, dict]
def x(x: Iterable[expected_types]):
pass
这就像上面的代码一样工作。
Python 本身不支持排除类型,但您可以添加 if 语句,然后在函数内部使用 raise,如果传入特定类型,则显示错误。
def function_except_str(x: Iterable):
if type(x) is str:
raise Exception("Invalid argument passed into function")
else:
pass
是的,这是可能的。您可以使用 TypeVar 类。请参考此解决方案。
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 将在参数中采用参数 arg,该参数应该是可迭代的或字符串。但是 String 类型会抛出值错误,这将确保输入是可迭代的。