python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.57k stars 2.85k forks source link

`builtins.sum`: Spurious error for operands having `__add__` defined using `partialmetho` #17734

Open inducer opened 2 months ago

inducer commented 2 months ago

Bug Report

This is a follow-on from https://github.com/python/typeshed/issues/7739. See there for additional context provided by @srittau and @AlexWaygood.

To Reproduce

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)

Expected Behavior

The above seems like a legitimate way to define __add__.

Actual Behavior

$ 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)

mypy 1.11.1's output is essentially unchanged.

Your Environment

cc @kaushikcfd

erictraut commented 2 months ago

I think this is because mypy has no special-case logic for functools.partialmethod. If I'm correct, this issue could be considered a duplicate of #8619.