readinto()
我正在尝试向从派生的自定义类中声明的方法添加参数类型RawIOBase
,如下所示:
from io import RawIOBase
class Reader(RawIOBase):
def readinto(self, buf: bytearray) -> int:
pass # actual implementation omitted
但 pyright 抱怨道:
io.py:6:9 - error: Method "readinto" overrides class "_RawIOBase" in an incompatible manner
Parameter 2 type mismatch: base parameter is type "WriteableBuffer", override parameter is type "bytearray"
"Buffer" is not assignable to "bytearray" (reportIncompatibleMethodOverride)
1 error, 0 warnings, 0 informations
我该如何解决这个问题?注意:我知道我可以完全删除类型提示。我想改为为其分配正确的类型。
我正在使用 Python 3.13.3 和 pyright 1.1.400。
_typeshed
您需要使用与基类相同的类型定义。您可以通过从包中导入相同的类型别名来使用它,前提是您将其置于TYPE_CHECKING
保护之下:您可以信赖在类型检查器下运行时
_typeshed
存在的包,因为类型检查器会自带该包。例如,这就是它知道 的签名是什么的原因。出于同样的原因,我在上面添加了 ,因为这也是已记录签名的一部分。pyright
RawIOBase.readinto()
MaybeNone
或者,因为
WriteableBuffer
只是 的类型别名collections.abc.Buffer
,所以以下内容也有效(MaybeNone
用重新定义替换):请参阅“
Any
技巧”以了解为什么MaybeNone
是 的别名Any
。