【发布时间】:2021-02-03 18:21:34
【问题描述】:
我寻找 Type 以便以下类型检查正常:
import typing
def f(a: str, collection: Type):
return a in collection
也就是说,Type 断言 collection 具有 __contains__。
【问题讨论】:
标签: python types annotations typing
我寻找 Type 以便以下类型检查正常:
import typing
def f(a: str, collection: Type):
return a in collection
也就是说,Type 断言 collection 具有 __contains__。
【问题讨论】:
标签: python types annotations typing
我将this 页面添加为书签,因为搜索起来很麻烦,但也很有帮助。
正如您在表格顶部看到的,Container 是一个具有__contains__ 方法的对象:
from typing import Container
def f(a: str, collection: Container[str]):
return a in collection
该表引用collections 中的类,但typing 包含相同类的通用类型变体。
如果collections.Container/typing.Container 不存在,您也可以通过create your own Protocol 对其进行正确提示。
【讨论】: