Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-108751: Add copy.replace() function #108752

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

serhiy-storchaka
Copy link
Member

@serhiy-storchaka serhiy-storchaka commented Sep 1, 2023

It creates a modified copy of an object by calling the object's __replace__() method.

It is a generalization of dataclasses.replace(), named tuple's _replace() method and replace() methods in various classes, and supports all these stdlib classes.


馃摎 Documentation preview 馃摎: https://cpython-previews--108752.org.readthedocs.build/

It creates a modified copy of an object by calling the object's
__replace__() method.

It is a generalization of dataclasses.replace(), named tuple's _replace()
method and replace() methods in various classes, and supports all these
stdlib classes.
single: __replace__() (replace protocol)

Function :func:`replace` is more limited than :func:`copy` and :func:`deepcopy`,
and only supports named tuples, dataclasses, and other classes which
Copy link
Member

@merwok merwok Sep 1, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
and only supports named tuples, dataclasses, and other classes which
and only supports :term:`named tuples <named tuple>`, :mod:`dataclasses`, and other classes which

(I haven鈥檛 double checked if named tuple or namedtuple is the right key)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, it does not support named tuples in general. It currently only supports named tuples created by collections.namedtuple().

func = getattr(cls, '__replace__', None)
if func is None:
raise TypeError(f"replace() does not support {cls.__name__} objects")
return func(obj, **changes)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a cool feature for very little code!

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

Successfully merging this pull request may close these issues.

None yet

4 participants