Skip to content

Commit

Permalink
Fix inference for constrained type variables within unions (#14396)
Browse files Browse the repository at this point in the history
Fixes #3644

Handling of constrained type variables of function `filter_satisfiable`
of module `constraints` was missing (as was indicated by a removed
ToDo).
  • Loading branch information
tyralla committed Jan 6, 2023
1 parent 25ccdfc commit 98cc165
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
8 changes: 6 additions & 2 deletions mypy/constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -420,8 +420,12 @@ def filter_satisfiable(option: list[Constraint] | None) -> list[Constraint] | No
return option
satisfiable = []
for c in option:
# TODO: add similar logic for TypeVar values (also in various other places)?
if mypy.subtypes.is_subtype(c.target, c.origin_type_var.upper_bound):
if isinstance(c.origin_type_var, TypeVarType) and c.origin_type_var.values:
if any(
mypy.subtypes.is_subtype(c.target, value) for value in c.origin_type_var.values
):
satisfiable.append(c)
elif mypy.subtypes.is_subtype(c.target, c.origin_type_var.upper_bound):
satisfiable.append(c)
if not satisfiable:
return None
Expand Down
19 changes: 19 additions & 0 deletions test-data/unit/check-unions.test
Original file line number Diff line number Diff line change
Expand Up @@ -1171,6 +1171,25 @@ def foo(
foo([1])
[builtins fixtures/list.pyi]

[case testGenericUnionMemberWithTypeVarConstraints]

from typing import Generic, TypeVar, Union

T = TypeVar('T', str, int)

class C(Generic[T]): ...

def f(s: Union[T, C[T]]) -> T: ...

ci: C[int]
cs: C[str]

reveal_type(f(1)) # N: Revealed type is "builtins.int"
reveal_type(f('')) # N: Revealed type is "builtins.str"
reveal_type(f(ci)) # N: Revealed type is "builtins.int"
reveal_type(f(cs)) # N: Revealed type is "builtins.str"


[case testNestedInstanceTypeAliasUnsimplifiedUnion]
from typing import TypeVar, Union, Iterator, List, Any
T = TypeVar("T")
Expand Down

0 comments on commit 98cc165

Please sign in to comment.