【问题标题】:type hinting an array类型提示数组
【发布时间】:2021-11-10 23:15:37
【问题描述】:

考虑以下最小示例:

from array import array


def foo(arr: array) -> None:
    print(arr)

我有一个带有array 参数的函数。 我的项目是静态类型的并使用mypy。 Mypy 抱怨说: Mypy: Missing type parameters for generic type "array".

你能帮我理解我应该如何输入提示参数吗?我似乎无法找到有关该主题的文档。我不明白为什么 mypy 会认为这是一个泛型类型。

为了澄清,据我了解,我使用的类型提示有效,但 mypy 仍然抱怨,因为它认为它是泛型类型,并且想要“元素”的类型。我错过了什么,还是 mypy 中的错误?

与此相关: What's the type hint for an array?

【问题讨论】:

    标签: python arrays type-hinting mypy python-typing


    【解决方案1】:

    大多数标准库都没有类型注释。 mypy 正在使用来自 typeshed 项目的标准库的存根(与标准库一起,还包含各种贡献者提供的流行第三方库的注释)。对于array module,您可以看到它的类型被注释为泛型:

    import sys
    from typing import Any, BinaryIO, Generic, Iterable, MutableSequence, Tuple, TypeVar, Union, overload
    from typing_extensions import Literal
    
    _IntTypeCode = Literal["b", "B", "h", "H", "i", "I", "l", "L", "q", "Q"]
    _FloatTypeCode = Literal["f", "d"]
    _UnicodeTypeCode = Literal["u"]
    _TypeCode = Union[_IntTypeCode, _FloatTypeCode, _UnicodeTypeCode]
    
    _T = TypeVar("_T", int, float, str)
    
    typecodes: str
    
    class array(MutableSequence[_T], Generic[_T]):
        typecode: _TypeCode
        itemsize: int
        @overload
        def __init__(self: array[int], typecode: _IntTypeCode, __initializer: bytes | Iterable[_T] = ...) -> None: ...
        @overload
        def __init__(self: array[float], typecode: _FloatTypeCode, __initializer: bytes | Iterable[_T] = ...) -> None: ...
        @overload
        def __init__(self: array[str], typecode: _UnicodeTypeCode, __initializer: bytes | Iterable[_T] = ...) -> None: ...
        @overload
        def __init__(self, typecode: str, __initializer: bytes | Iterable[_T] = ...) -> None: ...
        def append(self, __v: _T) -> None: ...
    
        ...
    

    解决方案是使用MutableSequence,如您链接到的问题中所述。请注意,由于 Python 3.9+、typing.MutableSequence(以及诸如 typing.Listtyping.Dict 之类的东西)已被弃用,并且类型本身支持泛型,因此请使用 import collectionscollections.abc.MutableSequence

    【讨论】:

    • 感谢您提供详细且具有教育意义的答案。
    猜你喜欢
    • 2015-11-10
    • 2021-06-13
    • 2019-09-08
    • 2015-05-23
    • 2021-02-17
    • 2014-08-08
    • 2017-09-09
    • 2014-01-12
    • 2010-10-21
    相关资源
    最近更新 更多