大多数标准库都没有类型注释。 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.List 和 typing.Dict 之类的东西)已被弃用,并且类型本身支持泛型,因此请使用 import collections 和 collections.abc.MutableSequence