Skip to content

Commit

Permalink
Add a tiny bit more special-casing for sum (#8231)
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexWaygood committed Jul 2, 2022
1 parent 1f0172c commit e19073e
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 3 deletions.
7 changes: 4 additions & 3 deletions stdlib/builtins.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ class super:

_PositiveInteger: TypeAlias = Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
_NegativeInteger: TypeAlias = Literal[-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -20]
_LiteralInteger = _PositiveInteger | _NegativeInteger | Literal[0] # noqa: Y026 # TODO: Use TypeAlias once mypy bugs are fixed

class int:
@overload
Expand Down Expand Up @@ -1648,14 +1649,14 @@ _SupportsSumNoDefaultT = TypeVar("_SupportsSumNoDefaultT", bound=_SupportsSumWit
# In general, the return type of `x + x` is *not* guaranteed to be the same type as x.
# However, we can't express that in the stub for `sum()`
# without creating many false-positive errors (see #7578).
# Instead, we special-case the most common example of this: bool.
# Instead, we special-case the most common examples of this: bool and literal integers.
if sys.version_info >= (3, 8):
@overload
def sum(__iterable: Iterable[bool], start: int = ...) -> int: ... # type: ignore[misc]
def sum(__iterable: Iterable[bool | _LiteralInteger], start: int = ...) -> int: ... # type: ignore[misc]

else:
@overload
def sum(__iterable: Iterable[bool], __start: int = ...) -> int: ... # type: ignore[misc]
def sum(__iterable: Iterable[bool | _LiteralInteger], __start: int = ...) -> int: ... # type: ignore[misc]

@overload
def sum(__iterable: Iterable[_SupportsSumNoDefaultT]) -> _SupportsSumNoDefaultT | Literal[0]: ...
Expand Down
3 changes: 3 additions & 0 deletions test_cases/stdlib/builtins/test_sum.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,14 @@ def __radd__(self, other: Any) -> "Baz":
return Baz()


literal_list: List[Literal[0, 1]] = [0, 1, 1]

assert_type(sum([2, 4]), int)
assert_type(sum([3, 5], 4), int)

assert_type(sum([True, False]), int)
assert_type(sum([True, False], True), int)
assert_type(sum(literal_list), int)

assert_type(sum([["foo"], ["bar"]], ["baz"]), List[str])

Expand Down

0 comments on commit e19073e

Please sign in to comment.