Skip to content

3.13 Better Document __replace__ on Dataclasses and Named Tuples #121371

Open

Description

@max-muoto

Documentation

With named tuples and dataclasses now implementing __replace__, it would be good to have some clearer documentation on this somewhere. Type-checkers will likely have to implement support as a specific implementation detail, which MyPy is already starting to do (see here, for example), so having more formal documentation of this fact would helpful.

Activity

  1. serhiy-storchaka commented on Jul 4, 2024

    @serhiy-storchaka
    Member

    The __replace__ method itself is an implementation detail. Only the support of copy.replace() should be documented. In future we may add other ways to specify this.

    Special methods like __iter__ or __reduce__ are rarely documented. Instead the fact that objects are iterable or pickleable are documented.

  2. max-muoto commented on Jul 5, 2024

    @max-muoto
    ContributorAuthor

    The __replace__ method itself is an implementation detail. Only the support of copy.replace() should be documented. In future we may add other ways to specify this.

    Special methods like __iter__ or __reduce__ are rarely documented. Instead the fact that objects are iterable or pickleable are documented.

    Makes sense, I will just say it just being documented in copy, while it needing to be special-cased I think makes it harder to realize that type-checkers should likely implement support - so I do wonder if there's a better way to indicate things like that long-term.

  3. randolf-scholz commented on Jul 1, 2025

    @randolf-scholz
    Contributor

    @max-muoto Regarding copy.replace in conjunction with generic types, is the following considered legal?

    import copy
    from dataclasses import dataclass
    
    @dataclass
    class Foo[T]:
        value: T
    
    foo: Foo[int] = Foo(1)
    copy.replace(foo, value="x")  # <-- mutates generic type into Foo[str]

    Or, should copy.replace only allow integer values for value in this case? This would be useful to add to the documentation as well.

    context: https://discuss.python.org/t/make-replace-stop-interfering-with-variance-inference/96092/16

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    docsDocumentation in the Doc dir

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions