Skip to content

Commit 98cc165

Browse files
authored
Fix inference for constrained type variables within unions (#14396)
Fixes #3644 Handling of constrained type variables of function `filter_satisfiable` of module `constraints` was missing (as was indicated by a removed ToDo).
1 parent 25ccdfc commit 98cc165

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

mypy/constraints.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -420,8 +420,12 @@ def filter_satisfiable(option: list[Constraint] | None) -> list[Constraint] | No
420420
return option
421421
satisfiable = []
422422
for c in option:
423-
# TODO: add similar logic for TypeVar values (also in various other places)?
424-
if mypy.subtypes.is_subtype(c.target, c.origin_type_var.upper_bound):
423+
if isinstance(c.origin_type_var, TypeVarType) and c.origin_type_var.values:
424+
if any(
425+
mypy.subtypes.is_subtype(c.target, value) for value in c.origin_type_var.values
426+
):
427+
satisfiable.append(c)
428+
elif mypy.subtypes.is_subtype(c.target, c.origin_type_var.upper_bound):
425429
satisfiable.append(c)
426430
if not satisfiable:
427431
return None

test-data/unit/check-unions.test

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1171,6 +1171,25 @@ def foo(
11711171
foo([1])
11721172
[builtins fixtures/list.pyi]
11731173

1174+
[case testGenericUnionMemberWithTypeVarConstraints]
1175+
1176+
from typing import Generic, TypeVar, Union
1177+
1178+
T = TypeVar('T', str, int)
1179+
1180+
class C(Generic[T]): ...
1181+
1182+
def f(s: Union[T, C[T]]) -> T: ...
1183+
1184+
ci: C[int]
1185+
cs: C[str]
1186+
1187+
reveal_type(f(1)) # N: Revealed type is "builtins.int"
1188+
reveal_type(f('')) # N: Revealed type is "builtins.str"
1189+
reveal_type(f(ci)) # N: Revealed type is "builtins.int"
1190+
reveal_type(f(cs)) # N: Revealed type is "builtins.str"
1191+
1192+
11741193
[case testNestedInstanceTypeAliasUnsimplifiedUnion]
11751194
from typing import TypeVar, Union, Iterator, List, Any
11761195
T = TypeVar("T")

0 commit comments

Comments
 (0)