Open pgjones opened 1 year ago
Mypy's behavior here is correct.
The value g
has type Callable[[], dict] | Callable[[], Awaitable[dict]]
. A value of this type is not compatible with the first overload signature, but it is compatible with the second. The constraints of P
and T
are met with the following types:
P = []
T = int | Awaitable[int]
Mypy's constraint solver uses joins rather than unions, so it widens the type of T
to object
in this case. This is a legal solution for T
even though it's not as precise (narrow) as it could be.
When applying the solutions for P
and T
to the return type of the second overload, the result is def () -> Awaitable[object]
. That explains the behavior you're observing.
You likely thought that mypy would use "union expansion" for the type of argument g
and apply different overloads for each of the subtypes of the union, but union expansion is used only if the unexpanded argument types match zero overload signatures. In your example, the unexpanded union type works fine with the second overload signature, so union expansion isn't applied.
The mypy documentation for overloaded call evaluation is a bit vague about how this works. The pyright documentation for overloads is a bit more detailed, so it may help illuminate what's happening here.
Thanks, I'll read the documents and try to understand.
Would you know how to fix the typing of the ensure_async
function to preserve the dict type?
Bug Report
In the snippet below I'd expect the revealed type to be
def () -> typing.Awaitable[builtins.dict]
, notdef () -> typing.Awaitable[builtins.object]
.To Reproduce
https://mypy-play.net/?mypy=master&python=3.12&gist=f596993883d9235e669e38dbe212909e
Actual Behavior
main.py:18: note: Revealed type is "def () -> typing.Awaitable[builtins.object]"
Your Environment
mypy.ini
(and other config files):This may be related to https://github.com/python/mypy/issues/12385 - closest issue I can find.