【发布时间】:2020-02-26 06:02:01
【问题描述】:
在 Python 中,是否可以声明从匹配中排除某些类型的类型提示?例如,有没有办法声明“typing.Iterable except not str”之类的类型提示?
【问题讨论】:
在 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
这就像上面的代码一样工作。
【讨论】:
Iterable (包含任何类型的对象),但 not str (可迭代)本身。对我想要支持的类型进行Union 可能会无限长。