python / python/cpython

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

未关闭
#140,457 5 条评论 3 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

stdlib type-feature
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

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

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 Lib/dataclasses.py 中合成 replace 的链接行开始,检查周围的 dataclass 参数处理。完成标准是:replace=False 的 dataclass 不会获得 replace,同时默认行为保持不变;根据需要添加或更新相关的 dataclasses 测试。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
backend
Issue 类型
功能
难度
2/5
预计耗时
1-3 小时
活跃度
停滞
描述清晰度
描述清楚
新手友好度
52/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。