python / python/cpython

Add a new parameter to `@dataclass` to optionally turn off the synthesizing of a `__replace__` method

Open
#140,457 5 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

stdlib type-feature
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Feature or enhancement

Proposal:

Most (all?) synthesized methods on dataclasses can be turned off:

  • __init__ -> init=False
  • __repr__ -> repr=False
  • __eq__ -> eq=False
  • __match_args__ -> match_args=False
  • __slots__ -> slots=False
  • __lt__(), __le__(), __gt__(), __ge__() -> order=False

But __replace__ cannot be turned off, which presents a problem for generic dataclasses: https://discuss.python.org/t/make-replace-stop-interfering-with-variance-inference/96092/

I propose this

@dataclass(replace=False)
class D:
    x: int

to create a dataclass without __replace__ method.

As far as I can tell, all that's needed is to put a guard around this line:

https://github.com/python/cpython/blob/a4709e525f5bc3a1719b33f52377cccb2af70278/Lib/dataclasses.py#L1098

Has this already been discussed elsewhere?

I have already discussed this feature proposal on Discourse

Links to previous discussion of this feature:

I proposed it in this comment on the DPO thread: https://discuss.python.org/t/make-replace-stop-interfering-with-variance-inference/96092/19

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in Lib/dataclasses.py at the linked line where replace is synthesized, and inspect the surrounding dataclass parameter handling. Done means a replace=False dataclass does not receive replace, while the default behavior remains unchanged; add or update the relevant dataclasses tests as needed.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Feature
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
52/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.