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

(cherry picked from commit f5b89af)
This commit is contained in:
Serhiy Storchaka 2019-06-26 23:03:08 +03:00 committed by GitHub
parent 814c7aefc2
commit 6ef103fbdb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 10 additions and 1 deletions

View File

@ -1202,7 +1202,7 @@ def make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True,
unsafe_hash=unsafe_hash, frozen=frozen) unsafe_hash=unsafe_hash, frozen=frozen)
def replace(obj, **changes): def replace(*args, **changes):
"""Return a new object replacing specified fields with new values. """Return a new object replacing specified fields with new values.
This is especially useful for frozen classes. Example usage: This is especially useful for frozen classes. Example usage:
@ -1216,6 +1216,14 @@ def replace(obj, **changes):
c1 = replace(c, x=3) c1 = replace(c, x=3)
assert c1.x == 3 and c1.y == 2 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 # We're going to mutate 'changes', but that's okay because it's a
# new dict, even if called with 'replace(obj, **my_changes)'. # new dict, even if called with 'replace(obj, **my_changes)'.

View File

@ -0,0 +1 @@
:func:`dataclasses.replace` now supports the field named "obj".