重载以下可选参数

2024-09-28 17:21:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类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错误


Tags: pyselfnonefalsefoomaindeftype
2条回答

尝试:

@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):
    ...

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

这似乎有效:

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))

很多过载,但这可能是不可避免的

相关问题 更多 >