是否有 Python 类型的注释表示具有“__contains__”方法的东西?

Is there a Python type for annotation that represents something that has `__contains__` method?

我寻找 Type 这样下面的类型检查就可以了:

import typing

def f(a: str, collection: Type):
    return a in collection

也就是说,Type 断言 collection__contains__

我将 this 页面加入书签,因为搜索起来很麻烦,但也很有帮助。

正如您在 table 顶部看到的那样,Container 是一个具有 __contains__ 方法的对象:

from typing import Container

def f(a: str, collection: Container[str]):
    return a in collection

table 引用 collections 中的 类,但 typing 包含相同 类.

的通用类型变体

如果 collections.Container/typing.Container 不存在,您也可以 正确提示它。