diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index 88b3005b1376..fd83b6359ddc 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -6004,6 +6004,10 @@ def analyze_cond_branch( def _combined_context(self, ty: Type | None) -> Type | None: ctx_items = [] if ty is not None: + if has_any_type(ty): + # HACK: Any should be contagious, `dict[str, Any] or ` should still + # infer Any in x. + return ty ctx_items.append(ty) if self.type_context and self.type_context[-1] is not None: ctx_items.append(self.type_context[-1]) diff --git a/test-data/unit/check-inference-context.test b/test-data/unit/check-inference-context.test index 5a674cca09da..cd44fb5b85cd 100644 --- a/test-data/unit/check-inference-context.test +++ b/test-data/unit/check-inference-context.test @@ -1530,3 +1530,13 @@ def check3(use: bool, val: str) -> "str | Literal[False]": def check4(use: bool, val: str) -> "str | bool": return use and identity(val) [builtins fixtures/tuple.pyi] + +[case testDictAnyOrLiteralInContext] +from typing import Union, Optional, Any + +def f(x: dict[str, Union[str, None, int]]) -> None: + pass + +def g(x: Optional[dict[str, Any]], s: Optional[str]) -> None: + f(x or {'x': s}) +[builtins fixtures/dict.pyi]