From 4ac3aa3710fa588e55831238c36aa34708a2fc3d Mon Sep 17 00:00:00 2001 From: KotlinIsland <65446343+kotlinisland@users.noreply.github.com> Date: Sun, 21 Sep 2025 13:50:53 +1000 Subject: [PATCH] fix `list.copy` to use the expected type --- stdlib/@tests/test_cases/builtins/check_list.py | 5 +++++ stdlib/builtins.pyi | 3 ++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/stdlib/@tests/test_cases/builtins/check_list.py b/stdlib/@tests/test_cases/builtins/check_list.py index 4113f5c66182..141dfcb3021c 100644 --- a/stdlib/@tests/test_cases/builtins/check_list.py +++ b/stdlib/@tests/test_cases/builtins/check_list.py @@ -19,3 +19,8 @@ def asd(self) -> int: assert_type(combined, List[Union[Foo, Bar]]) for item in combined: assert_type(item.asd(), int) + +l1: list[int] = [1] +l2: list[object] = l1.copy() +# this is an error, because a list of ints can't be a list of strs +l3: list[str] = l1.copy() # type: ignore diff --git a/stdlib/builtins.pyi b/stdlib/builtins.pyi index bcfc81622179..29cf6c5a167b 100644 --- a/stdlib/builtins.pyi +++ b/stdlib/builtins.pyi @@ -1104,7 +1104,8 @@ class list(MutableSequence[_T]): def __init__(self) -> None: ... @overload def __init__(self, iterable: Iterable[_T], /) -> None: ... - def copy(self) -> list[_T]: ... + # `copy` returns a new object, so capture the expected return type here using a type var + def copy(self) -> list[_S | _T]: ... def append(self, object: _T, /) -> None: ... def extend(self, iterable: Iterable[_T], /) -> None: ... def pop(self, index: SupportsIndex = -1, /) -> _T: ...