Skip to content
Open
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
17 changes: 12 additions & 5 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -6591,12 +6591,19 @@ def find_isinstance_check_helper(
if len(node.args) != 2: # the error will be reported elsewhere
return {}, {}
if literal(expr) == LITERAL_TYPE:
return conditional_types_to_typemaps(
expr,
*self.conditional_types_with_intersection(
self.lookup_type(expr), self.get_isinstance_type(node.args[1]), expr
),
original_type = self.lookup_type(expr)
current_type = self.expr_checker.narrow_type_from_binder(expr, original_type)
yes_type, no_type = self.conditional_types_with_intersection(
current_type, self.get_isinstance_type(node.args[1]), expr
)
if (
self.binder.get(expr) is not None
and yes_type is not None
and not isinstance(get_proper_type(current_type), AnyType)
and is_subtype(current_type, yes_type, ignore_promotions=True)
):
yes_type = current_type
return conditional_types_to_typemaps(expr, yes_type, no_type)
elif refers_to_fullname(node.callee, "builtins.issubclass"):
if len(node.args) != 2: # the error will be reported elsewhere
return {}, {}
Expand Down
9 changes: 9 additions & 0 deletions test-data/unit/check-isinstance.test
Original file line number Diff line number Diff line change
Expand Up @@ -3248,6 +3248,15 @@ def foo(x: object, t: type[Any]):
reveal_type(x) # N: Revealed type is "Any"
[builtins fixtures/isinstance.pyi]

[case testAssertIsinstanceAny]
from typing import Any

def f(x: Any) -> str:
assert isinstance(x, str)
reveal_type(x) # N: Revealed type is "builtins.str"
return x
[builtins fixtures/isinstance.pyi]

[case testIsInstanceObject]
# flags: --strict-equality --warn-unreachable
from typing import Any
Expand Down
19 changes: 19 additions & 0 deletions test-data/unit/check-typeis.test
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,25 @@ def main(a: Union[Point, Line, int]) -> None:

[builtins fixtures/tuple.pyi]

[case testTypeIsAndIsinstanceWithGenericAlias]
from typing import Any, Generic, TypeVar
from typing_extensions import TypeAlias, TypeIs

T = TypeVar("T")
class Slice(Generic[T]): pass

SliceInt: TypeAlias = Slice[int | None]
SliceStr: TypeAlias = Slice[str | None]

def is_slice_int(obj: Any) -> TypeIs[SliceInt]: pass

def main(obj: SliceInt | SliceStr) -> None:
if is_slice_int(obj):
pass
elif isinstance(obj, Slice):
reveal_type(obj) # N: Revealed type is "__main__.Slice[builtins.str | None]"
[builtins fixtures/isinstance.pyi]

[case testTypeIsTypeArgsNone]
from typing_extensions import TypeIs
def foo(a: object) -> TypeIs: # E: TypeIs must have exactly one type argument
Expand Down
Loading