Imagine a simple data class:

class Settings:
  m: int
  s: str

old = Settings(m=10, s="ten")

It feels normal to write new = old.replace(m=1), but we have to write new = replace(old, m=1). It feels so normal that I see people adding a member replace(self, **kwargs) to their dataclass types.

I see a single possible reason for this design choice, which I think is a bit purist: it would prevent dataclass members to be called 'replace'. Adding an underscore suffix would have solved that mostly (like with namedtuple), so I was wondering if the 'pollution' argument was indeed the rationale for choosing the non-member function.

EDIT: I'm not interested in hypotheses or opinions; I'm in pursuit of the history of this decision (which I respect).

  • I think this is a better forum than where the question was posted originally: stackoverflow.com/q/70201906/6610
    – xtofl
    Dec 2, 2021 at 15:24
  • 1
  • 1
    "It feels normal to write x = lst.len(), but we have to write x = len(lst)."
    – Caleth
    Dec 2, 2021 at 17:13
  • @Caleth Indeed. What justifies the inconsistency? Why is this choice not documented, is it so obvious, then?
    – xtofl
    Dec 3, 2021 at 7:00
  • I am explicitly not interested in opinions, but in the rationale that was used for this decition. I'll clarify that in the question.
    – xtofl
    Dec 4, 2021 at 15:27

1 Answer 1


For what it's worth, Raymond Hettinger (an author of namedtuple) has stated that he regrets opting for the namedtuple._replace approach (in this talk, around the 20 minute mark) because it makes the method "seem private" when it's actually not. I can only assume that the replace function was created in order to avoid this issue, while simultaneously allowing unaware developers to implement a dataclass.replace attribute or method without risking overshadowing this functionality.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.