Yai*_*r M 1 python arrays type-hinting mypy python-typing
考虑以下最小示例:
from array import array
def foo(arr: array) -> None:
print(arr)
Run Code Online (Sandbox Code Playgroud)
我有一个带有参数的函数array。我的项目是静态类型的并使用mypy。Mypy 抱怨说:
Mypy: Missing type parameters for generic type "array".
你能帮我理解我应该如何输入提示参数吗?我似乎找不到有关该主题的文档。我不明白为什么 mypy 会认为这是一个通用类型。
为了澄清,根据我的理解,我使用的类型提示有效,但 mypy 仍然抱怨,因为它认为它是通用类型,并且想要“元素”的类型。我是否遗漏了什么,或者是 mypy 中的错误?
与此相关: 数组的类型提示是什么?
大多数标准库都没有类型注释。正在使用typeshedmypy项目中标准库的存根(该项目与标准库一起,还包含由各个贡献者提供的流行第三方库的注释)。对于module,您可以看到它的类型注释为 generic:array
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: ...
...
Run Code Online (Sandbox Code Playgroud)
MutableSequence解决方案是按照您链接的问题中的回答所述使用。请注意,自 Python 3.9+ 起,typing.MutableSequence(以及诸如typing.List和 之类的东西typing.Dict)已被弃用,并且类型本身支持泛型,因此请使用import collections和collections.abc.MutableSequence