Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 排除特定类型的类型提示_Python_Types - Fatal编程技术网

Python 排除特定类型的类型提示

Python 排除特定类型的类型提示,python,types,Python,Types,在Python中,是否可以声明一个类型提示,将某些类型排除在匹配之外?例如,有没有一种方法可以声明一个类型提示,它是“typing.Iterablenotstr”之类的?python类型提示不支持排除类型,但是您可以使用Union type指定要获取的类型 比如: def x(x: Iterable[Union[int, str, dict]]): pass x([1]) # correct x([1, ""]) # correct x([None]) # not correct 如

在Python中,是否可以声明一个类型提示,将某些类型排除在匹配之外?例如,有没有一种方法可以声明一个类型提示,它是“
typing.Iterable
not
str
”之类的?

python类型提示不支持排除类型,但是您可以使用Union type指定要获取的类型

比如:

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
(包含任何类型的对象),但不支持
str
(Iterable)本身。对我想要支持的类型执行一个
Union
可能会无限长。@fluffy如果您的函数是这样工作的,那么使用常量EVERYTYPE_EXCEPT_STR怎么样?我的意思是我定义了一个注释类型,它包含我想要支持的最常见的iterable类型(STR除外),但这相当麻烦。无论如何,我希望得到一个更一般的答案,它不一定能处理我在问题中描述的确切情况。我想问一些更一般的问题,我不想因为我的具体要求而挂断回答。