Skip to content
Open
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
21 changes: 21 additions & 0 deletions stdlib/@tests/test_cases/check_copy.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,24 @@ def __replace__(self, /, *, value: str) -> Box[str]:
box1: Box[int] = Box(42)
box2 = copy.replace(box1, value="spam")
assert_type(box2, Box[str])


if sys.version_info >= (3, 13):
# Regression for #16582: a union whose members each have a field the
# others lack must not be rejected.
from dataclasses import dataclass

@dataclass(frozen=True)
class Circle:
name: str
radius: float

@dataclass(frozen=True)
class Square:
name: str
side: float

def rename(shape: Circle | Square) -> Circle | Square:
res = copy.replace(shape, name="renamed")
assert_type(res, Circle | Square)
return res
15 changes: 13 additions & 2 deletions stdlib/copy.pyi
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import sys
from typing import Any, Protocol, TypeVar, type_check_only
from typing_extensions import ParamSpec
from typing import Any, Protocol, TypeVar, final, overload, type_check_only
from typing_extensions import Never, ParamSpec

__all__ = ["Error", "copy", "deepcopy"]

Expand All @@ -13,6 +13,14 @@ class _SupportsReplace(Protocol[_P, _RT_co]):
# In reality doesn't support args, but there's no great way to express this.
def __replace__(self, /, *_: _P.args, **changes: _P.kwargs) -> _RT_co: ...

# @final + empty: no argument can be an instance of it. The second replace
# overload below is never matched directly; it exists so checkers fall back
# to argument-type expansion (typing spec overload evaluation step 3) and
# evaluate a union argument member-by-member. See #16582.
@final
@type_check_only
class _Unreplaceable: ...

# None in CPython but non-None in Jython
PyStringMap: Any

Expand All @@ -28,9 +36,12 @@ else:
if sys.version_info >= (3, 13):
__all__ += ["replace"]

@overload
def replace(
obj: _SupportsReplace[_P, _RT_co], /, *_: _P.args, **changes: _P.kwargs # does not accept positional arguments at runtime
) -> _RT_co: ...
@overload
def replace(obj: _Unreplaceable, /, **changes: object) -> Never: ...

class Error(Exception): ...

Expand Down
Loading