我有一个Generic
基类,它以一种方法返回自身(get_self
)。我已经打字暗示了这一点。
然后,我有一个该基类的子类,它传入Generic
. 在那个儿童班里,我打电话给get_self
。我想将类型提示更新为子类的名称。
不过,mypy==0.782
正在报道error: Incompatible return value type (got "Foo[Bar]", expected "DFoo") [return-value]
。有什么办法可以做到这一点吗?
**编辑**
经过进一步思考,我决定重新解释这个问题。提前抱歉啰嗦了。
基类 ( Foo
) 有一个方法 ( get_self
) 类型,暗示返回其自身的实例
子类( DFoo
)不重写方法
然后子类使用 ( get_self
) 方法
并且知道返回类型实际上是子类的 ( DFoo
)
但是,静态类型检查器(例如mypy
:)不知道子类的方法实际上会返回子类的对象,因为它们正在使用基类中的类型提示
get_self
因此,如果不使用新类型提示在子类中重新声明方法 (),我的问题可能无法实现。
我可以使 的返回get_self
成为 a TypeVar
。然而,由于基类Foo
已经是 a Generic
,所以目前这是不可能的,因为它需要python/typing Higher-Kinded TypeVars #548中提到的“Higher-Kinded TypeVars” 。
示例脚本
我希望这能澄清我想要表达的意思。
from __future__ import annotations
from typing import Generic, TypeVar, cast
T = TypeVar("T")
class Foo(Generic[T]):
def get_self(self) -> Foo[T]:
# Other stuff happens here before the return
return self
class Bar:
pass
class DFoo(Foo[Bar]):
def do_something_get_self(self) -> DFoo:
# mypy error: Incompatible return value type (got "Foo[Bar]",
# expected "DFoo")
return self.get_self()
class DFooCast(Foo[Bar]):
def do_something_get_self(self) -> DFooCast:
# This works, but I don't like this method. I don't want to use `cast`
# all over the place.
return cast(DFooCast, self.get_self())
class DFooNoUpdatedTypeHint(Foo[Bar]):
def do_something_get_self(self) -> Foo[Bar]:
# mypy doesn't error here, but later on it will raise an error
# when using method's added in Foo subclasses
return self.get_self()
def dfoo_adds_method(self) -> None:
"""DFoo also has additional methods."""
dfoo = DFooNoUpdatedTypeHint()
dfoo.do_something_get_self().dfoo_adds_method() # error: "Foo[Bar]" has no attribute "dfoo_adds_method"
HUWWW
相关分类