Skip to content

Commit 3c90c97

Browse files
AkuliAlexWaygoodpre-commit-ci[bot]
authored
List[Foo] + List[Bar] now returns List[Foo | Bar] (#8293)
Co-authored-by: Alex Waygood <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 0764f9f commit 3c90c97

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

stdlib/builtins.pyi

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -986,8 +986,12 @@ class list(MutableSequence[_T], Generic[_T]):
986986
@overload
987987
def __setitem__(self, __s: slice, __o: Iterable[_T]) -> None: ...
988988
def __delitem__(self, __i: SupportsIndex | slice) -> None: ...
989+
# Overloading looks unnecessary, but is needed to work around complex mypy problems
990+
@overload
989991
def __add__(self, __x: list[_T]) -> list[_T]: ...
990-
def __iadd__(self: Self, __x: Iterable[_T]) -> Self: ...
992+
@overload
993+
def __add__(self, __x: list[_S]) -> list[_S | _T]: ...
994+
def __iadd__(self: Self, __x: Iterable[_T]) -> Self: ... # type: ignore[misc]
991995
def __mul__(self, __n: SupportsIndex) -> list[_T]: ...
992996
def __rmul__(self, __n: SupportsIndex) -> list[_T]: ...
993997
def __imul__(self: Self, __n: SupportsIndex) -> Self: ...
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
from typing import List, Union
2+
from typing_extensions import assert_type
3+
4+
5+
# list.__add__ example from #8292
6+
class Foo:
7+
def asd(self) -> int:
8+
return 1
9+
10+
11+
class Bar:
12+
def asd(self) -> int:
13+
return 2
14+
15+
16+
combined = [Foo()] + [Bar()]
17+
assert_type(combined, List[Union[Foo, Bar]])
18+
for item in combined:
19+
assert_type(item.asd(), int)

0 commit comments

Comments
 (0)