可选参数之后的重载

mar*_*lli 9 python static-typing mypy

我有一个类Animal,该类的方法foo根据inplace可选参数后面的布尔参数具有不同的返回类型bar。我想重载该函数,以便在已知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))
Run Code Online (Sandbox Code Playgroud)
$ 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)
Run Code Online (Sandbox Code Playgroud)

https://mypy-play.net/?mypy=latest&python=3.9&gist=49da369f6343543769eed2060fa61639

如何避免Overloaded function signatures 1 and 2 overlap with incompatible return types第 8 行的错误?

hus*_*sic 0

尝试:

@overload
def foo(self, inplace: Literal[False]=..., bar=...) -> Animal:
    ...

@overload
def foo(self, inplace: Literal[True], bar=...,) -> None:
    ...

def foo(self, inplace=False, bar=None):
    ...
Run Code Online (Sandbox Code Playgroud)

我更改了参数的顺序,否则第二个重载应该不正确。