From 382829dffeea82157ec00d3086868d778e1a4e92 Mon Sep 17 00:00:00 2001 From: TheMuffinMan1320 <76186189+TheMuffinMan1320@users.noreply.github.com> Date: Thu, 13 Aug 2026 14:47:43 -0500 Subject: [PATCH] Fix crash on walrus assignment shadowing partial type in comprehension (#20792) Evaluating an rvalue can itself resolve a variable's partial type as a side effect, e.g. when a walrus assignment inside a comprehension reassigns the same partial-typed name. In that case, try_infer_partial_generic_type_from_assignment would try to delete the already-removed entry from partial_types, raising a KeyError. Guard against this by checking that the var is still tracked as partial after evaluating the rvalue. Fixes #20792 --- mypy/checker.py | 4 ++++ test-data/unit/check-python38.test | 9 +++++++++ 2 files changed, 13 insertions(+) diff --git a/mypy/checker.py b/mypy/checker.py index b1c15d20c329b..a92b43ebebf9d 100644 --- a/mypy/checker.py +++ b/mypy/checker.py @@ -3710,6 +3710,10 @@ def try_infer_partial_generic_type_from_assignment( return rvalue_type = self.expr_checker.accept(rvalue) rvalue_type = get_proper_type(rvalue_type) + if var not in partial_types: + # Evaluating rvalue may have already resolved this partial type + # (e.g. a walrus assignment to the same variable inside rvalue). + return if isinstance(rvalue_type, Instance): if rvalue_type.type == typ.type and is_valid_inferred_type( rvalue_type, self.options diff --git a/test-data/unit/check-python38.test b/test-data/unit/check-python38.test index d2ede55840cfe..a83b1a7d312fb 100644 --- a/test-data/unit/check-python38.test +++ b/test-data/unit/check-python38.test @@ -455,6 +455,15 @@ def check_partial_list() -> None: reveal_type(z) # N: Revealed type is "builtins.list[builtins.int]" [builtins fixtures/list.pyi] +[case testWalrusPartialTypeShadowedInComprehension] +# https://github.com/python/mypy/issues/20792 +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 testWalrusAssignmentAndConditionScopeForLiteral] # flags: --warn-unreachable