Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do not include non-init fields in the synthesized __replace__ method for dataclasses #18221

Merged
merged 2 commits into from
Dec 1, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
Do not include non-init fields in the synthesized __replace__ metho…
…d for dataclasses
  • Loading branch information
Viicos committed Dec 1, 2024
commit 3d0aa9e5619b4c9f5189eb7585bc22580728f976
2 changes: 1 addition & 1 deletion mypy/plugins/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,7 @@ def transform(self) -> bool:

def _add_dunder_replace(self, attributes: list[DataclassAttribute]) -> None:
"""Add a `__replace__` method to the class, which is used to replace attributes in the `copy` module."""
args = [attr.to_argument(self._cls.info, of="replace") for attr in attributes]
args = [attr.to_argument(self._cls.info, of="replace") for attr in attributes if attr.is_in_init]
type_vars = [tv for tv in self._cls.type_vars]
add_method_to_class(
self._api,
Expand Down
4 changes: 3 additions & 1 deletion test-data/unit/check-dataclasses.test
Original file line number Diff line number Diff line change
Expand Up @@ -2492,12 +2492,14 @@ class Child(Base):

[case testDunderReplacePresent]
# flags: --python-version 3.13
from dataclasses import dataclass
from dataclasses import dataclass, field

@dataclass
class Coords:
x: int
y: int
# non-init fields are not allowed with replace:
z: int = field(init=False)


replaced = Coords(2, 4).__replace__(x=2, y=5)
Expand Down
Loading