我正在try 理解typing.overload
,并将其应用到一个简单的例子中,其中我需要一个接受输入x: Literal["foo", "bar"]
并返回列表[x]
的函数.
我希望mypy根据值x
将结果列表输入为list[Literal["foo"]]
或list[Literal["bar"]]
.
我知道我可以用TypeVar
来实现这一点,但我仍然想知道为什么下面的代码会失败,并出现以下错误:
test.py:14: error: Overloaded function implementation cannot produce return type of signature 1
test.py:14: error: Overloaded function implementation cannot produce return type of signature 2
from typing import Literal, overload
@overload
def f(x: Literal["foo"]) -> list[Literal["foo"]]:
...
@overload
def f(x: Literal["bar"]) -> list[Literal["bar"]]:
...
def f(x: Literal["foo", "bar"]) -> list[Literal["foo", "bar"]]:
return [x]