When using key function in min builtin function, default None value and returning it from a function which has an Optional type, mypy reports a problem where I believe there is none.
This is not a stub bug as I expected initially when got bitten by this. min is defined correctly with two different typevars. This is a strange failure of inference.
The following snippet demonstrates the weird inconsistency:
from __future__ importannotationsdeffoo(x: list[list[int]]) ->list[int] |None:
reveal_type(min(x, key=len, default=None)) # N: Revealed type is "Union[builtins.list[builtins.int], None]"returnmin(x, key=len, default=None) # E: Argument "key" to "min" has incompatible type "Callable[[Sized], int]"; expected "Callable[[list[int] | None], SupportsDunderLT[Any] | SupportsDunderGT[Any]]" [arg-type]foos: list[list[int]]
reveal_type(min(foos, key=len, default=None)) # N: Revealed type is "Union[builtins.list[builtins.int], None]"min_foo: list[int] |None=min(foos, key=len, default=None) # E: Argument "key" to "min" has incompatible type "Callable[[Sized], int]"; expected "Callable[[list[int] | None], SupportsDunderLT[Any] | SupportsDunderGT[Any]]" [arg-type]
Note that return line produces an arg-type error, but the same expression (!) on the previous line has type assignable to return type. The same happens outside of the function with and without output types.
Got bitten by this too; the weird thing is that assigning the expression to a (non annotated) name and returning the name works but returning the expression directly errors with Argument "key" to "min" has incompatible type "Callable[[Path], Any]"; expected "Callable[[Path | None], SupportsDunderLT[Any] | SupportsDunderGT[Any]]" [arg-type]
Activity
sterliakov commented on Jun 5, 2024
This is not a stub bug as I expected initially when got bitten by this. min is defined correctly with two different typevars. This is a strange failure of inference.
The following snippet demonstrates the weird inconsistency:
Note that return line produces an arg-type error, but the same expression (!) on the previous line has type assignable to return type. The same happens outside of the function with and without output types.
min is defined in typeshed as
The relevant overload is the last one.
Here's a playground link: https://mypy-play.net/?mypy=master&python=3.11&flags=strict&gist=8b209a7e7c9ddf0c03f3f6dfb0153316
gsakkis commented on Apr 26, 2025
Got bitten by this too; the weird thing is that assigning the expression to a (non annotated) name and returning the name works but returning the expression directly errors with Argument "key" to "min" has incompatible type "Callable[[Path], Any]"; expected "Callable[[Path | None], SupportsDunderLT[Any] | SupportsDunderGT[Any]]" [arg-type]
Merge branch 'master' into bugfix/pythongh-17221-typevar-union-context
Merge branch 'master' into bugfix/pythongh-17221-typevar-union-context
Extend special case for context-based typevar inference to typevar un…