Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a tiny bit more special-casing for sum #8231

Merged
merged 1 commit into from
Jul 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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