From e113f0bde0953e9b77c646cf77f082568f2cfb2f Mon Sep 17 00:00:00 2001 From: Ivan Levkivskyi Date: Tue, 3 Jun 2025 16:31:35 +0100 Subject: [PATCH] Fix crash on partial type used as context --- mypy/checker.py | 4 +++- test-data/unit/check-inference.test | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/mypy/checker.py b/mypy/checker.py index e83473492f01..5201037242ac 100644 --- a/mypy/checker.py +++ b/mypy/checker.py @@ -3427,7 +3427,9 @@ def check_compatibility_all_supers(self, lvalue: RefExpr, rvalue: Expression) -> # store the rvalue type on the variable. actual_lvalue_type = None if lvalue_node.is_inferred and not lvalue_node.explicit_self_type: - rvalue_type = self.expr_checker.accept(rvalue, lvalue_node.type) + # Don't use partial types as context, similar to regular code path. + ctx = lvalue_node.type if not isinstance(lvalue_node.type, PartialType) else None + rvalue_type = self.expr_checker.accept(rvalue, ctx) actual_lvalue_type = lvalue_node.type lvalue_node.type = rvalue_type lvalue_type, _ = self.node_type_from_base(lvalue_node.name, lvalue_node.info, lvalue) diff --git a/test-data/unit/check-inference.test b/test-data/unit/check-inference.test index 4a3930533954..b563eef0f8aa 100644 --- a/test-data/unit/check-inference.test +++ b/test-data/unit/check-inference.test @@ -4128,3 +4128,24 @@ T = TypeVar("T") def f(x: Optional[T]) -> T: ... reveal_type(f(a)) # N: Revealed type is "Any" reveal_type(f(oa)) # N: Revealed type is "Any" + +[case testNoCrashOnPartialTypeAsContext] +from typing import overload, TypeVar, Optional, Protocol + +T = TypeVar("T") +class DbManager(Protocol): + @overload + def get(self, key: str) -> Optional[T]: + pass + + @overload + def get(self, key: str, default: T) -> T: + pass + +class Foo: + def __init__(self, db: DbManager, bar: bool) -> None: + if bar: + self.qux = db.get("qux") + else: + self.qux = {} # E: Need type annotation for "qux" (hint: "qux: dict[, ] = ...") +[builtins fixtures/dict.pyi]