diff --git a/mypy/constraints.py b/mypy/constraints.py index 8e7a30e05ffb..b1f3a8b180e1 100644 --- a/mypy/constraints.py +++ b/mypy/constraints.py @@ -416,7 +416,7 @@ def _infer_constraints( infer_constraints_if_possible(t_item, actual, direction) for t_item in template.items ], - eager=False, + eager=isinstance(actual, AnyType), ) if result: return result diff --git a/test-data/unit/check-inference.test b/test-data/unit/check-inference.test index 381f73ed9862..4ae5ddb00b18 100644 --- a/test-data/unit/check-inference.test +++ b/test-data/unit/check-inference.test @@ -4071,3 +4071,13 @@ def check_or_nested(maybe: bool) -> None: reveal_type(foo) # N: Revealed type is "builtins.list[builtins.int]" reveal_type(bar) # N: Revealed type is "builtins.list[builtins.int]" reveal_type(baz) # N: Revealed type is "builtins.list[builtins.int]" + +[case testInferOptionalAgainstAny] +from typing import Any, Optional, TypeVar + +a: Any +oa: Optional[Any] +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"