如何正确键入注释自定义 MutableMapping 实现?

问题描述 投票:0回答:1

我有以下子类

MutableMapping

from typing import Hashable, Any, MutableMapping
from _typeshed import SupportsKeysAndGetItem

class MyMutableMapping(MutableMapping[Hashable, Any]):
    def update(self, other: SupportsKeysAndGetItem[Hashable, Any], /, **kwargs: Any) -> None:
        pass

但是,

mypy
抱怨我重写的
update
方法的签名。

test.py:5: error: Signature of "update" incompatible with supertype "MutableMapping"  [override]
test.py:5: note:      Superclass:
test.py:5: note:          @overload
test.py:5: note:          def update(self, SupportsKeysAndGetItem[Hashable, Any], /, **kwargs: Any) -> None
test.py:5: note:          @overload
test.py:5: note:          def update(self, Iterable[tuple[Hashable, Any]], /, **kwargs: Any) -> None
test.py:5: note:          @overload
test.py:5: note:          def update(self, **kwargs: Any) -> None
test.py:5: note:      Subclass:
test.py:5: note:          def update(self, SupportsKeysAndGetItem[Hashable, Any], /, **kwargs: Any) -> None
Found 1 error in 1 file (checked 1 source file)

我尽可能复制了

mypy
声称超类具有的确切签名,但没有运气。我做错了什么?

编辑:我已经在 github mypy 问题跟踪器中提交了 issue

python mypy typing
1个回答
0
投票

...复制 mypy 声称超类具有的确切签名...

你有吗?

overload
不是“其中之一”,而是实施时的“全部”。您的子类必须至少支持所有三种重载变体,而不是任意其中之一。以下类型检查:

from typing import Hashable, Any, Iterable, MutableMapping, overload
from _typeshed import SupportsKeysAndGetItem

class MyMutableMapping(MutableMapping[Hashable, Any]):
    @overload
    def update(self, arg: SupportsKeysAndGetItem[Hashable, Any], /, **kwargs: Any) -> None: ...
    @overload
    def update(self, arg: Iterable[tuple[Hashable, Any]], /, **kwargs: Any) -> None: ...
    @overload
    def update(self, /, **kwargs: Any) -> None: ...
    
    def update(self, arg: Any = None, /, **kwargs: Any) -> None: ...

游乐场

我不确定为什么在第三次重载中需要仅 pos 标记,但是

mypy
认为实现与第三次重载不兼容。 Pyright 没有,所以这可能是一个
mypy
bug。

另请参阅此答案了解

Hashable
用作映射键 - 可能不值得。

© www.soinside.com 2019 - 2024. All rights reserved.