我有一个类Animal
,它有一个方法foo
,该方法根据可选参数bar
后面的布尔参数inplace
具有不同的返回类型。我希望重载该函数,以便在已知inplace
的值时知道返回类型
这是我的密码:
# main.py
from __future__ import annotations
from typing import Optional, overload, Literal
class Animal:
@overload
def foo(self, bar=..., inplace: Literal[False]=...) -> Animal:
...
@overload
def foo(self, bar=..., inplace: Literal[True]=...) -> None:
...
def foo(
self, bar=None, inplace: bool = False
) -> Optional[Animal]:
...
reveal_type(Animal().foo(bar='a'))
reveal_type(Animal().foo(inplace=True))
reveal_type(Animal().foo(inplace=False))
$ mypy main.py
main.py:8: error: Overloaded function signatures 1 and 2 overlap with incompatible return types
main.py:21: note: Revealed type is 'main.Animal'
main.py:22: note: Revealed type is 'None'
main.py:23: note: Revealed type is 'main.Animal'
Found 1 error in 1 file (checked 1 source file)
https://mypy-play.net/?mypy=latest&python=3.9&gist=49da369f6343543769eed2060fa61639
如何避免第8行的Overloaded function signatures 1 and 2 overlap with incompatible return types
错误
尝试:
我更改了args的顺序,否则第二个重载应该不正确
这似乎有效:
很多过载,但这可能是不可避免的
相关问题 更多 >
编程相关推荐