Skip to content

Fix type extraction from isinstance checks #19223

New issue

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

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

Already on GitHub? # 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
10 changes: 7 additions & 3 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -7691,9 +7691,13 @@ def get_isinstance_type(self, expr: Expression) -> list[TypeRange] | None:
types: list[TypeRange] = []
for typ in all_types:
if isinstance(typ, FunctionLike) and typ.is_type_obj():
# Type variables may be present -- erase them, which is the best
# we can do (outside disallowing them here).
erased_type = erase_typevars(typ.items[0].ret_type)
# If a type is generic, `isinstance` can only narrow its variables to Any.
any_parameterized = fill_typevars_with_any(typ.type_object())
# Tuples may have unattended type variables among their items
if isinstance(any_parameterized, TupleType):
erased_type = erase_typevars(any_parameterized)
else:
erased_type = any_parameterized
types.append(TypeRange(erased_type, is_upper_bound=False))
elif isinstance(typ, TypeType):
# Type[A] means "any type that is a subtype of A" rather than "precisely type A"
Expand Down
57 changes: 57 additions & 0 deletions test-data/unit/check-narrowing.test
Original file line number Diff line number Diff line change
Expand Up @@ -2463,3 +2463,60 @@ def test(x: T) -> T:
reveal_type(x.x) # N: Revealed type is "builtins.str"
return x
[builtins fixtures/isinstance.pyi]

[case testIsinstanceNarrowingWithSelfTypes]
from typing import Generic, TypeVar, overload

T = TypeVar("T")

class A(Generic[T]):
def __init__(self: A[int]) -> None:
pass

def check_a(obj: "A[T] | str") -> None:
reveal_type(obj) # N: Revealed type is "Union[__main__.A[T`-1], builtins.str]"
if isinstance(obj, A):
reveal_type(obj) # N: Revealed type is "__main__.A[T`-1]"
else:
reveal_type(obj) # N: Revealed type is "builtins.str"


class B(Generic[T]):
@overload
def __init__(self, x: T) -> None: ...
@overload
def __init__(self: B[int]) -> None: ...
def __init__(self, x: "T | None" = None) -> None:
pass

def check_b(obj: "B[T] | str") -> None:
reveal_type(obj) # N: Revealed type is "Union[__main__.B[T`-1], builtins.str]"
if isinstance(obj, B):
reveal_type(obj) # N: Revealed type is "__main__.B[T`-1]"
else:
reveal_type(obj) # N: Revealed type is "builtins.str"


class C(Generic[T]):
@overload
def __init__(self: C[int]) -> None: ...
@overload
def __init__(self, x: T) -> None: ...
def __init__(self, x: "T | None" = None) -> None:
pass

def check_c(obj: "C[T] | str") -> None:
reveal_type(obj) # N: Revealed type is "Union[__main__.C[T`-1], builtins.str]"
if isinstance(obj, C):
reveal_type(obj) # N: Revealed type is "__main__.C[T`-1]"
else:
reveal_type(obj) # N: Revealed type is "builtins.str"


class D(tuple[T], Generic[T]): ...

def check_d(arg: D[T]) -> None:
if not isinstance(arg, D):
return
reveal_type(arg) # N: Revealed type is "tuple[T`-1, fallback=__main__.D[Any]]"
[builtins fixtures/tuple.pyi]
2 changes: 1 addition & 1 deletion test-data/unit/check-typeddict.test
Original file line number Diff line number Diff line change
Expand Up @@ -810,7 +810,7 @@ from typing import TypedDict
D = TypedDict('D', {'x': int})
d: object
if isinstance(d, D): # E: Cannot use isinstance() with TypedDict type
reveal_type(d) # N: Revealed type is "TypedDict('__main__.D', {'x': builtins.int})"
reveal_type(d) # N: Revealed type is "__main__.D"
issubclass(object, D) # E: Cannot use issubclass() with TypedDict type
[builtins fixtures/isinstancelist.pyi]
[typing fixtures/typing-typeddict.pyi]
Expand Down