Skip to content

Narrow TypeVar to bounded TypeVar #15377

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

Closed
Closed
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/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -7396,6 +7396,11 @@ def conditional_types(
if not type_range.is_upper_bound
]
)
if isinstance(current_type, TypeVarType):
assert not current_type.values # constrained TypeVars should not reach here
proposed_type = current_type.copy_modified(
values=[], upper_bound=proposed_type, narrowed=True
)
remaining_type = restrict_subtype_away(current_type, proposed_precise_type)
return proposed_type, remaining_type
else:
Expand Down
9 changes: 7 additions & 2 deletions mypy/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -586,7 +586,7 @@ def has_default(self) -> bool:
class TypeVarType(TypeVarLikeType):
"""Type that refers to a type variable."""

__slots__ = ("values", "variance")
__slots__ = ("values", "variance", "narrowed")

values: list[Type] # Value restriction, empty list if no restriction
variance: int
Expand All @@ -602,11 +602,14 @@ def __init__(
variance: int = INVARIANT,
line: int = -1,
column: int = -1,
*,
narrowed: bool = False,
) -> None:
super().__init__(name, fullname, id, upper_bound, default, line, column)
assert values is not None, "No restrictions must be represented by empty list"
self.values = values
self.variance = variance
self.narrowed = narrowed

def copy_modified(
self,
Expand All @@ -617,6 +620,7 @@ def copy_modified(
id: Bogus[TypeVarId | int] = _dummy,
line: int = _dummy_int,
column: int = _dummy_int,
narrowed: Bogus[bool] = _dummy,
**kwargs: Any,
) -> TypeVarType:
return TypeVarType(
Expand All @@ -629,6 +633,7 @@ def copy_modified(
variance=self.variance,
line=self.line if line == _dummy_int else line,
column=self.column if column == _dummy_int else column,
narrowed=self.narrowed if narrowed is _dummy else narrowed,
)

def accept(self, visitor: TypeVisitor[T]) -> T:
Expand Down Expand Up @@ -3203,7 +3208,7 @@ def visit_type_var(self, t: TypeVarType) -> str:
else:
# Named type variable type.
s = f"{t.name}`{t.id}"
if self.id_mapper and t.upper_bound:
if (self.id_mapper or t.narrowed) and t.upper_bound:
s += f"(upper_bound={t.upper_bound.accept(self)})"
if t.has_default():
s += f" = {t.default.accept(self)}"
Expand Down
4 changes: 2 additions & 2 deletions test-data/unit/check-classes.test
Original file line number Diff line number Diff line change
Expand Up @@ -6685,11 +6685,11 @@ class C(Generic[T]):
def meth(self, cls: Type[T]) -> None:
if not issubclass(cls, Sub):
return
reveal_type(cls) # N: Revealed type is "Type[__main__.Sub]"
reveal_type(cls) # N: Revealed type is "Type[T`1(upper_bound=__main__.Sub)]"
def other(self, cls: Type[T]) -> None:
if not issubclass(cls, Sub):
return
reveal_type(cls) # N: Revealed type is "Type[__main__.Sub]"
reveal_type(cls) # N: Revealed type is "Type[T`1(upper_bound=__main__.Sub)]"

[builtins fixtures/isinstancelist.pyi]

Expand Down
26 changes: 25 additions & 1 deletion test-data/unit/check-isinstance.test
Original file line number Diff line number Diff line change
Expand Up @@ -1818,21 +1818,45 @@ if issubclass(fm, Baz):
[builtins fixtures/isinstance.pyi]

[case testIsinstanceAndNarrowTypeVariable]
# flags: --warn-unreachable
from typing import TypeVar

class A: pass
class B(A): pass
class C: pass

T = TypeVar('T', bound=A)

def f(x: T) -> None:
if isinstance(x, B):
reveal_type(x) # N: Revealed type is "__main__.B"
reveal_type(x) # N: Revealed type is "T`-1(upper_bound=__main__.B)"
x1: T = x
a: A = x
b: B = x
c: C = x # E: Incompatible types in assignment (expression has type "T", variable has type "C")
elif isinstance(x, int):
return # E: Statement is unreachable
else:
reveal_type(x) # N: Revealed type is "T`-1"
x2: T = x
reveal_type(x) # N: Revealed type is "T`-1"
[builtins fixtures/isinstance.pyi]

[case testIsinstanceAndNarrowTypeVariableIntersection-xfail]
# flags: --warn-unreachable
from typing import TypeVar

class A: pass
class B: pass

T = TypeVar('T', bound=A)

def f(x: T) -> None:
if isinstance(x, B):
reveal_type(x) # N: Revealed type is "T`-1(upper_bound=Union[__main__.A, __main__.B])"

[builtins fixtures/isinstance.pyi]

[case testIsinstanceAndTypeType]
from typing import Type
def f(x: Type[int]) -> None:
Expand Down