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