typeshed icon indicating copy to clipboard operation
typeshed copied to clipboard

`builtins.sum`: Spurious error for operands having `__add__` defined using `partialmethod`

Open kaushikcfd opened this issue 3 years ago • 2 comments

Here's a minimal reproducer:

from __future__ import annotations
from functools import partialmethod

class A:
    def my_add(self, other: A, reverse: bool) -> A:
        return self

    __add__ = partialmethod(my_add, reverse=False)

a = A()
aa = A()
aaa = A()
result = sum([aa, a], start=aaa)

And the commands to reproduce it:

$ mypy --version
mypy 0.950 (compiled: yes)

$ mypy --show-error-codes --strict  mypy_bug_report.py 
mypy_bug_report.py:15: error: No overload variant of "sum" matches argument types "List[A]", "A"  [call-overload]
mypy_bug_report.py:15: note: Possible overload variants:
mypy_bug_report.py:15: note:     def [_SumT <: _SupportsSum] sum(Iterable[_SumT]) -> Union[_SumT, Literal[0]]
mypy_bug_report.py:15: note:     def [_SumT <: _SupportsSum, _SumS <: _SupportsSum] sum(Iterable[_SumT], start: _SumS) -> Union[_SumT, _SumS]
Found 1 error in 1 file (checked 1 source file)

Related https://github.com/python/typeshed/issues/7735, https://github.com/python/typeshed/pull/7578

kaushikcfd avatar Apr 29 '22 00:04 kaushikcfd

It appears that this is a regression. mypy 0.942 does not object to the code in the OP.

inducer avatar Apr 29 '22 00:04 inducer

This still (unsurprisingly) reproduces after the recent changes to the sum stub. Here's the current error message:

(.venv) C:\Users\alexw\coding\typeshed>mypy test.py --strict --show-error-codes --custom-typeshed-dir .
test.py:13: error: No overload variant of "sum" matches argument types "List[A]", "A"  [call-overload]
test.py:13: note: Possible overload variants:
test.py:13: note:     def sum(__iterable, Iterable[bool], start: int = ...) -> int
test.py:13: note:     def [_SupportsSumNoDefaultT <: _SupportsSumWithNoDefaultGiven] sum(__iterable, Iterable[_SupportsSumNoDefaultT]) -> Union[_SupportsSumNoDefaultT, Literal[0]]
test.py:13: note:     def [_AddableT1 <: SupportsAdd[Any, Any], _AddableT2 <: SupportsAdd[Any, Any]] sum(__iterable, Iterable[_AddableT1], start: _AddableT2) -> Union[_AddableT1, _AddableT2]
Found 1 error in 1 file (checked 1 source file)

The reason why there's now an error where previously there was none is almost certainly due to changes made in typeshed between 0.942 and 0.950 that made the stub forsum` more complicated. Nonetheless, I feel like this is sort-of a bug in mypy's understanding of higher-order callables rather than a bug in the stub. In an ideal world, mypy should be able to understand that the arguments being passed in here match the third overload here:

https://github.com/python/typeshed/blob/1828ba2045f1bece898058d917b8f27989d815a7/stdlib/builtins.pyi#L1664-L1665

AlexWaygood avatar Jun 13 '22 22:06 AlexWaygood