Overload + generic functions + union arguments = inconsistent results (wrong overload is matched?) #18321
Labels
bug
mypy got something wrong
topic-overloads
topic-type-context
Type context / bidirectional inference
Bug Report
If I have an
@overload
ed generic function, and call that function with a variable having union type, I get inconsistent results.To Reproduce
Expected Behavior
I expect that if the argument has type
str | list[str]
, thenmakelist(arg)
should be of typelist[str]
.Reason: the first
@overload
(def makelist(a: list[_T]) -> list[_T]: ...
) should matchlist[str]
. The second@overload
(def makelist(a: _T) -> list[_T]: ...
) should matchstr
. So in all cases of the argument's union type, the return type should belist[str]
.I also expect mypy to be consistent about expression types. Since mypy says
makelist(str_or_list_of_str)
has typelist[str | list[str]]
, thenlist_of_str: list[str] = makelist(str_or_list_of_str)
should raise an error.Actual Behavior
Your Environment
mypy 1.14.0 (compiled: yes)
mypy
pyproject.toml
:Python 3.10.12
If I had to guess, it seems like mypy is wrongly matching my
str | list[str]
argument to the broad overload (def makelist(a: _T) -> list[_T]: ...
). But I don't understand why it's not consistent.#17331 also involves overloads and generics. Perhaps it's related.
The text was updated successfully, but these errors were encountered: