【发布时间】:2021-01-30 10:04:33
【问题描述】:
考虑:
from __future__ import annotations
class A:
@classmethod
def get(cls) -> A:
return cls()
class B(A):
pass
def func() -> B: # Line 12
return B.get()
运行 mypy 得到:
$ mypy test.py
test.py:12: error: Incompatible return value type (got "A", expected "B")
Found 1 error in 1 file (checked 1 source file)
此外,我已经检查过旧式递归注释是否有效。那就是:
# from __future__ import annotations
class A:
@classmethod
def get(cls) -> "A":
# ...
...无济于事。
当然可以:
from typing import cast
def func() -> B: # Line 12
return cast(B, B.get())
每次出现这种情况。但我想避免这样做。
应该如何输入这个?
【问题讨论】:
-
我不确定你在问什么。如果你想返回
A,你需要明确地转换它。如果您只想正确地对函数进行类型注释,为什么不def func() -> A? -
我实际上想在
func中返回B。例如,假设我们有代表数据库实体的类。我们有一个公共类Entity和子类User和Project。这些子类还具有其他重要的特殊属性。我们希望明确说明您是返回User还是Project,因为这会限制我们在下游可以做的事情。
标签: python mypy python-typing