Skip to content

Commit 8b16f8d

Browse files
Add comments and another test
1 parent 01dc0f4 commit 8b16f8d

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

mypy/checker.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6184,17 +6184,20 @@ def find_isinstance_check_helper(
61846184
if literal(expr) == LITERAL_TYPE and attr and len(attr) == 1:
61856185
return self.hasattr_type_maps(expr, self.lookup_type(expr), attr[0])
61866186
elif isinstance(node.callee, (RefExpr, CallExpr)):
6187+
# We support both named callables (RefExpr) and temporaries (CallExpr).
6188+
# For temporaries (e.g., E()(x)), we extract type_is/type_guard from the __call__ method.
6189+
# For named callables (e.g., is_int(x)), we extract type_is/type_guard directly from the RefExpr.
61876190
type_is, type_guard = None, None
6188-
# the first argument might be used as a kwarg
61896191
called_type = get_proper_type(self.lookup_type(node.callee))
6190-
61916192
# TODO: there are some more cases in check_call() to handle.
6193+
# If the callee is an instance, try to extract TypeGuard/TypeIs from its __call__ method.
61926194
if isinstance(called_type, Instance):
61936195
call = find_member("__call__", called_type, called_type, is_operator=True)
61946196
if call is not None:
61956197
called_type = get_proper_type(call)
61966198
if isinstance(called_type, CallableType):
61976199
type_is, type_guard = called_type.type_is, called_type.type_guard
6200+
# If the callee is a RefExpr, extract TypeGuard/TypeIs directly.
61986201
if isinstance(node.callee, RefExpr):
61996202
type_is, type_guard = node.callee.type_is, node.callee.type_guard
62006203
if type_guard is not None or type_is is not None:

test-data/unit/check-typeguard.test

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -767,6 +767,17 @@ if E[int]()(x):
767767
reveal_type(x) # N: Revealed type is "builtins.int"
768768
[builtins fixtures/tuple.pyi]
769769

770+
[case testTypeGuardTemporaryObjectWithKeywordArg]
771+
from typing_extensions import TypeGuard
772+
class E:
773+
def __init__(self) -> None: ...
774+
def __call__(self, o: object) -> TypeGuard[int]:
775+
return True
776+
x = object()
777+
if E()(o=x):
778+
reveal_type(x) # N: Revealed type is "builtins.int"
779+
[builtins fixtures/tuple.pyi]
780+
770781
[case testTypeGuardRestrictAwaySingleInvariant]
771782
from typing import List
772783
from typing_extensions import TypeGuard

0 commit comments

Comments
 (0)