Skip to content

Commit

Permalink
Make sure dataclasses.replace actually has args to unpack.
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 595455184
  • Loading branch information
Solumin authored and rchen152 committed Jan 4, 2024
1 parent 56f876e commit e7fcd3c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
12 changes: 12 additions & 0 deletions pytype/overlays/dataclass_overlay.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,18 @@ def _match_args_sequentially(self, node, args, alias_map, match_all_views):
ret = super()._match_args_sequentially(
node, args, alias_map, match_all_views
)
if not args.posargs:
# This is a weird case where pytype thinks the call can succeed, but
# there's no concrete `__obj` in the posargs.
# This can happen when `dataclasses.replace` is called with **kwargs:
# @dataclasses.dataclass
# class A:
# replace = dataclasses.replace
# def do(self, **kwargs):
# return self.replace(**kwargs)
# (Yes, this is a simplified example of real code.)
# Since **kwargs is opaque magic, we can't do more type checking.
return ret
# _match_args_sequentially has succeeded, so we know we have 1 posarg (the
# object) and some number of named args (the new fields).
(obj,) = args.posargs
Expand Down
15 changes: 15 additions & 0 deletions pytype/tests/test_dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -1333,5 +1333,20 @@ class Z:
name: str
""")

def test_replace_as_method_with_kwargs(self):
# This is a weird case where replace is added as a method, then called
# with kwargs. This makes pytype unable to see that `self` is the object
# being modified, and also caused a crash when the dataclass overlay tries
# to unpack the object being modified from the args.
self.Check("""
import dataclasses
@dataclasses.dataclass
class WithKwargs:
replace = dataclasses.replace
def do(self, **kwargs):
return self.replace(**kwargs)
""")


if __name__ == "__main__":
test_base.main()

0 comments on commit e7fcd3c

Please sign in to comment.