Skip to content

Commit 80ffce8

Browse files
committed
fix list.__add__ to use the expected type
1 parent 7c8dce0 commit 80ffce8

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

stdlib/@tests/test_cases/builtins/check_list.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,23 @@ def asd(self) -> int:
1919
assert_type(combined, List[Union[Foo, Bar]])
2020
for item in combined:
2121
assert_type(item.asd(), int)
22+
23+
# ignoring this so we can test mypy and pyright separately
24+
# pyright: reportUnnecessaryTypeIgnoreComment=false
25+
26+
l_int = [1, 2]
27+
l_str = ["a", "b"]
28+
combined1 = l_int + l_str
29+
assert_type(combined1, List[int | str])
30+
31+
combined2: list[str | int]
32+
# mypy doesn't support this case
33+
combined2 = l_int + l_str # type: ignore[operator]
34+
assert_type(combined2, List[str | int])
35+
36+
combined2 = list[str]() + list[int | str]()
37+
assert_type(combined2, List[str | int])
38+
39+
# mypy doesn't support this case
40+
combined3: list[object] = l_int + l_str # type: ignore[operator]
41+
assert_type(combined3, List[object])

stdlib/builtins.pyi

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1137,9 +1137,10 @@ class list(MutableSequence[_T]):
11371137
def __delitem__(self, key: SupportsIndex | slice, /) -> None: ...
11381138
# Overloading looks unnecessary, but is needed to work around complex mypy problems
11391139
@overload
1140-
def __add__(self, value: list[_T], /) -> list[_T]: ...
1140+
# # `__add__` returns a new object, so we capture the expected result type with a type variable
1141+
def __add__(self, value: list[_T], /) -> list[_T1 | _T]: ...
11411142
@overload
1142-
def __add__(self, value: list[_S], /) -> list[_S | _T]: ...
1143+
def __add__(self, value: list[_S], /) -> list[_T1 | _T | _S]: ...
11431144
def __iadd__(self, value: Iterable[_T], /) -> Self: ... # type: ignore[misc]
11441145
def __mul__(self, value: SupportsIndex, /) -> list[_T]: ...
11451146
def __rmul__(self, value: SupportsIndex, /) -> list[_T]: ...

0 commit comments

Comments
 (0)