8000 Catch more potential type errors in `builtins.sum` (#7578) · python/typeshed@d45c908 · GitHub
[go: up one dir, main page]

Skip to content

Commit d45c908

Browse files
authored
Catch more potential type errors in builtins.sum (#7578)
Use a ` TypeVar` bound to a `Protocol` defining `__add__`
1 parent 646993c commit d45c908

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

stdlib/builtins.pyi

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1477,16 +1477,23 @@ def sorted(
14771477
) -> list[SupportsRichComparisonT]: ...
14781478
@overload
14791479
def sorted(__iterable: Iterable[_T], *, key: Callable[[_T], SupportsRichComparison], reverse: bool = ...) -> list[_T]: ...
1480+
1481+
class _SupportsSum(Protocol):
1482+
def __add__(self, __x: Any) -> Any: ...
1483+
1484+
_SumT = TypeVar("_SumT", bound=_SupportsSum)
1485+
_SumS = TypeVar("_SumS", bound=_SupportsSum)
1486+
14801487
@overload
1481-
def sum(__iterable: Iterable[_T]) -> _T | Literal[0]: ...
1488+
def sum(__iterable: Iterable[_SumT]) -> _SumT | Literal[0]: ...
14821489

14831490
if sys.version_info >= (3, 8):
14841491
@overload
148 7261 5-
def sum(__iterable: Iterable[_T], start: _S) -> _T | _S: ...
1492+
def sum(__iterable: Iterable[_SumT], start: _SumS) -> _SumT | _SumS: ...
14861493

14871494
else:
14881495
@overload
1489-
def sum(__iterable: Iterable[_T], __start: _S) -> _T | _S: ...
1496+
def sum(__iterable: Iterable[_SumT], __start: _SumS) -> _SumT | _SumS: ...
14901497

14911498
# The argument to `vars()` has to have a `__dict__` attribute, so can't be annotated with `object`
14921499
# (A "SupportsDunderDict" protocol doesn't work)

0 commit comments

Comments
 (0)
0