考慮以下最小的例子:
from array import array
def foo(arr: array) -> None:
print(arr)
我有一個函式,它需要一個array引數。
我的專案是靜態型別的,并且使用mypy。
Mypy抱怨說。
Mypy: 缺少通用型別 "陣列 "的型別引數。
你能幫助我理解我應該如何輸入提示引數嗎?我似乎找不到關于這個問題的檔案。我不明白為什么Mypy會認為這是一個通用型別。
澄清一下,根據我的理解,我使用的型別提示是有效的,但是 mypy 仍然抱怨,因為它認為它是一個通用型別,并且希望得到 "元素 "的型別。我是否遺漏了什么,還是說這是mypy的一個錯誤?
與此相關。 陣列的型別提示是什么?
uj5u.com熱心網友回復:
大部分的標準庫都沒有型別注釋。mypy使用的是typeshed專案的標準庫存根(與標準庫一起,它還包含了由不同貢獻者提供的流行第三方庫的注釋)。對于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"/span>, "I"/span>, "l"/span>, "L", "q", "Q"]
_FloatTypeCode = Literal["f", "d"]。
_UnicodeTypeCode = Literal["u"]。
_TypeCode = Union[_IntTypeCode, _FloatTypeCode, _UnicodeTypeCode]
_T = TypeVar("_T"/span>, int, float, str)
型別代碼。str
class array(MutableSequence[_T], Generic[_T]) 。
型別代碼。_TypeCode
itemsize。int: 型別代碼: _TypeCode
@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
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/306902.html
標籤:
