diff --git a/mypy/plugins/dataclasses.py b/mypy/plugins/dataclasses.py index 81a5e70e6b3a..349eca7f0143 100644 --- a/mypy/plugins/dataclasses.py +++ b/mypy/plugins/dataclasses.py @@ -400,7 +400,11 @@ 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, diff --git a/test-data/unit/check-dataclasses.test b/test-data/unit/check-dataclasses.test index 294612db7ea5..6de428109c72 100644 --- a/test-data/unit/check-dataclasses.test +++ b/test-data/unit/check-dataclasses.test @@ -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)