Skip to content

Narrow TypeVars in the negative case + narrow them through upper bounds #15711

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
wants to merge 2 commits into from
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
4 changes: 4 additions & 0 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -7388,6 +7388,10 @@ def conditional_types(
# Expression is never of any type in proposed_type_ranges
return UninhabitedType(), default
else:
if isinstance(current_type, TypeVarType):
# narrowing T`-1 to int should *really* return T`-1 with a narrowed upper bound!
proposed_type = current_type.copy_modified(upper_bound=proposed_type)

# we can only restrict when the type is precise, not bounded
proposed_precise_type = UnionType.make_union(
[
Expand Down
7 changes: 6 additions & 1 deletion mypy/subtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1899,7 +1899,7 @@ def restrict_subtype_away(t: Type, s: Type) -> Type:
"""Return t minus s for runtime type assertions.

If we can't determine a precise result, return a supertype of the
ideal result (just t is a valid result).
ideal result (i.e. just t is a valid result).

This is used for type inference of runtime type checks such as
isinstance(). Currently, this just removes elements of a union type.
Expand All @@ -1914,6 +1914,11 @@ def restrict_subtype_away(t: Type, s: Type) -> Type:
if (isinstance(get_proper_type(item), AnyType) or not covers_at_runtime(item, s))
]
return UnionType.make_union(new_items)
elif isinstance(p_t, TypeVarType):
# TODO: should this check if `p_t.upper_bound` is covered at runtime?
# NOTE: I don't think I'm allowed to return proper types like this. But
# I don't know what else I could do.
return p_t.copy_modified(upper_bound=restrict_subtype_away(p_t.upper_bound, s))
elif covers_at_runtime(t, s):
return UninhabitedType()
else:
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]"
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]"

[builtins fixtures/isinstancelist.pyi]

Expand Down
22 changes: 20 additions & 2 deletions test-data/unit/check-isinstance.test
Original file line number Diff line number Diff line change
Expand Up @@ -1821,13 +1821,15 @@ if issubclass(fm, Baz):
from typing import TypeVar

class A: pass
class B(A): pass
class B(A):
z: int

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.z) # N: Revealed type is "builtins.int"
reveal_type(x) # N: Revealed type is "T`-1"
else:
reveal_type(x) # N: Revealed type is "T`-1"
reveal_type(x) # N: Revealed type is "T`-1"
Expand Down Expand Up @@ -2892,3 +2894,19 @@ if hasattr(mod, "y"):
[file mod.py]
def __getattr__(attr: str) -> str: ...
[builtins fixtures/module.pyi]

[case testFunctionCanReturnNarrowedTypeVar]
from typing import TypeVar

T = TypeVar("T")

def f(x: T) -> T:
if isinstance(x, int):
reveal_type(x) # N: Revealed type is "T`-1"
x + 42
return x
else:
reveal_type(x) # N: Revealed type is "T`-1"
x + 42 # E: Unsupported left operand type for + ("T")
return x
[builtins fixtures/isinstancelist.pyi]