Skip to content

Commit

Permalink
bpo-37163: Deprecate passing argument obj of dataclasses.replace() by…
Browse files Browse the repository at this point in the history
… keyword. (GH-13877)
  • Loading branch information
serhiy-storchaka authored Jun 19, 2019
1 parent 7edf8e5 commit f5b89af
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
14 changes: 13 additions & 1 deletion Lib/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -1206,7 +1206,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 @@ -1220,6 +1220,17 @@ 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')
import warnings
warnings.warn("Passing 'obj' as keyword argument is deprecated",
DeprecationWarning, stacklevel=2)
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 Expand Up @@ -1255,3 +1266,4 @@ class C:
# changes that aren't fields, this will correctly raise a
# TypeError.
return obj.__class__(**changes)
replace.__text_signature__ = '(obj, /, **kwargs)'
7 changes: 7 additions & 0 deletions Lib/test/test_dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -3075,6 +3075,13 @@ class C:
self.assertEqual(c1.x, 3)
self.assertEqual(c1.y, 2)

self.assertRaises(TypeError, replace)
self.assertRaises(TypeError, replace, c, c)
with self.assertWarns(DeprecationWarning):
c1 = replace(obj=c, x=3)
self.assertEqual(c1.x, 3)
self.assertEqual(c1.y, 2)

def test_frozen(self):
@dataclass(frozen=True)
class C:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Deprecated passing ``obj`` argument of :func:`dataclasses.replace` as
keyword argument.

0 comments on commit f5b89af

Please sign in to comment.