forked from python/cpython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_typing.py
5349 lines (4351 loc) · 174 KB
/
test_typing.py
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
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import contextlib
import collections
from functools import lru_cache
import inspect
import pickle
import re
import sys
import warnings
from unittest import TestCase, main, skipUnless, skip
from copy import copy, deepcopy
from typing import Any, NoReturn
from typing import TypeVar, AnyStr
from typing import T, KT, VT # Not in __all__.
from typing import Union, Optional, Literal
from typing import Tuple, List, Dict, MutableMapping
from typing import Callable
from typing import Generic, ClassVar, Final, final, Protocol
from typing import cast, runtime_checkable
from typing import get_type_hints
from typing import get_origin, get_args
from typing import is_typeddict
from typing import reveal_type
from typing import no_type_check, no_type_check_decorator
from typing import Type
from typing import NamedTuple, TypedDict
from typing import IO, TextIO, BinaryIO
from typing import Pattern, Match
from typing import Annotated, ForwardRef
from typing import TypeAlias
from typing import ParamSpec, Concatenate, ParamSpecArgs, ParamSpecKwargs
from typing import TypeGuard
import abc
import typing
import weakref
import types
from test.support import import_helper, captured_stderr
from test import mod_generics_cache
from test import _typed_dict_helper
py_typing = import_helper.import_fresh_module('typing', blocked=['_typing'])
c_typing = import_helper.import_fresh_module('typing', fresh=['_typing'])
class BaseTestCase(TestCase):
def assertIsSubclass(self, cls, class_or_tuple, msg=None):
if not issubclass(cls, class_or_tuple):
message = '%r is not a subclass of %r' % (cls, class_or_tuple)
if msg is not None:
message += ' : %s' % msg
raise self.failureException(message)
def assertNotIsSubclass(self, cls, class_or_tuple, msg=None):
if issubclass(cls, class_or_tuple):
message = '%r is a subclass of %r' % (cls, class_or_tuple)
if msg is not None:
message += ' : %s' % msg
raise self.failureException(message)
def clear_caches(self):
for f in typing._cleanups:
f()
class Employee:
pass
class Manager(Employee):
pass
class Founder(Employee):
pass
class ManagingFounder(Manager, Founder):
pass
class AnyTests(BaseTestCase):
def test_any_instance_type_error(self):
with self.assertRaises(TypeError):
isinstance(42, Any)
def test_any_subclass_type_error(self):
with self.assertRaises(TypeError):
issubclass(Employee, Any)
with self.assertRaises(TypeError):
issubclass(Any, Employee)
def test_repr(self):
self.assertEqual(repr(Any), 'typing.Any')
def test_errors(self):
with self.assertRaises(TypeError):
issubclass(42, Any)
with self.assertRaises(TypeError):
Any[int] # Any is not a generic type.
def test_cannot_subclass(self):
with self.assertRaises(TypeError):
class A(Any):
pass
with self.assertRaises(TypeError):
class A(type(Any)):
pass
def test_cannot_instantiate(self):
with self.assertRaises(TypeError):
Any()
with self.assertRaises(TypeError):
type(Any)()
def test_any_works_with_alias(self):
# These expressions must simply not fail.
typing.Match[Any]
typing.Pattern[Any]
typing.IO[Any]
class NoReturnTests(BaseTestCase):
def test_noreturn_instance_type_error(self):
with self.assertRaises(TypeError):
isinstance(42, NoReturn)
def test_noreturn_subclass_type_error(self):
with self.assertRaises(TypeError):
issubclass(Employee, NoReturn)
with self.assertRaises(TypeError):
issubclass(NoReturn, Employee)
def test_repr(self):
self.assertEqual(repr(NoReturn), 'typing.NoReturn')
def test_not_generic(self):
with self.assertRaises(TypeError):
NoReturn[int]
def test_cannot_subclass(self):
with self.assertRaises(TypeError):
class A(NoReturn):
pass
with self.assertRaises(TypeError):
class A(type(NoReturn)):
pass
def test_cannot_instantiate(self):
with self.assertRaises(TypeError):
NoReturn()
with self.assertRaises(TypeError):
type(NoReturn)()
class TypeVarTests(BaseTestCase):
def test_basic_plain(self):
T = TypeVar('T')
# T equals itself.
self.assertEqual(T, T)
# T is an instance of TypeVar
self.assertIsInstance(T, TypeVar)
def test_typevar_instance_type_error(self):
T = TypeVar('T')
with self.assertRaises(TypeError):
isinstance(42, T)
def test_typevar_subclass_type_error(self):
T = TypeVar('T')
with self.assertRaises(TypeError):
issubclass(int, T)
with self.assertRaises(TypeError):
issubclass(T, int)
def test_constrained_error(self):
with self.assertRaises(TypeError):
X = TypeVar('X', int)
X
def test_union_unique(self):
X = TypeVar('X')
Y = TypeVar('Y')
self.assertNotEqual(X, Y)
self.assertEqual(Union[X], X)
self.assertNotEqual(Union[X], Union[X, Y])
self.assertEqual(Union[X, X], X)
self.assertNotEqual(Union[X, int], Union[X])
self.assertNotEqual(Union[X, int], Union[int])
self.assertEqual(Union[X, int].__args__, (X, int))
self.assertEqual(Union[X, int].__parameters__, (X,))
self.assertIs(Union[X, int].__origin__, Union)
def test_or(self):
X = TypeVar('X')
# use a string because str doesn't implement
# __or__/__ror__ itself
self.assertEqual(X | "x", Union[X, "x"])
self.assertEqual("x" | X, Union["x", X])
# make sure the order is correct
self.assertEqual(get_args(X | "x"), (X, ForwardRef("x")))
self.assertEqual(get_args("x" | X), (ForwardRef("x"), X))
def test_union_constrained(self):
A = TypeVar('A', str, bytes)
self.assertNotEqual(Union[A, str], Union[A])
def test_repr(self):
self.assertEqual(repr(T), '~T')
self.assertEqual(repr(KT), '~KT')
self.assertEqual(repr(VT), '~VT')
self.assertEqual(repr(AnyStr), '~AnyStr')
T_co = TypeVar('T_co', covariant=True)
self.assertEqual(repr(T_co), '+T_co')
T_contra = TypeVar('T_contra', contravariant=True)
self.assertEqual(repr(T_contra), '-T_contra')
def test_no_redefinition(self):
self.assertNotEqual(TypeVar('T'), TypeVar('T'))
self.assertNotEqual(TypeVar('T', int, str), TypeVar('T', int, str))
def test_cannot_subclass_vars(self):
with self.assertRaisesRegex(
TypeError, r"Cannot subclass an instance of TypeVar\."
):
class V(TypeVar("T")):
pass
def test_cannot_subclass_var_itself(self):
with self.assertRaises(TypeError):
class V(TypeVar):
pass
def test_cannot_instantiate_vars(self):
with self.assertRaises(TypeError):
TypeVar('A')()
def test_bound_errors(self):
with self.assertRaises(TypeError):
TypeVar('X', bound=42)
with self.assertRaises(TypeError):
TypeVar('X', str, float, bound=Employee)
def test_missing__name__(self):
# See bpo-39942
code = ("import typing\n"
"T = typing.TypeVar('T')\n"
)
exec(code, {})
def test_no_bivariant(self):
with self.assertRaises(ValueError):
TypeVar('T', covariant=True, contravariant=True)
class UnionTests(BaseTestCase):
def test_basics(self):
u = Union[int, float]
self.assertNotEqual(u, Union)
def test_subclass_error(self):
with self.assertRaises(TypeError):
issubclass(int, Union)
with self.assertRaises(TypeError):
issubclass(Union, int)
with self.assertRaises(TypeError):
issubclass(Union[int, str], int)
def test_union_any(self):
u = Union[Any]
self.assertEqual(u, Any)
u1 = Union[int, Any]
u2 = Union[Any, int]
u3 = Union[Any, object]
self.assertEqual(u1, u2)
self.assertNotEqual(u1, Any)
self.assertNotEqual(u2, Any)
self.assertNotEqual(u3, Any)
def test_union_object(self):
u = Union[object]
self.assertEqual(u, object)
u1 = Union[int, object]
u2 = Union[object, int]
self.assertEqual(u1, u2)
self.assertNotEqual(u1, object)
self.assertNotEqual(u2, object)
def test_unordered(self):
u1 = Union[int, float]
u2 = Union[float, int]
self.assertEqual(u1, u2)
def test_single_class_disappears(self):
t = Union[Employee]
self.assertIs(t, Employee)
def test_base_class_kept(self):
u = Union[Employee, Manager]
self.assertNotEqual(u, Employee)
self.assertIn(Employee, u.__args__)
self.assertIn(Manager, u.__args__)
def test_union_union(self):
u = Union[int, float]
v = Union[u, Employee]
self.assertEqual(v, Union[int, float, Employee])
def test_repr(self):
self.assertEqual(repr(Union), 'typing.Union')
u = Union[Employee, int]
self.assertEqual(repr(u), 'typing.Union[%s.Employee, int]' % __name__)
u = Union[int, Employee]
self.assertEqual(repr(u), 'typing.Union[int, %s.Employee]' % __name__)
T = TypeVar('T')
u = Union[T, int][int]
self.assertEqual(repr(u), repr(int))
u = Union[List[int], int]
self.assertEqual(repr(u), 'typing.Union[typing.List[int], int]')
u = Union[list[int], dict[str, float]]
self.assertEqual(repr(u), 'typing.Union[list[int], dict[str, float]]')
u = Union[int | float]
self.assertEqual(repr(u), 'typing.Union[int, float]')
u = Union[None, str]
self.assertEqual(repr(u), 'typing.Optional[str]')
u = Union[str, None]
self.assertEqual(repr(u), 'typing.Optional[str]')
u = Union[None, str, int]
self.assertEqual(repr(u), 'typing.Union[NoneType, str, int]')
u = Optional[str]
self.assertEqual(repr(u), 'typing.Optional[str]')
def test_cannot_subclass(self):
with self.assertRaises(TypeError):
class C(Union):
pass
with self.assertRaises(TypeError):
class C(type(Union)):
pass
with self.assertRaises(TypeError):
class C(Union[int, str]):
pass
def test_cannot_instantiate(self):
with self.assertRaises(TypeError):
Union()
with self.assertRaises(TypeError):
type(Union)()
u = Union[int, float]
with self.assertRaises(TypeError):
u()
with self.assertRaises(TypeError):
type(u)()
def test_union_generalization(self):
self.assertFalse(Union[str, typing.Iterable[int]] == str)
self.assertFalse(Union[str, typing.Iterable[int]] == typing.Iterable[int])
self.assertIn(str, Union[str, typing.Iterable[int]].__args__)
self.assertIn(typing.Iterable[int], Union[str, typing.Iterable[int]].__args__)
def test_union_compare_other(self):
self.assertNotEqual(Union, object)
self.assertNotEqual(Union, Any)
self.assertNotEqual(ClassVar, Union)
self.assertNotEqual(Optional, Union)
self.assertNotEqual([None], Optional)
self.assertNotEqual(Optional, typing.Mapping)
self.assertNotEqual(Optional[typing.MutableMapping], Union)
def test_optional(self):
o = Optional[int]
u = Union[int, None]
self.assertEqual(o, u)
def test_empty(self):
with self.assertRaises(TypeError):
Union[()]
def test_no_eval_union(self):
u = Union[int, str]
def f(x: u): ...
self.assertIs(get_type_hints(f)['x'], u)
def test_function_repr_union(self):
def fun() -> int: ...
self.assertEqual(repr(Union[fun, int]), 'typing.Union[fun, int]')
def test_union_str_pattern(self):
# Shouldn't crash; see http://bugs.python.org/issue25390
A = Union[str, Pattern]
A
def test_etree(self):
# See https://github.com/python/typing/issues/229
# (Only relevant for Python 2.)
from xml.etree.ElementTree import Element
Union[Element, str] # Shouldn't crash
def Elem(*args):
return Element(*args)
Union[Elem, str] # Nor should this
class TupleTests(BaseTestCase):
def test_basics(self):
with self.assertRaises(TypeError):
issubclass(Tuple, Tuple[int, str])
with self.assertRaises(TypeError):
issubclass(tuple, Tuple[int, str])
class TP(tuple): ...
self.assertIsSubclass(tuple, Tuple)
self.assertIsSubclass(TP, Tuple)
def test_equality(self):
self.assertEqual(Tuple[int], Tuple[int])
self.assertEqual(Tuple[int, ...], Tuple[int, ...])
self.assertNotEqual(Tuple[int], Tuple[int, int])
self.assertNotEqual(Tuple[int], Tuple[int, ...])
def test_tuple_subclass(self):
class MyTuple(tuple):
pass
self.assertIsSubclass(MyTuple, Tuple)
def test_tuple_instance_type_error(self):
with self.assertRaises(TypeError):
isinstance((0, 0), Tuple[int, int])
self.assertIsInstance((0, 0), Tuple)
def test_repr(self):
self.assertEqual(repr(Tuple), 'typing.Tuple')
self.assertEqual(repr(Tuple[()]), 'typing.Tuple[()]')
self.assertEqual(repr(Tuple[int, float]), 'typing.Tuple[int, float]')
self.assertEqual(repr(Tuple[int, ...]), 'typing.Tuple[int, ...]')
self.assertEqual(repr(Tuple[list[int]]), 'typing.Tuple[list[int]]')
def test_errors(self):
with self.assertRaises(TypeError):
issubclass(42, Tuple)
with self.assertRaises(TypeError):
issubclass(42, Tuple[int])
class BaseCallableTests:
def test_self_subclass(self):
Callable = self.Callable
with self.assertRaises(TypeError):
issubclass(types.FunctionType, Callable[[int], int])
self.assertIsSubclass(types.FunctionType, Callable)
def test_eq_hash(self):
Callable = self.Callable
C = Callable[[int], int]
self.assertEqual(C, Callable[[int], int])
self.assertEqual(len({C, Callable[[int], int]}), 1)
self.assertNotEqual(C, Callable[[int], str])
self.assertNotEqual(C, Callable[[str], int])
self.assertNotEqual(C, Callable[[int, int], int])
self.assertNotEqual(C, Callable[[], int])
self.assertNotEqual(C, Callable[..., int])
self.assertNotEqual(C, Callable)
def test_cannot_instantiate(self):
Callable = self.Callable
with self.assertRaises(TypeError):
Callable()
with self.assertRaises(TypeError):
type(Callable)()
c = Callable[[int], str]
with self.assertRaises(TypeError):
c()
with self.assertRaises(TypeError):
type(c)()
def test_callable_wrong_forms(self):
Callable = self.Callable
with self.assertRaises(TypeError):
Callable[int]
def test_callable_instance_works(self):
Callable = self.Callable
def f():
pass
self.assertIsInstance(f, Callable)
self.assertNotIsInstance(None, Callable)
def test_callable_instance_type_error(self):
Callable = self.Callable
def f():
pass
with self.assertRaises(TypeError):
self.assertIsInstance(f, Callable[[], None])
with self.assertRaises(TypeError):
self.assertIsInstance(f, Callable[[], Any])
with self.assertRaises(TypeError):
self.assertNotIsInstance(None, Callable[[], None])
with self.assertRaises(TypeError):
self.assertNotIsInstance(None, Callable[[], Any])
def test_repr(self):
Callable = self.Callable
fullname = f'{Callable.__module__}.Callable'
ct0 = Callable[[], bool]
self.assertEqual(repr(ct0), f'{fullname}[[], bool]')
ct2 = Callable[[str, float], int]
self.assertEqual(repr(ct2), f'{fullname}[[str, float], int]')
ctv = Callable[..., str]
self.assertEqual(repr(ctv), f'{fullname}[..., str]')
ct3 = Callable[[str, float], list[int]]
self.assertEqual(repr(ct3), f'{fullname}[[str, float], list[int]]')
def test_callable_with_ellipsis(self):
Callable = self.Callable
def foo(a: Callable[..., T]):
pass
self.assertEqual(get_type_hints(foo, globals(), locals()),
{'a': Callable[..., T]})
def test_ellipsis_in_generic(self):
Callable = self.Callable
# Shouldn't crash; see https://github.com/python/typing/issues/259
typing.List[Callable[..., str]]
def test_or_and_ror(self):
Callable = self.Callable
self.assertEqual(Callable | Tuple, Union[Callable, Tuple])
self.assertEqual(Tuple | Callable, Union[Tuple, Callable])
def test_basic(self):
Callable = self.Callable
alias = Callable[[int, str], float]
if Callable is collections.abc.Callable:
self.assertIsInstance(alias, types.GenericAlias)
self.assertIs(alias.__origin__, collections.abc.Callable)
self.assertEqual(alias.__args__, (int, str, float))
self.assertEqual(alias.__parameters__, ())
def test_weakref(self):
Callable = self.Callable
alias = Callable[[int, str], float]
self.assertEqual(weakref.ref(alias)(), alias)
def test_pickle(self):
Callable = self.Callable
alias = Callable[[int, str], float]
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
s = pickle.dumps(alias, proto)
loaded = pickle.loads(s)
self.assertEqual(alias.__origin__, loaded.__origin__)
self.assertEqual(alias.__args__, loaded.__args__)
self.assertEqual(alias.__parameters__, loaded.__parameters__)
def test_var_substitution(self):
Callable = self.Callable
fullname = f"{Callable.__module__}.Callable"
C1 = Callable[[int, T], T]
C2 = Callable[[KT, T], VT]
C3 = Callable[..., T]
self.assertEqual(C1[str], Callable[[int, str], str])
self.assertEqual(C2[int, float, str], Callable[[int, float], str])
self.assertEqual(C3[int], Callable[..., int])
# multi chaining
C4 = C2[int, VT, str]
self.assertEqual(repr(C4), f"{fullname}[[int, ~VT], str]")
self.assertEqual(repr(C4[dict]), f"{fullname}[[int, dict], str]")
self.assertEqual(C4[dict], Callable[[int, dict], str])
# substitute a nested GenericAlias (both typing and the builtin
# version)
C5 = Callable[[typing.List[T], tuple[KT, T], VT], int]
self.assertEqual(C5[int, str, float],
Callable[[typing.List[int], tuple[str, int], float], int])
def test_type_erasure(self):
Callable = self.Callable
class C1(Callable):
def __call__(self):
return None
a = C1[[int], T]
self.assertIs(a().__class__, C1)
self.assertEqual(a().__orig_class__, C1[[int], T])
def test_paramspec(self):
Callable = self.Callable
fullname = f"{Callable.__module__}.Callable"
P = ParamSpec('P')
P2 = ParamSpec('P2')
C1 = Callable[P, T]
# substitution
self.assertEqual(C1[[int], str], Callable[[int], str])
self.assertEqual(C1[[int, str], str], Callable[[int, str], str])
self.assertEqual(C1[[], str], Callable[[], str])
self.assertEqual(C1[..., str], Callable[..., str])
self.assertEqual(C1[P2, str], Callable[P2, str])
self.assertEqual(C1[Concatenate[int, P2], str],
Callable[Concatenate[int, P2], str])
self.assertEqual(repr(C1), f"{fullname}[~P, ~T]")
self.assertEqual(repr(C1[[int, str], str]), f"{fullname}[[int, str], str]")
with self.assertRaises(TypeError):
C1[int, str]
C2 = Callable[P, int]
self.assertEqual(C2[[int]], Callable[[int], int])
self.assertEqual(C2[[int, str]], Callable[[int, str], int])
self.assertEqual(C2[[]], Callable[[], int])
self.assertEqual(C2[...], Callable[..., int])
self.assertEqual(C2[P2], Callable[P2, int])
self.assertEqual(C2[Concatenate[int, P2]],
Callable[Concatenate[int, P2], int])
# special case in PEP 612 where
# X[int, str, float] == X[[int, str, float]]
self.assertEqual(C2[int], Callable[[int], int])
self.assertEqual(C2[int, str], Callable[[int, str], int])
self.assertEqual(repr(C2), f"{fullname}[~P, int]")
self.assertEqual(repr(C2[int, str]), f"{fullname}[[int, str], int]")
def test_concatenate(self):
Callable = self.Callable
fullname = f"{Callable.__module__}.Callable"
T = TypeVar('T')
P = ParamSpec('P')
P2 = ParamSpec('P2')
C = Callable[Concatenate[int, P], T]
self.assertEqual(repr(C),
f"{fullname}[typing.Concatenate[int, ~P], ~T]")
self.assertEqual(C[P2, int], Callable[Concatenate[int, P2], int])
self.assertEqual(C[[str, float], int], Callable[[int, str, float], int])
self.assertEqual(C[[], int], Callable[[int], int])
self.assertEqual(C[Concatenate[str, P2], int],
Callable[Concatenate[int, str, P2], int])
with self.assertRaises(TypeError):
C[..., int]
C = Callable[Concatenate[int, P], int]
self.assertEqual(repr(C),
f"{fullname}[typing.Concatenate[int, ~P], int]")
self.assertEqual(C[P2], Callable[Concatenate[int, P2], int])
self.assertEqual(C[[str, float]], Callable[[int, str, float], int])
self.assertEqual(C[str, float], Callable[[int, str, float], int])
self.assertEqual(C[[]], Callable[[int], int])
self.assertEqual(C[Concatenate[str, P2]],
Callable[Concatenate[int, str, P2], int])
with self.assertRaises(TypeError):
C[...]
def test_errors(self):
Callable = self.Callable
alias = Callable[[int, str], float]
with self.assertRaisesRegex(TypeError, "is not a generic class"):
alias[int]
P = ParamSpec('P')
C1 = Callable[P, T]
with self.assertRaisesRegex(TypeError, "many arguments for"):
C1[int, str, str]
with self.assertRaisesRegex(TypeError, "few arguments for"):
C1[int]
class TypingCallableTests(BaseCallableTests, BaseTestCase):
Callable = typing.Callable
def test_consistency(self):
# bpo-42195
# Testing collections.abc.Callable's consistency with typing.Callable
c1 = typing.Callable[[int, str], dict]
c2 = collections.abc.Callable[[int, str], dict]
self.assertEqual(c1.__args__, c2.__args__)
self.assertEqual(hash(c1.__args__), hash(c2.__args__))
class CollectionsCallableTests(BaseCallableTests, BaseTestCase):
Callable = collections.abc.Callable
class LiteralTests(BaseTestCase):
def test_basics(self):
# All of these are allowed.
Literal[1]
Literal[1, 2, 3]
Literal["x", "y", "z"]
Literal[None]
Literal[True]
Literal[1, "2", False]
Literal[Literal[1, 2], Literal[4, 5]]
Literal[b"foo", u"bar"]
def test_illegal_parameters_do_not_raise_runtime_errors(self):
# Type checkers should reject these types, but we do not
# raise errors at runtime to maintain maximum flexibility.
Literal[int]
Literal[3j + 2, ..., ()]
Literal[{"foo": 3, "bar": 4}]
Literal[T]
def test_literals_inside_other_types(self):
List[Literal[1, 2, 3]]
List[Literal[("foo", "bar", "baz")]]
def test_repr(self):
self.assertEqual(repr(Literal[1]), "typing.Literal[1]")
self.assertEqual(repr(Literal[1, True, "foo"]), "typing.Literal[1, True, 'foo']")
self.assertEqual(repr(Literal[int]), "typing.Literal[int]")
self.assertEqual(repr(Literal), "typing.Literal")
self.assertEqual(repr(Literal[None]), "typing.Literal[None]")
self.assertEqual(repr(Literal[1, 2, 3, 3]), "typing.Literal[1, 2, 3]")
def test_cannot_init(self):
with self.assertRaises(TypeError):
Literal()
with self.assertRaises(TypeError):
Literal[1]()
with self.assertRaises(TypeError):
type(Literal)()
with self.assertRaises(TypeError):
type(Literal[1])()
def test_no_isinstance_or_issubclass(self):
with self.assertRaises(TypeError):
isinstance(1, Literal[1])
with self.assertRaises(TypeError):
isinstance(int, Literal[1])
with self.assertRaises(TypeError):
issubclass(1, Literal[1])
with self.assertRaises(TypeError):
issubclass(int, Literal[1])
def test_no_subclassing(self):
with self.assertRaises(TypeError):
class Foo(Literal[1]): pass
with self.assertRaises(TypeError):
class Bar(Literal): pass
def test_no_multiple_subscripts(self):
with self.assertRaises(TypeError):
Literal[1][1]
def test_equal(self):
self.assertNotEqual(Literal[0], Literal[False])
self.assertNotEqual(Literal[True], Literal[1])
self.assertNotEqual(Literal[1], Literal[2])
self.assertNotEqual(Literal[1, True], Literal[1])
self.assertNotEqual(Literal[1, True], Literal[1, 1])
self.assertNotEqual(Literal[1, 2], Literal[True, 2])
self.assertEqual(Literal[1], Literal[1])
self.assertEqual(Literal[1, 2], Literal[2, 1])
self.assertEqual(Literal[1, 2, 3], Literal[1, 2, 3, 3])
def test_hash(self):
self.assertEqual(hash(Literal[1]), hash(Literal[1]))
self.assertEqual(hash(Literal[1, 2]), hash(Literal[2, 1]))
self.assertEqual(hash(Literal[1, 2, 3]), hash(Literal[1, 2, 3, 3]))
def test_args(self):
self.assertEqual(Literal[1, 2, 3].__args__, (1, 2, 3))
self.assertEqual(Literal[1, 2, 3, 3].__args__, (1, 2, 3))
self.assertEqual(Literal[1, Literal[2], Literal[3, 4]].__args__, (1, 2, 3, 4))
# Mutable arguments will not be deduplicated
self.assertEqual(Literal[[], []].__args__, ([], []))
def test_flatten(self):
l1 = Literal[Literal[1], Literal[2], Literal[3]]
l2 = Literal[Literal[1, 2], 3]
l3 = Literal[Literal[1, 2, 3]]
for l in l1, l2, l3:
self.assertEqual(l, Literal[1, 2, 3])
self.assertEqual(l.__args__, (1, 2, 3))
XK = TypeVar('XK', str, bytes)
XV = TypeVar('XV')
class SimpleMapping(Generic[XK, XV]):
def __getitem__(self, key: XK) -> XV:
...
def __setitem__(self, key: XK, value: XV):
...
def get(self, key: XK, default: XV = None) -> XV:
...
class MySimpleMapping(SimpleMapping[XK, XV]):
def __init__(self):
self.store = {}
def __getitem__(self, key: str):
return self.store[key]
def __setitem__(self, key: str, value):
self.store[key] = value
def get(self, key: str, default=None):
try:
return self.store[key]
except KeyError:
return default
class Coordinate(Protocol):
x: int
y: int
@runtime_checkable
class Point(Coordinate, Protocol):
label: str
class MyPoint:
x: int
y: int
label: str
class XAxis(Protocol):
x: int
class YAxis(Protocol):
y: int
@runtime_checkable
class Position(XAxis, YAxis, Protocol):
pass
@runtime_checkable
class Proto(Protocol):
attr: int
def meth(self, arg: str) -> int:
...
class Concrete(Proto):
pass
class Other:
attr: int = 1
def meth(self, arg: str) -> int:
if arg == 'this':
return 1
return 0
class NT(NamedTuple):
x: int
y: int
@runtime_checkable
class HasCallProtocol(Protocol):
__call__: typing.Callable
class ProtocolTests(BaseTestCase):
def test_basic_protocol(self):
@runtime_checkable
class P(Protocol):
def meth(self):
pass
class C: pass
class D:
def meth(self):
pass
def f():
pass
self.assertIsSubclass(D, P)
self.assertIsInstance(D(), P)
self.assertNotIsSubclass(C, P)
self.assertNotIsInstance(C(), P)
self.assertNotIsSubclass(types.FunctionType, P)
self.assertNotIsInstance(f, P)
def test_everything_implements_empty_protocol(self):
@runtime_checkable
class Empty(Protocol):
pass
class C:
pass
def f():
pass
for thing in (object, type, tuple, C, types.FunctionType):
self.assertIsSubclass(thing, Empty)
for thing in (object(), 1, (), typing, f):
self.assertIsInstance(thing, Empty)
def test_function_implements_protocol(self):
def f():
pass
self.assertIsInstance(f, HasCallProtocol)
def test_no_inheritance_from_nominal(self):
class C: pass
class BP(Protocol): pass
with self.assertRaises(TypeError):
class P(C, Protocol):
pass
with self.assertRaises(TypeError):
class P(Protocol, C):
pass
with self.assertRaises(TypeError):
class P(BP, C, Protocol):
pass
class D(BP, C): pass
class E(C, BP): pass
self.assertNotIsInstance(D(), E)
self.assertNotIsInstance(E(), D)
def test_no_instantiation(self):
class P(Protocol): pass
with self.assertRaises(TypeError):
P()
class C(P): pass
self.assertIsInstance(C(), C)
with self.assertRaises(TypeError):
C(42)
T = TypeVar('T')
class PG(Protocol[T]): pass
with self.assertRaises(TypeError):
PG()
with self.assertRaises(TypeError):
PG[int]()
with self.assertRaises(TypeError):
PG[T]()
class CG(PG[T]): pass
self.assertIsInstance(CG[int](), CG)
with self.assertRaises(TypeError):
CG[int](42)
def test_cannot_instantiate_abstract(self):
@runtime_checkable
class P(Protocol):
@abc.abstractmethod
def ameth(self) -> int:
raise NotImplementedError
class B(P):
pass
class C(B):
def ameth(self) -> int:
return 26
with self.assertRaises(TypeError):
B()
self.assertIsInstance(C(), P)
def test_subprotocols_extending(self):
class P1(Protocol):
def meth1(self):
pass
@runtime_checkable
class P2(P1, Protocol):
def meth2(self):
pass
class C:
def meth1(self):
pass
def meth2(self):
pass
class C1:
def meth1(self):
pass
class C2:
def meth2(self):