Skip to content

Fix function argument inference for constrained type variables within unions (Fixes #3644). #14396

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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