类型提示数组

type hinting an array

考虑以下最小示例:

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 中的错误?

与此相关:

大多数标准库都没有类型注释。 mypy 正在使用 typeshed project (which along with the standard library, also contains annotations for popular third-party library as provided by various contributers). For the 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