Skip to content

Commit

Permalink
Use type variable bound to infer constraints (python#12230)
Browse files Browse the repository at this point in the history
This fixes a regression where `iter(x)` could generate a false
positive if `x` has a type variable type.
  • Loading branch information
JukkaL authored Feb 22, 2022
1 parent eca4c30 commit 65ac270
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
4 changes: 4 additions & 0 deletions mypy/constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -513,6 +513,10 @@ def visit_instance(self, template: Instance) -> List[Constraint]:
return infer_constraints(template,
mypy.typeops.tuple_fallback(actual),
self.direction)
elif isinstance(actual, TypeVarType):
if not actual.values:
return infer_constraints(template, actual.upper_bound, self.direction)
return []
else:
return []

Expand Down
21 changes: 21 additions & 0 deletions test-data/unit/check-protocols.test
Original file line number Diff line number Diff line change
Expand Up @@ -2807,6 +2807,27 @@ class MyClass:
[builtins fixtures/isinstance.pyi]
[typing fixtures/typing-full.pyi]

[case testProtocolAndTypeVariableSpecialCase]
from typing import TypeVar, Iterable, Optional, Callable, Protocol

T_co = TypeVar('T_co', covariant=True)

class SupportsNext(Protocol[T_co]):
def __next__(self) -> T_co: ...

N = TypeVar("N", bound=SupportsNext, covariant=True)

class SupportsIter(Protocol[T_co]):
def __iter__(self) -> T_co: ...

def f(i: SupportsIter[N]) -> N: ...

I = TypeVar('I', bound=Iterable)

def g(x: I, y: Iterable) -> None:
f(x)
f(y)

[case testMatchProtocolAgainstOverloadWithAmbiguity]
from typing import TypeVar, Protocol, Union, Generic, overload

Expand Down

0 comments on commit 65ac270

Please sign in to comment.