Skip to content

[3.7] bpo-37163: dataclasses.replace() now supports the field named "obj". (GH-13877) #14405

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’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 26, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion Lib/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -1202,7 +1202,7 @@ class C(Base):
unsafe_hash=unsafe_hash, frozen=frozen)


def replace(obj, **changes):
def replace(*args, **changes):
"""Return a new object replacing specified fields with new values.

This is especially useful for frozen classes. Example usage:
Expand All @@ -1216,6 +1216,14 @@ class C:
c1 = replace(c, x=3)
assert c1.x == 3 and c1.y == 2
"""
if len(args) > 1:
raise TypeError(f'replace() takes 1 positional argument but {len(args)} were given')
if args:
obj, = args
elif 'obj' in changes:
obj = changes.pop('obj')
else:
raise TypeError("replace() missing 1 required positional argument: 'obj'")

# We're going to mutate 'changes', but that's okay because it's a
# new dict, even if called with 'replace(obj, **my_changes)'.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
:func:`dataclasses.replace` now supports the field named "obj".