是否有一个Python类型的注释代表具有`__contains__`方法的东西?

Ant*_*yko 5 python types annotations typing

我寻找Type以下类型检查正常的:

import typing

def f(a: str, collection: Type):
    return a in collection
Run Code Online (Sandbox Code Playgroud)

也就是说,Type断言collection__contains__

Car*_*ate 8

我将此页面添加为书签,因为搜索起来很麻烦,但也非常有帮助。

正如您在该表顶部看到的, aContainer是一个具有__contains__方法的对象:

from typing import Container

def f(a: str, collection: Container[str]):
    return a in collection
Run Code Online (Sandbox Code Playgroud)

该表引用 中的类collections,但typing包含相同类的通用类型变体。

如果collections.Container/typing.Container不存在,您也可以创建自己的Protocol以正确提示它。