【发布时间】:2021-05-31 05:35:54
【问题描述】:
我有一个文件t.py,它有一个类Animal 和一个子类Cat。两者都有方法foo,根据布尔值inplace的值有不同的返回类型。
这是文件的完整代码:
# t.py
from __future__ import annotations
from typing import TypeVar, Optional, overload, Literal
CatOrDog = TypeVar("CatOrDog", bound="Animal")
class Animal:
@overload
def foo(self: CatOrDog, inplace: Literal[False], bar) -> CatOrDog:
...
@overload
def foo(self: CatOrDog, inplace: Literal[True], bar) -> None:
...
def foo(
self: CatOrDog, inplace: bool = False, bar=None
) -> Optional[CatOrDog]:
...
def ffill(self) -> Optional[CatOrDog]:
return self.foo(bar="a")
class Cat(Animal):
@overload
def foo(self, inplace: Literal[False], bar) -> Cat:
...
@overload
def foo(self, inplace: Literal[True], bar) -> None:
...
def foo(self, inplace: bool = False, bar=None) -> Optional[Cat]:
...
如果我在上面运行mypy,我会得到
$ mypy t.py
t.py:23: error: No overload variant of "foo" of "Animal" matches argument type "str"
t.py:23: note: Possible overload variants:
t.py:23: note: def foo(self, inplace: Literal[False], bar: Any) -> Animal
t.py:23: note: def foo(self, inplace: Literal[True], bar: Any) -> None
Found 1 error in 1 file (checked 1 source file)
如何正确重载foo,以便我可以调用self.foo(bar="a")?我尝试过设置bar: Any,但不起作用。
【问题讨论】:
标签: python mypy static-typing