【问题标题】:Is there a Python type for annotation that represents something that has `__contains__` method?是否有用于表示具有 __contains__ 方法的注释的 Python 类型?
【发布时间】: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


【解决方案1】:

我将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 对其进行正确提示。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-19
    • 2021-09-13
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    • 2020-03-23
    • 2016-10-26
    相关资源
    最近更新 更多