diff --git a/mypy/checker.py b/mypy/checker.py index 69522410e5bed..2c49ae386f8d2 100644 --- a/mypy/checker.py +++ b/mypy/checker.py @@ -3722,6 +3722,9 @@ def try_infer_partial_generic_type_from_assignment( if partial_types is None: return rvalue_type = self.expr_checker.accept(rvalue) + if var not in partial_types: + # Partial type may have been inferred while visiting rvalue (e.g. by walrus). + return rvalue_type = get_proper_type(rvalue_type) if isinstance(rvalue_type, Instance): if rvalue_type.type == typ.type and is_valid_inferred_type( @@ -5230,6 +5233,7 @@ def try_infer_partial_type_from_indexed_assignment( if ( is_valid_inferred_type(key_type, self.options) and is_valid_inferred_type(value_type, self.options) + and var in partial_types and not self.current_node_deferred and not ( typename == "collections.defaultdict" diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index a3075d52dc1fd..769e37ac97ee0 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -1177,7 +1177,10 @@ def try_infer_partial_type(self, e: CallExpr) -> None: if value_type is not None: # Infer key type. key_type = self.accept(index) - if mypy.checker.is_valid_inferred_type(key_type, self.chk.options): + if ( + mypy.checker.is_valid_inferred_type(key_type, self.chk.options) + and var in partial_types + ): # Store inferred partial type. assert partial_type.type is not None typename = partial_type.type.fullname diff --git a/test-data/unit/check-python38.test b/test-data/unit/check-python38.test index d2ede55840cfe..50daac19f81ae 100644 --- a/test-data/unit/check-python38.test +++ b/test-data/unit/check-python38.test @@ -831,3 +831,18 @@ def fn() -> tuple[int, int]: # E: Unsupported operand types for + ("None" and "int") \ # N: Left operand is of type "int | None" [builtins fixtures/dict.pyi] + +[case testPartialTypeResolvedByWalrusInAssignmentRvalueList] +errors = [] +errors = [ + i for i in [1, 2, 3] if (errors := [1]) +] +reveal_type(errors) # N: Revealed type is "builtins.list[builtins.int]" +[builtins fixtures/list.pyi] + +[case testPartialTypeResolvedByCallInAssignmentRvalueDict] +errors = {} +errors["42"] = 1 if int() else errors.update({"43": 1}) # E: Incompatible types in assignment (expression has type "int | None", target has type "int") \ + # E: "update" of "dict" does not return a value (it only ever returns None) +reveal_type(errors) # N: Revealed type is "builtins.dict[builtins.str, builtins.int]" +[builtins fixtures/dict.pyi]