Debian Codegraph @

test-data/unit/check-typeguard.test

raw
1 [case testTypeGuardBasic]
2 from typing_extensions import TypeGuard
3 class Point: pass
4 def is_point(a: object) -> TypeGuard[Point]: pass
5 def main(a: object) -> None:
6 if is_point(a):
7 reveal_type(a) # N: Revealed type is "__main__.Point"
8 else:
9 reveal_type(a) # N: Revealed type is "builtins.object"
10 [builtins fixtures/tuple.pyi]
11
12 [case testTypeGuardTypeArgsNone]
13 from typing_extensions import TypeGuard
14 def foo(a: object) -> TypeGuard: # E: TypeGuard must have exactly one type argument
15 pass
16 [builtins fixtures/tuple.pyi]
17
18 [case testTypeGuardTypeArgsTooMany]
19 from typing_extensions import TypeGuard
20 def foo(a: object) -> TypeGuard[int, int]: # E: TypeGuard must have exactly one type argument
21 pass
22 [builtins fixtures/tuple.pyi]
23
24 [case testTypeGuardTypeArgType]
25 from typing_extensions import TypeGuard
26 def foo(a: object) -> TypeGuard[42]: # E: Invalid type: try using Literal[42] instead?
27 pass
28 [builtins fixtures/tuple.pyi]
29
30 [case testTypeGuardRepr]
31 from typing_extensions import TypeGuard
32 def foo(a: object) -> TypeGuard[int]:
33 pass
34 reveal_type(foo) # N: Revealed type is "def (a: builtins.object) -> TypeGuard[builtins.int]"
35 [builtins fixtures/tuple.pyi]
36
37 [case testTypeGuardCallArgsNone]
38 from typing_extensions import TypeGuard
39 class Point: pass
40
41 def is_point() -> TypeGuard[Point]: pass # E: TypeGuard functions must have a positional argument
42 def main(a: object) -> None:
43 if is_point():
44 reveal_type(a) # N: Revealed type is "builtins.object"
45 [builtins fixtures/tuple.pyi]
46
47 [case testTypeGuardCallArgsMultiple]
48 from typing_extensions import TypeGuard
49 class Point: pass
50 def is_point(a: object, b: object) -> TypeGuard[Point]: pass
51 def main(a: object, b: object) -> None:
52 if is_point(a, b):
53 reveal_type(a) # N: Revealed type is "__main__.Point"
54 reveal_type(b) # N: Revealed type is "builtins.object"
55 [builtins fixtures/tuple.pyi]
56
57 [case testTypeGuardTypeVarReturn]
58 from typing import Callable, Optional, TypeVar
59 from typing_extensions import TypeGuard
60 T = TypeVar('T')
61 def is_str(x: object) -> TypeGuard[str]: pass
62 def main(x: object, type_check_func: Callable[[object], TypeGuard[T]]) -> T:
63 if not type_check_func(x):
64 raise Exception()
65 return x
66 reveal_type(main("a", is_str)) # N: Revealed type is "builtins.str"
67 [builtins fixtures/exception.pyi]
68
69 [case testTypeGuardIsBool]
70 from typing_extensions import TypeGuard
71 def f(a: TypeGuard[int]) -> None: pass
72 reveal_type(f) # N: Revealed type is "def (a: builtins.bool)"
73 a: TypeGuard[int]
74 reveal_type(a) # N: Revealed type is "builtins.bool"
75 class C:
76 a: TypeGuard[int]
77 reveal_type(C().a) # N: Revealed type is "builtins.bool"
78 [builtins fixtures/tuple.pyi]
79
80 [case testTypeGuardWithTypeVar]
81 from typing import TypeVar, Tuple
82 from typing_extensions import TypeGuard
83 T = TypeVar('T')
84 def is_two_element_tuple(a: Tuple[T, ...]) -> TypeGuard[Tuple[T, T]]: pass
85 def main(a: Tuple[T, ...]):
86 if is_two_element_tuple(a):
87 reveal_type(a) # N: Revealed type is "tuple[T`-1, T`-1]"
88 [builtins fixtures/tuple.pyi]
89
90 [case testTypeGuardPassedAsTypeVarIsBool]
91 from typing import Callable, TypeVar
92 from typing_extensions import TypeGuard
93 T = TypeVar('T')
94 def is_str(x: object) -> TypeGuard[str]: ...
95 def main(f: Callable[[object], T]) -> T: ...
96 reveal_type(main(is_str)) # N: Revealed type is "builtins.bool"
97 [builtins fixtures/tuple.pyi]
98
99 [case testTypeGuardNonOverlapping]
100 from typing import List
101 from typing_extensions import TypeGuard
102 def is_str_list(a: List[object]) -> TypeGuard[List[str]]: pass
103 def main(a: List[object]):
104 if is_str_list(a):
105 reveal_type(a) # N: Revealed type is "builtins.list[builtins.str]"
106 reveal_type(a) # N: Revealed type is "builtins.list[builtins.object]"
107 [builtins fixtures/tuple.pyi]
108
109 [case testTypeGuardUnionIn]
110 from typing import Union
111 from typing_extensions import TypeGuard
112 def is_foo(a: Union[int, str]) -> TypeGuard[str]: pass
113 def main(a: Union[str, int]) -> None:
114 if is_foo(a):
115 reveal_type(a) # N: Revealed type is "builtins.str"
116 reveal_type(a) # N: Revealed type is "builtins.str | builtins.int"
117 [builtins fixtures/tuple.pyi]
118
119 [case testTypeGuardUnionOut]
120 from typing import Union
121 from typing_extensions import TypeGuard
122 def is_foo(a: object) -> TypeGuard[Union[int, str]]: pass
123 def main(a: object) -> None:
124 if is_foo(a):
125 reveal_type(a) # N: Revealed type is "builtins.int | builtins.str"
126 [builtins fixtures/tuple.pyi]
127
128 [case testTypeGuardNonzeroFloat]
129 from typing_extensions import TypeGuard
130 def is_nonzero(a: object) -> TypeGuard[float]: pass
131 def main(a: int):
132 if is_nonzero(a):
133 reveal_type(a) # N: Revealed type is "builtins.float"
134 [builtins fixtures/tuple.pyi]
135
136 [case testTypeGuardHigherOrder]
137 from typing import Callable, TypeVar, Iterable, List
138 from typing_extensions import TypeGuard
139 T = TypeVar('T')
140 R = TypeVar('R')
141 def filter(f: Callable[[T], TypeGuard[R]], it: Iterable[T]) -> Iterable[R]: pass
142 def is_float(a: object) -> TypeGuard[float]: pass
143 a: List[object] = ["a", 0, 0.0]
144 b = filter(is_float, a)
145 reveal_type(b) # N: Revealed type is "typing.Iterable[builtins.float]"
146 [builtins fixtures/tuple.pyi]
147
148 [case testTypeGuardMethod]
149 from typing_extensions import TypeGuard
150 class C:
151 def main(self, a: object) -> None:
152 if self.is_float(a):
153 reveal_type(self) # N: Revealed type is "__main__.C"
154 reveal_type(a) # N: Revealed type is "builtins.float"
155 def is_float(self, a: object) -> TypeGuard[float]: pass
156 [builtins fixtures/tuple.pyi]
157
158 [case testTypeGuardCrossModule]
159 import guard
160 from points import Point
161 def main(a: object) -> None:
162 if guard.is_point(a):
163 reveal_type(a) # N: Revealed type is "points.Point"
164 [file guard.py]
165 from typing_extensions import TypeGuard
166 import points
167 def is_point(a: object) -> TypeGuard[points.Point]: pass
168 [file points.py]
169 class Point: pass
170 [builtins fixtures/tuple.pyi]
171
172 [case testTypeGuardBodyRequiresBool]
173 from typing_extensions import TypeGuard
174 def is_float(a: object) -> TypeGuard[float]:
175 return "not a bool" # E: Incompatible return value type (got "str", expected "bool")
176 [builtins fixtures/tuple.pyi]
177
178 [case testTypeGuardNarrowToTypedDict]
179 from typing import Dict, TypedDict
180 from typing_extensions import TypeGuard
181 class User(TypedDict):
182 name: str
183 id: int
184 def is_user(a: Dict[str, object]) -> TypeGuard[User]:
185 return isinstance(a.get("name"), str) and isinstance(a.get("id"), int)
186 def main(a: Dict[str, object]) -> None:
187 if is_user(a):
188 reveal_type(a) # N: Revealed type is "TypedDict('__main__.User', {'name': builtins.str, 'id': builtins.int})"
189 [builtins fixtures/dict.pyi]
190 [typing fixtures/typing-typeddict.pyi]
191
192 [case testTypeGuardInAssert]
193 from typing_extensions import TypeGuard
194 def is_float(a: object) -> TypeGuard[float]: pass
195 def main(a: object) -> None:
196 assert is_float(a)
197 reveal_type(a) # N: Revealed type is "builtins.float"
198 [builtins fixtures/tuple.pyi]
199
200 [case testTypeGuardFromAny]
201 from typing import Any
202 from typing_extensions import TypeGuard
203 def is_objfloat(a: object) -> TypeGuard[float]: pass
204 def is_anyfloat(a: Any) -> TypeGuard[float]: pass
205 def objmain(a: object) -> None:
206 if is_objfloat(a):
207 reveal_type(a) # N: Revealed type is "builtins.float"
208 if is_anyfloat(a):
209 reveal_type(a) # N: Revealed type is "builtins.float"
210 def anymain(a: Any) -> None:
211 if is_objfloat(a):
212 reveal_type(a) # N: Revealed type is "builtins.float"
213 if is_anyfloat(a):
214 reveal_type(a) # N: Revealed type is "builtins.float"
215 [builtins fixtures/tuple.pyi]
216
217 [case testTypeGuardNegatedAndElse]
218 from typing import Union
219 from typing_extensions import TypeGuard
220 def is_int(a: object) -> TypeGuard[int]: pass
221 def is_str(a: object) -> TypeGuard[str]: pass
222 def intmain(a: Union[int, str]) -> None:
223 if not is_int(a):
224 reveal_type(a) # N: Revealed type is "builtins.int | builtins.str"
225 else:
226 reveal_type(a) # N: Revealed type is "builtins.int"
227 def strmain(a: Union[int, str]) -> None:
228 if is_str(a):
229 reveal_type(a) # N: Revealed type is "builtins.str"
230 else:
231 reveal_type(a) # N: Revealed type is "builtins.int | builtins.str"
232 [builtins fixtures/tuple.pyi]
233
234 [case testTypeGuardClassMethod]
235 from typing_extensions import TypeGuard
236 class C:
237 @classmethod
238 def is_float(cls, a: object) -> TypeGuard[float]: pass
239 def method(self, a: object) -> None:
240 if self.is_float(a):
241 reveal_type(a) # N: Revealed type is "builtins.float"
242 def main(a: object) -> None:
243 if C.is_float(a):
244 reveal_type(a) # N: Revealed type is "builtins.float"
245 [builtins fixtures/classmethod.pyi]
246
247 [case testTypeGuardRequiresPositionalArgs]
248 from typing_extensions import TypeGuard
249 def is_float(a: object, b: object = 0) -> TypeGuard[float]: pass
250 def main1(a: object) -> None:
251 if is_float(a=a, b=1):
252 reveal_type(a) # N: Revealed type is "builtins.float"
253
254 if is_float(b=1, a=a):
255 reveal_type(a) # N: Revealed type is "builtins.float"
256
257 # This is debatable -- should we support these cases?
258
259 ta = (a,)
260 if is_float(*ta): # E: Type guard requires positional argument
261 reveal_type(ta) # N: Revealed type is "tuple[builtins.object]"
262 reveal_type(a) # N: Revealed type is "builtins.object"
263
264 la = [a]
265 if is_float(*la): # E: Type guard requires positional argument
266 reveal_type(la) # N: Revealed type is "builtins.list[builtins.object]"
267 reveal_type(a) # N: Revealed type is "builtins.object"
268
269 [builtins fixtures/tuple.pyi]
270
271 [case testTypeGuardOverload]
272 from typing import overload, Any, Callable, Iterable, Iterator, List, Optional, TypeVar
273 from typing_extensions import TypeGuard
274
275 T = TypeVar("T")
276 R = TypeVar("R")
277
278 @overload
279 def filter(f: Callable[[T], TypeGuard[R]], it: Iterable[T]) -> Iterator[R]: ...
280 @overload
281 def filter(f: Callable[[T], bool], it: Iterable[T]) -> Iterator[T]: ...
282 def filter(*args): pass
283
284 def is_int_typeguard(a: object) -> TypeGuard[int]: pass
285 def is_int_bool(a: object) -> bool: pass
286
287 def main(a: List[Optional[int]]) -> None:
288 bb = filter(lambda x: x is not None, a)
289 reveal_type(bb) # N: Revealed type is "typing.Iterator[builtins.int | None]"
290 # Also, if you replace 'bool' with 'Any' in the second overload, bb is Iterator[Any]
291 cc = filter(is_int_typeguard, a)
292 reveal_type(cc) # N: Revealed type is "typing.Iterator[builtins.int]"
293 dd = filter(is_int_bool, a)
294 reveal_type(dd) # N: Revealed type is "typing.Iterator[builtins.int | None]"
295
296 [builtins fixtures/tuple.pyi]
297 [typing fixtures/typing-full.pyi]
298
299 [case testTypeGuardDecorated]
300 from typing import TypeVar
301 from typing_extensions import TypeGuard
302 T = TypeVar("T")
303 def decorator(f: T) -> T: pass
304 @decorator
305 def is_float(a: object) -> TypeGuard[float]:
306 pass
307 def main(a: object) -> None:
308 if is_float(a):
309 reveal_type(a) # N: Revealed type is "builtins.float"
310 [builtins fixtures/tuple.pyi]
311
312 [case testTypeGuardMethodOverride]
313 from typing_extensions import TypeGuard
314 class C:
315 def is_float(self, a: object) -> TypeGuard[float]: pass
316 class D(C):
317 def is_float(self, a: object) -> bool: pass # Fail
318 [builtins fixtures/tuple.pyi]
319 [out]
320 main:5: error: Signature of "is_float" incompatible with supertype "C"
321 main:5: note: Superclass:
322 main:5: note: def is_float(self, a: object) -> TypeGuard[float]
323 main:5: note: Subclass:
324 main:5: note: def is_float(self, a: object) -> bool
325
326 [case testTypeGuardInAnd]
327 from typing import Any
328 from typing_extensions import TypeGuard
329 import types
330 def isclass(a: object) -> bool:
331 pass
332 def ismethod(a: object) -> TypeGuard[float]:
333 pass
334 def isfunction(a: object) -> TypeGuard[str]:
335 pass
336 def isclassmethod(obj: Any) -> bool:
337 if ismethod(obj) and obj.__self__ is not None and isclass(obj.__self__): # E: "float" has no attribute "__self__"
338 return True
339
340 return False
341 def coverage(obj: Any) -> bool:
342 if not (ismethod(obj) or isfunction(obj)):
343 return True
344 return False
345 [builtins fixtures/classmethod.pyi]
346
347 [case testAssignToTypeGuardedVariable1]
348 from typing_extensions import TypeGuard
349
350 class A: pass
351 class B(A): pass
352
353 def guard(a: A) -> TypeGuard[B]:
354 pass
355
356 a = A()
357 if not guard(a):
358 a = A()
359 [builtins fixtures/tuple.pyi]
360
361 [case testAssignToTypeGuardedVariable2]
362 from typing_extensions import TypeGuard
363
364 class A: pass
365 class B: pass
366
367 def guard(a: A) -> TypeGuard[B]:
368 pass
369
370 a = A()
371 if not guard(a):
372 a = A()
373 [builtins fixtures/tuple.pyi]
374
375 [case testAssignToTypeGuardedVariable3]
376 from typing_extensions import TypeGuard
377
378 class A: pass
379 class B: pass
380
381 def guard(a: A) -> TypeGuard[B]:
382 pass
383
384 a = A()
385 if guard(a):
386 reveal_type(a) # N: Revealed type is "__main__.B"
387 a = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
388 reveal_type(a) # N: Revealed type is "__main__.B"
389 a = A()
390 reveal_type(a) # N: Revealed type is "__main__.A"
391 reveal_type(a) # N: Revealed type is "__main__.A"
392 [builtins fixtures/tuple.pyi]
393
394 [case testTypeGuardNestedRestrictionAny]
395 from typing_extensions import TypeGuard
396 from typing import Any
397
398 class A: ...
399 def f(x: object) -> TypeGuard[A]: ...
400 def g(x: object) -> None: ...
401
402 def test(x: Any) -> None:
403 if not(f(x) or x):
404 return
405 g(reveal_type(x)) # N: Revealed type is "__main__.A | Any"
406 [builtins fixtures/tuple.pyi]
407
408 [case testTypeGuardNestedRestrictionUnionOther]
409 from typing_extensions import TypeGuard
410 from typing import Any
411
412 class A: ...
413 class B: ...
414 def f(x: object) -> TypeGuard[A]: ...
415 def f2(x: object) -> TypeGuard[B]: ...
416 def g(x: object) -> None: ...
417
418 def test(x: object) -> None:
419 if not(f(x) or f2(x)):
420 return
421 g(reveal_type(x)) # N: Revealed type is "__main__.A | __main__.B"
422 [builtins fixtures/tuple.pyi]
423
424 [case testTypeGuardComprehensionSubtype]
425 from typing import List
426 from typing_extensions import TypeGuard
427
428 class Base: ...
429 class Foo(Base): ...
430 class Bar(Base): ...
431
432 def is_foo(item: object) -> TypeGuard[Foo]:
433 return isinstance(item, Foo)
434
435 def is_bar(item: object) -> TypeGuard[Bar]:
436 return isinstance(item, Bar)
437
438 def foobar(items: List[object]):
439 a: List[Base] = [x for x in items if is_foo(x) or is_bar(x)]
440 b: List[Base] = [x for x in items if is_foo(x)]
441 c: List[Bar] = [x for x in items if is_foo(x)] # E: List comprehension has incompatible type List[Foo]; expected List[Bar]
442 [builtins fixtures/tuple.pyi]
443
444 [case testTypeGuardNestedRestrictionUnionIsInstance]
445 from typing_extensions import TypeGuard
446 from typing import Any, List
447
448 class A: ...
449 def f(x: List[object]) -> TypeGuard[List[str]]: ...
450 def g(x: object) -> None: ...
451
452 def test(x: List[object]) -> None:
453 if not(f(x) or isinstance(x, A)):
454 return
455 g(reveal_type(x)) # N: Revealed type is "builtins.list[builtins.str] | __main__.<subclass of "builtins.list[builtins.object]" and "__main__.A">"
456 [builtins fixtures/tuple.pyi]
457
458 [case testTypeGuardMultipleCondition-xfail]
459 from typing_extensions import TypeGuard
460 from typing import Any, List
461
462 class Foo: ...
463 class Bar: ...
464
465 def is_foo(item: object) -> TypeGuard[Foo]:
466 return isinstance(item, Foo)
467
468 def is_bar(item: object) -> TypeGuard[Bar]:
469 return isinstance(item, Bar)
470
471 def foobar(x: object):
472 if not isinstance(x, Foo) or not isinstance(x, Bar):
473 return
474 reveal_type(x) # N: Revealed type is "__main__.<subclass of "Foo" and "Bar">"
475
476 def foobar_typeguard(x: object):
477 if not is_foo(x) or not is_bar(x):
478 return
479 reveal_type(x) # N: Revealed type is "__main__.<subclass of "Foo" and "Bar">"
480 [builtins fixtures/tuple.pyi]
481
482 [case testTypeGuardAsFunctionArgAsBoolSubtype]
483 from typing import Callable
484 from typing_extensions import TypeGuard
485
486 def accepts_bool(f: Callable[[object], bool]): pass
487
488 def with_bool_typeguard(o: object) -> TypeGuard[bool]: pass
489 def with_str_typeguard(o: object) -> TypeGuard[str]: pass
490 def with_bool(o: object) -> bool: pass
491
492 accepts_bool(with_bool_typeguard)
493 accepts_bool(with_str_typeguard)
494 accepts_bool(with_bool)
495 [builtins fixtures/tuple.pyi]
496
497 [case testTypeGuardAsFunctionArg]
498 from typing import Callable
499 from typing_extensions import TypeGuard
500
501 def accepts_typeguard(f: Callable[[object], TypeGuard[bool]]): pass
502 def different_typeguard(f: Callable[[object], TypeGuard[str]]): pass
503
504 def with_typeguard(o: object) -> TypeGuard[bool]: pass
505 def with_bool(o: object) -> bool: pass
506
507 accepts_typeguard(with_typeguard)
508 accepts_typeguard(with_bool) # E: Argument 1 to "accepts_typeguard" has incompatible type "Callable[[object], bool]"; expected "Callable[[object], TypeGuard[bool]]"
509
510 different_typeguard(with_typeguard) # E: Argument 1 to "different_typeguard" has incompatible type "Callable[[object], TypeGuard[bool]]"; expected "Callable[[object], TypeGuard[str]]"
511 different_typeguard(with_bool) # E: Argument 1 to "different_typeguard" has incompatible type "Callable[[object], bool]"; expected "Callable[[object], TypeGuard[str]]"
512 [builtins fixtures/tuple.pyi]
513
514 [case testTypeGuardAsGenericFunctionArg]
515 from typing import Callable, TypeVar
516 from typing_extensions import TypeGuard
517
518 T = TypeVar('T')
519
520 def accepts_typeguard(f: Callable[[object], TypeGuard[T]]): pass
521
522 def with_bool_typeguard(o: object) -> TypeGuard[bool]: pass
523 def with_str_typeguard(o: object) -> TypeGuard[str]: pass
524 def with_bool(o: object) -> bool: pass
525
526 accepts_typeguard(with_bool_typeguard)
527 accepts_typeguard(with_str_typeguard)
528 accepts_typeguard(with_bool) # E: Argument 1 to "accepts_typeguard" has incompatible type "Callable[[object], bool]"; expected "Callable[[object], TypeGuard[Never]]"
529 [builtins fixtures/tuple.pyi]
530
531 [case testTypeGuardAsOverloadedFunctionArg]
532 # https://github.com/python/mypy/issues/11307
533 from typing import Callable, TypeVar, Generic, Any, overload
534 from typing_extensions import TypeGuard
535
536 _T = TypeVar('_T')
537
538 class filter(Generic[_T]):
539 @overload
540 def __init__(self, function: Callable[[object], TypeGuard[_T]]) -> None: pass
541 @overload
542 def __init__(self, function: Callable[[_T], Any]) -> None: pass
543 def __init__(self, function): pass
544
545 def is_int_typeguard(a: object) -> TypeGuard[int]: pass
546 def returns_bool(a: object) -> bool: pass
547
548 reveal_type(filter(is_int_typeguard)) # N: Revealed type is "__main__.filter[builtins.int]"
549 reveal_type(filter(returns_bool)) # N: Revealed type is "__main__.filter[builtins.object]"
550 [builtins fixtures/tuple.pyi]
551
552 [case testTypeGuardSubtypingVariance]
553 from typing import Callable
554 from typing_extensions import TypeGuard
555
556 class A: pass
557 class B(A): pass
558 class C(B): pass
559
560 def accepts_typeguard(f: Callable[[object], TypeGuard[B]]): pass
561
562 def with_typeguard_a(o: object) -> TypeGuard[A]: pass
563 def with_typeguard_b(o: object) -> TypeGuard[B]: pass
564 def with_typeguard_c(o: object) -> TypeGuard[C]: pass
565
566 accepts_typeguard(with_typeguard_a) # E: Argument 1 to "accepts_typeguard" has incompatible type "Callable[[object], TypeGuard[A]]"; expected "Callable[[object], TypeGuard[B]]"
567 accepts_typeguard(with_typeguard_b)
568 accepts_typeguard(with_typeguard_c)
569 [builtins fixtures/tuple.pyi]
570
571 [case testTypeGuardWithIdentityGeneric]
572 from typing import TypeVar
573 from typing_extensions import TypeGuard
574
575 _T = TypeVar("_T")
576
577 def identity(val: _T) -> TypeGuard[_T]:
578 pass
579
580 def func1(name: _T):
581 reveal_type(name) # N: Revealed type is "_T`-1"
582 if identity(name):
583 reveal_type(name) # N: Revealed type is "_T`-1"
584
585 def func2(name: str):
586 reveal_type(name) # N: Revealed type is "builtins.str"
587 if identity(name):
588 reveal_type(name) # N: Revealed type is "builtins.str"
589 [builtins fixtures/tuple.pyi]
590
591 [case testTypeGuardWithGenericInstance]
592 from typing import TypeVar, List
593 from typing_extensions import TypeGuard
594
595 _T = TypeVar("_T")
596
597 def is_list_of_str(val: _T) -> TypeGuard[List[_T]]:
598 pass
599
600 def func(name: str):
601 reveal_type(name) # N: Revealed type is "builtins.str"
602 if is_list_of_str(name):
603 reveal_type(name) # N: Revealed type is "builtins.list[builtins.str]"
604 [builtins fixtures/tuple.pyi]
605
606 [case testTypeGuardWithTupleGeneric]
607 from typing import TypeVar, Tuple
608 from typing_extensions import TypeGuard
609
610 _T = TypeVar("_T")
611
612 def is_two_element_tuple(val: Tuple[_T, ...]) -> TypeGuard[Tuple[_T, _T]]:
613 pass
614
615 def func(names: Tuple[str, ...]):
616 reveal_type(names) # N: Revealed type is "builtins.tuple[builtins.str, ...]"
617 if is_two_element_tuple(names):
618 reveal_type(names) # N: Revealed type is "tuple[builtins.str, builtins.str]"
619 [builtins fixtures/tuple.pyi]
620
621 [case testTypeGuardErroneousDefinitionFails]
622 from typing_extensions import TypeGuard
623
624 class Z:
625 def typeguard1(self, *, x: object) -> TypeGuard[int]: # line 4
626 ...
627
628 @staticmethod
629 def typeguard2(x: object) -> TypeGuard[int]:
630 ...
631
632 @staticmethod # line 11
633 def typeguard3(*, x: object) -> TypeGuard[int]:
634 ...
635
636 def bad_typeguard(*, x: object) -> TypeGuard[int]: # line 15
637 ...
638
639 # In Python 3.8 the line number associated with FunctionDef nodes changed
640 [builtins fixtures/classmethod.pyi]
641 [out]
642 main:4: error: TypeGuard functions must have a positional argument
643 main:12: error: TypeGuard functions must have a positional argument
644 main:15: error: TypeGuard functions must have a positional argument
645
646 [case testTypeGuardWithKeywordArg]
647 from typing_extensions import TypeGuard
648
649 class Z:
650 def typeguard(self, x: object) -> TypeGuard[int]:
651 ...
652
653 def typeguard(x: object) -> TypeGuard[int]:
654 ...
655
656 n: object
657 if typeguard(x=n):
658 reveal_type(n) # N: Revealed type is "builtins.int"
659
660 if Z().typeguard(x=n):
661 reveal_type(n) # N: Revealed type is "builtins.int"
662 [builtins fixtures/tuple.pyi]
663
664 [case testStaticMethodTypeGuard]
665 from typing_extensions import TypeGuard
666
667 class Y:
668 @staticmethod
669 def typeguard(h: object) -> TypeGuard[int]:
670 ...
671
672 x: object
673 if Y().typeguard(x):
674 reveal_type(x) # N: Revealed type is "builtins.int"
675 if Y.typeguard(x):
676 reveal_type(x) # N: Revealed type is "builtins.int"
677 [builtins fixtures/classmethod.pyi]
678
679 [case testTypeGuardKwargFollowingThroughOverloaded]
680 from typing import overload, Union
681 from typing_extensions import TypeGuard
682
683 @overload
684 def typeguard(x: object, y: str) -> TypeGuard[str]:
685 ...
686
687 @overload
688 def typeguard(x: object, y: int) -> TypeGuard[int]:
689 ...
690
691 def typeguard(x: object, y: Union[int, str]) -> Union[TypeGuard[int], TypeGuard[str]]:
692 ...
693
694 x: object
695 if typeguard(x=x, y=42):
696 reveal_type(x) # N: Revealed type is "builtins.int"
697
698 if typeguard(y=42, x=x):
699 reveal_type(x) # N: Revealed type is "builtins.int"
700
701 if typeguard(x=x, y="42"):
702 reveal_type(x) # N: Revealed type is "builtins.str"
703
704 if typeguard(y="42", x=x):
705 reveal_type(x) # N: Revealed type is "builtins.str"
706 [builtins fixtures/tuple.pyi]
707
708 [case testGenericAliasWithTypeGuard]
709 from typing import Callable, List, TypeVar
710 from typing_extensions import TypeGuard, TypeAlias
711
712 A = Callable[[object], TypeGuard[List[T]]]
713 def foo(x: object) -> TypeGuard[List[str]]: ...
714
715 def test(f: A[T]) -> T: ...
716 reveal_type(test(foo)) # N: Revealed type is "builtins.str"
717 [builtins fixtures/list.pyi]
718
719 [case testNoCrashOnDunderCallTypeGuard]
720 from typing_extensions import TypeGuard
721
722 class A:
723 def __call__(self, x) -> TypeGuard[int]:
724 return True
725
726 a: A
727 assert a(x=1)
728
729 x: object
730 assert a(x=x)
731 reveal_type(x) # N: Revealed type is "builtins.int"
732 [builtins fixtures/tuple.pyi]
733
734 # https://github.com/python/mypy/issues/19575
735 [case testNoCrashOnDunderCallTypeGuardTemporaryObject]
736 from typing_extensions import TypeGuard
737 class E:
738 def __init__(self) -> None: ...
739 def __call__(self, o: object) -> TypeGuard[int]:
740 return True
741 x = object()
742 if E()(x):
743 reveal_type(x) # N: Revealed type is "builtins.int"
744 [builtins fixtures/tuple.pyi]
745
746 [case testNoCrashOnDunderCallTypeIsTemporaryObject]
747 from typing_extensions import TypeIs
748 class E:
749 def __init__(self) -> None: ...
750 def __call__(self, o: object) -> TypeIs[int]:
751 return True
752 x = object()
753 if E()(x):
754 reveal_type(x) # N: Revealed type is "builtins.int"
755 [builtins fixtures/tuple.pyi]
756
757 [case testNoCrashOnDunderCallTypeIsTemporaryObjectGeneric]
758 from typing import Generic, TypeVar
759 from typing_extensions import TypeIs
760 T = TypeVar("T")
761 class E(Generic[T]):
762 def __init__(self) -> None: ...
763 def __call__(self, o: object) -> TypeIs[T]:
764 return True
765 x = object()
766 if E[int]()(x):
767 reveal_type(x) # N: Revealed type is "builtins.int"
768 [builtins fixtures/tuple.pyi]
769
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
781 [case testTypeGuardRestrictAwaySingleInvariant]
782 from typing import List
783 from typing_extensions import TypeGuard
784
785 class B: ...
786 class C(B): ...
787
788 def is_c_list(x: list[B]) -> TypeGuard[list[C]]: ...
789
790 def test() -> None:
791 x: List[B]
792 if not is_c_list(x):
793 reveal_type(x) # N: Revealed type is "builtins.list[__main__.B]"
794 return
795 reveal_type(x) # N: Revealed type is "builtins.list[__main__.C]"
796 [builtins fixtures/tuple.pyi]
797
798 [case testTypeGuardedTypeDoesNotLeak]
799 # https://github.com/python/mypy/issues/18895
800 from enum import Enum
801 from typing import Literal, Union
802 from typing_extensions import TypeGuard
803
804 class Model(str, Enum):
805 A1 = 'model_a1'
806 A2 = 'model_a2'
807 B = 'model_b'
808
809 MODEL_A = Literal[Model.A1, Model.A2]
810 MODEL_B = Literal[Model.B]
811
812 def is_model_a(model: str) -> TypeGuard[MODEL_A]:
813 return True
814
815 def is_model_b(model: str) -> TypeGuard[MODEL_B]:
816 return True
817
818 def process_model(model: Union[MODEL_A, MODEL_B]) -> int:
819 return 42
820
821 def handle(model: Model) -> int:
822 if is_model_a(model) or is_model_b(model):
823 reveal_type(model) # N: Revealed type is "__main__.Model"
824 return process_model(model)
825 return 0
826 [builtins fixtures/tuple.pyi]
827
828 [case testTypeGuardedTypeDoesNotLeakTypeVar]
829 # flags: --debug-serialize
830 # https://github.com/python/mypy/issues/20015
831 from typing import Generic, TypeVar, TypeGuard
832
833 class A: ...
834 class B: ...
835
836 def is_a(_: object) -> TypeGuard[A]: return True
837 def is_b(_: object) -> TypeGuard[B]: return True
838
839 _T = TypeVar("_T")
840
841 class Foo(Generic[_T]):
842 def __init__(self, v: _T) -> None:
843 if is_a(v) or is_b(v):
844 self.v = v
845 [builtins fixtures/tuple.pyi]
846 [typing fixtures/typing-full.pyi]
847
848 [case testTypeGuardRestrictTypeVarUnion]
849 from typing import Union, TypeVar
850 from typing_extensions import TypeGuard
851
852 class A:
853 x: int
854 class B:
855 x: str
856
857 def is_b(x: object) -> TypeGuard[B]: ...
858
859 T = TypeVar("T")
860 def test(x: T) -> T:
861 if isinstance(x, A) or is_b(x):
862 reveal_type(x.x) # N: Revealed type is "builtins.int | builtins.str"
863 return x
864 [builtins fixtures/isinstance.pyi]
865
866 [case testOverloadedTypeGuardType]
867 from __future__ import annotations
868 from typing_extensions import TypeIs, Never, overload
869
870 class X: ...
871
872 @overload # E: An overloaded function outside a stub file must have an implementation
873 def is_xlike(obj: Never) -> TypeIs[X | type[X]]: ... # type: ignore
874 @overload
875 def is_xlike(obj: type) -> TypeIs[type[X]]: ...
876 @overload
877 def is_xlike(obj: object) -> TypeIs[X | type[X]]: ...
878
879 raw_target: object
880 if isinstance(raw_target, type) and is_xlike(raw_target):
881 reveal_type(raw_target) # N: Revealed type is "type[__main__.X]"
882 [builtins fixtures/tuple.pyi]
883
884 [case testTypeGuardWithDefer]
885 from typing import Union
886 from typing_extensions import TypeGuard
887
888 class A: ...
889 class B: ...
890
891 def is_a(x: object) -> TypeGuard[A]:
892 return defer_not_defined() # E: Name "defer_not_defined" is not defined
893
894 def main(x: Union[A, B]) -> None:
895 if is_a(x):
896 reveal_type(x) # N: Revealed type is "__main__.A"
897 else:
898 reveal_type(x) # N: Revealed type is "__main__.A | __main__.B"
899 [builtins fixtures/tuple.pyi]