【发布时间】:2020-03-20 15:02:54
【问题描述】:
我的项目依赖于将类型注释存储在存根文件中的另一个项目。在.py 文件中,另一个项目定义了一个我需要从以下对象继承的基类
# within a .py file
class Foo:
def bar(self, *baz):
raise NotImplementedError
在相应的.pyi 存根中,他们将其注释如下:
# whitin a .pyi file
from typing import Generic, TypeVar, Callable
T_co = TypeVar("T_co", covariant=True)
class Foo(Generic[T_co]):
bar: Callable[..., T_co]
对于我的项目,我想内联进行类型注释,即在 .py 文件中,并尝试在 Foo 的子类中进行,如下所示:
# within a .py file
class SubFoo(Foo):
def bar(self, baz: float) -> str:
pass
在此运行 mypy 会导致以下错误
error: Signature of "bar" incompatible with supertype "Foo"
如果我删除我的内联注释并将其添加到 .pyi 存根
# within a .pyi file
class SubFoo(Foo):
bar: Callable[[float], str]
mypy 运行良好。
我认为这两种方法是等效的,但显然情况并非如此。有人可以向我解释它们的不同之处以及我需要更改哪些内容才能使用内联注释吗?
在@Michael0x2a 答案的 cmets 中很明显,只有当您确实使用 .py 和 .pyi 文件时,该错误才会重现。您可以从上面here下载示例。
【问题讨论】:
标签: python python-3.6 mypy python-typing