Skip to content

Commit b5ad828

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

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

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

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,24 @@ 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+
# defining separately so that the value is not inferred at the usage
27+
l_int = [1, 2]
28+
l_str = ["a", "b"]
29+
combined1 = l_int + l_str
30+
assert_type(combined1, List[Union[int, str]])
31+
32+
combined2: list[Union[int, str]]
33+
# mypy doesn't support this case
34+
combined2 = l_int + l_str # type: ignore[operator]
35+
assert_type(combined2, List[Union[int, str]])
36+
37+
combined2 = l_int + combined1
38+
assert_type(combined2, List[Union[int, str]])
39+
40+
# mypy doesn't support this case
41+
combined3: List[object] = l_int + l_str # type: ignore[operator]
42+
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)