Skip to content

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

@tmke8

Description

@tmke8

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:

_set_new_attribute(cls, '__replace__', _replace)

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions