Skip to content

Tweak constraint inference against unions to exclude more unsatisfiable items #7922

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 4 commits into from
Nov 11, 2019
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
5 changes: 5 additions & 0 deletions mypy/constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,11 @@ def infer_constraints_if_possible(template: Type, actual: Type,
if (direction == SUPERTYPE_OF and
not mypy.subtypes.is_subtype(actual, erase_typevars(template))):
return None
if (direction == SUPERTYPE_OF and isinstance(template, TypeVarType) and
not mypy.subtypes.is_subtype(actual, erase_typevars(template.upper_bound))):
# This is not caught by the above branch because of the erase_typevars() call,
# that would return 'Any' for a type variable.
return None
return infer_constraints(template, actual, direction)


Expand Down
36 changes: 36 additions & 0 deletions test-data/unit/check-inference.test
Original file line number Diff line number Diff line change
Expand Up @@ -2761,3 +2761,39 @@ def f() -> None:
class C:
def __init__(self, a: int) -> None:
self.a = a

[case testUnionGenericWithBoundedVariable]
from typing import Generic, TypeVar, Union

T = TypeVar('T', bound=A)
class Z(Generic[T]):
def __init__(self, y: T) -> None:
self.y = y

class A: ...
class B(A): ...
F = TypeVar('F', bound=A)

def q1(x: Union[F, Z[F]]) -> F:
if isinstance(x, Z):
return x.y
else:
return x

def q2(x: Union[Z[F], F]) -> F:
if isinstance(x, Z):
return x.y
else:
return x

b: B
reveal_type(q1(b)) # N: Revealed type is '__main__.B*'
reveal_type(q2(b)) # N: Revealed type is '__main__.B*'

z: Z[B]
reveal_type(q1(z)) # N: Revealed type is '__main__.B*'
reveal_type(q2(z)) # N: Revealed type is '__main__.B*'

reveal_type(q1(Z(b))) # N: Revealed type is '__main__.B*'
reveal_type(q2(Z(b))) # N: Revealed type is '__main__.B*'
[builtins fixtures/isinstancelist.pyi]