可选参数后的重载 [英] overload following optional argument
本文介绍了可选参数后的重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类 Animal
和一个方法 foo
根据一个布尔参数 inplace
有不同的返回类型,它跟在一个可选参数 <代码>条形.我想重载该函数,以便在 inplace
的值已知时返回类型是已知的
I have a class Animal
with a method foo
which has different return types according to a boolean parameter inplace
which follows an optional parameter bar
. I'd like to overload the function so that the return type is known if the value of inplace
is known
这是我的代码:
# 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 行的 重载函数签名 1 和 2 与不兼容的返回类型重叠
错误?
How can I avoid the Overloaded function signatures 1 and 2 overlap with incompatible return types
error on line 8?
推荐答案
这似乎有效:
from __future__ import annotations
from typing import Optional, overload, Literal
class Animal:
# using defaults
@overload
def foo(self, bar=..., inplace: Literal[False]=...) -> Animal: ...
# using inplace = True
# with bar
@overload
def foo(self, bar, inplace: Literal[True]) -> None: ...
# without bar
@overload
def foo(self, *, inplace: Literal[True]) -> None: ...
# with bool
@overload
def foo(self, bar=..., inplace: bool=...) -> Optional[Animal]: ...
def foo(
self, bar=None, inplace = False
):
...
reveal_type(Animal().foo(bar='a'))
reveal_type(Animal().foo(bar='a', inplace=True))
reveal_type(Animal().foo(bar='a', inplace=False))
reveal_type(Animal().foo(inplace=True))
reveal_type(Animal().foo(inplace=False))
reveal_type(Animal().foo())
inplace: bool
reveal_type(Animal().foo(bar='a', inplace=inplace))
reveal_type(Animal().foo(inplace=inplace))
很多重载,但也许这是不可避免的
Lots of overloads, but perhaps that's inevitable here
这篇关于可选参数后的重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文