![](/img/trans.png)
[英]Generic protocols: mypy error: Argument 1 has incompatible type …; expected
[英]Why mypy is not throwing an error if interface and implementation has a different argument name
我今天在我們的代碼庫中發現了這個錯誤(簡化示例):
from abc import ABC, abstractmethod
class Interface(ABC):
@abstractmethod
def method(self, variable: str) -> str:
pass
class Implementation(Interface):
def method(self, variable_changed: str) -> str:
return "A"
Implementation().method("d") # works
Implementation().method(variable="d") # error
Implementation().method(variable_changed="d") # works
這里我們有一個 class 實現了一個接口。 這一切都很好,但是實現更改了方法的第一個參數的名稱。 如果我運行 mypy,我會得到一個錯誤,因為實現不遵循接口定義的契約。 令我驚訝的是,事實並非如此。
我不確定這是否有意為之,但我想盡快檢測到這些類型的不匹配。 知道如何修復 mypy 或者如何啟用這種檢測以防它不是錯誤嗎?
如果參數未明確指定為命名,則 Mypy 會將參數視為位置參數。 因此,您的Interface
只要求該method
接受一個參數,而不是它有一個特定的名稱。
要將其指定為命名參數(強制實現匹配名稱),您需要執行以下操作:
def method(self, *, variable: str) -> str:
說variable
是一個命名參數(並且必須始終這樣調用)。
有關在 mypy 中更改此行為的討論,請參閱相關的 GitHub 問題: https://github.com/python/mypy/issues/6709
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.