Debian Codegraph @

lib-python/3/test/test_typing.py

raw symbols SCIP
1 import contextlib
2 import collections
3 from collections import defaultdict
4 from functools import lru_cache, wraps, reduce
5 import inspect
6 import itertools
7 import gc
8 import operator
9 import pickle
10 import re
11 import sys
12 import warnings
13 from unittest import TestCase, main, skipUnless, skip
14 from unittest.mock import patch
15 from copy import copy, deepcopy
16
17 from typing import Any, NoReturn, Never, assert_never
18 from typing import overload, get_overloads, clear_overloads
19 from typing import TypeVar, TypeVarTuple, Unpack, AnyStr
20 from typing import T, KT, VT # Not in __all__.
21 from typing import Union, Optional, Literal
22 from typing import Tuple, List, Dict, MutableMapping
23 from typing import Callable
24 from typing import Generic, ClassVar, Final, final, Protocol
25 from typing import assert_type, cast, runtime_checkable
26 from typing import get_type_hints
27 from typing import get_origin, get_args
28 from typing import is_typeddict
29 from typing import reveal_type
30 from typing import dataclass_transform
31 from typing import no_type_check, no_type_check_decorator
32 from typing import Type
33 from typing import NamedTuple, NotRequired, Required, TypedDict
34 from typing import IO, TextIO, BinaryIO
35 from typing import Pattern, Match
36 from typing import Annotated, ForwardRef
37 from typing import Self, LiteralString
38 from typing import TypeAlias
39 from typing import ParamSpec, Concatenate, ParamSpecArgs, ParamSpecKwargs
40 from typing import TypeGuard
41 import abc
42 import textwrap
43 import typing
44 import weakref
45 import types
46
47 from test.support import import_helper, captured_stderr, cpython_only
48 from test.typinganndata import mod_generics_cache, _typed_dict_helper
49
50
51 py_typing = import_helper.import_fresh_module('typing', blocked=['_typing'])
52 c_typing = import_helper.import_fresh_module('typing', fresh=['_typing'])
53
54 CANNOT_SUBCLASS_TYPE = 'Cannot subclass special typing classes'
55
56
57 class BaseTestCase(TestCase):
58
59 def assertIsSubclass(self, cls, class_or_tuple, msg=None):
60 if not issubclass(cls, class_or_tuple):
61 message = '%r is not a subclass of %r' % (cls, class_or_tuple)
62 if msg is not None:
63 message += ' : %s' % msg
64 raise self.failureException(message)
65
66 def assertNotIsSubclass(self, cls, class_or_tuple, msg=None):
67 if issubclass(cls, class_or_tuple):
68 message = '%r is a subclass of %r' % (cls, class_or_tuple)
69 if msg is not None:
70 message += ' : %s' % msg
71 raise self.failureException(message)
72
73 def clear_caches(self):
74 for f in typing._cleanups:
75 f()
76
77
78 def all_pickle_protocols(test_func):
79 """Runs `test_func` with various values for `proto` argument."""
80
81 @wraps(test_func)
82 def wrapper(self):
83 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
84 with self.subTest(pickle_proto=proto):
85 test_func(self, proto=proto)
86
87 return wrapper
88
89
90 class Employee:
91 pass
92
93
94 class Manager(Employee):
95 pass
96
97
98 class Founder(Employee):
99 pass
100
101
102 class ManagingFounder(Manager, Founder):
103 pass
104
105
106 class AnyTests(BaseTestCase):
107
108 def test_any_instance_type_error(self):
109 with self.assertRaises(TypeError):
110 isinstance(42, Any)
111
112 def test_repr(self):
113 self.assertEqual(repr(Any), 'typing.Any')
114
115 class Sub(Any): pass
116 self.assertEqual(
117 repr(Sub),
118 f"<class '{__name__}.AnyTests.test_repr.<locals>.Sub'>",
119 )
120
121 def test_errors(self):
122 with self.assertRaises(TypeError):
123 issubclass(42, Any)
124 with self.assertRaises(TypeError):
125 Any[int] # Any is not a generic type.
126
127 def test_can_subclass(self):
128 class Mock(Any): pass
129 self.assertTrue(issubclass(Mock, Any))
130 self.assertIsInstance(Mock(), Mock)
131
132 class Something: pass
133 self.assertFalse(issubclass(Something, Any))
134 self.assertNotIsInstance(Something(), Mock)
135
136 class MockSomething(Something, Mock): pass
137 self.assertTrue(issubclass(MockSomething, Any))
138 ms = MockSomething()
139 self.assertIsInstance(ms, MockSomething)
140 self.assertIsInstance(ms, Something)
141 self.assertIsInstance(ms, Mock)
142
143 def test_subclassing_with_custom_constructor(self):
144 class Sub(Any):
145 def __init__(self, *args, **kwargs): pass
146 # The instantiation must not fail.
147 Sub(0, s="")
148
149 def test_multiple_inheritance_with_custom_constructors(self):
150 class Foo:
151 def __init__(self, x):
152 self.x = x
153
154 class Bar(Any, Foo):
155 def __init__(self, x, y):
156 self.y = y
157 super().__init__(x)
158
159 b = Bar(1, 2)
160 self.assertEqual(b.x, 1)
161 self.assertEqual(b.y, 2)
162
163 def test_cannot_instantiate(self):
164 with self.assertRaises(TypeError):
165 Any()
166 with self.assertRaises(TypeError):
167 type(Any)()
168
169 def test_any_works_with_alias(self):
170 # These expressions must simply not fail.
171 typing.Match[Any]
172 typing.Pattern[Any]
173 typing.IO[Any]
174
175
176 class BottomTypeTestsMixin:
177 bottom_type: ClassVar[Any]
178
179 def test_equality(self):
180 self.assertEqual(self.bottom_type, self.bottom_type)
181 self.assertIs(self.bottom_type, self.bottom_type)
182 self.assertNotEqual(self.bottom_type, None)
183
184 def test_get_origin(self):
185 self.assertIs(get_origin(self.bottom_type), None)
186
187 def test_instance_type_error(self):
188 with self.assertRaises(TypeError):
189 isinstance(42, self.bottom_type)
190
191 def test_subclass_type_error(self):
192 with self.assertRaises(TypeError):
193 issubclass(Employee, self.bottom_type)
194 with self.assertRaises(TypeError):
195 issubclass(NoReturn, self.bottom_type)
196
197 def test_not_generic(self):
198 with self.assertRaises(TypeError):
199 self.bottom_type[int]
200
201 def test_cannot_subclass(self):
202 with self.assertRaises(TypeError):
203 class A(self.bottom_type):
204 pass
205 with self.assertRaises(TypeError):
206 class B(type(self.bottom_type)):
207 pass
208
209 def test_cannot_instantiate(self):
210 with self.assertRaises(TypeError):
211 self.bottom_type()
212 with self.assertRaises(TypeError):
213 type(self.bottom_type)()
214
215
216 class NoReturnTests(BottomTypeTestsMixin, BaseTestCase):
217 bottom_type = NoReturn
218
219 def test_repr(self):
220 self.assertEqual(repr(NoReturn), 'typing.NoReturn')
221
222 def test_get_type_hints(self):
223 def some(arg: NoReturn) -> NoReturn: ...
224 def some_str(arg: 'NoReturn') -> 'typing.NoReturn': ...
225
226 expected = {'arg': NoReturn, 'return': NoReturn}
227 for target in [some, some_str]:
228 with self.subTest(target=target):
229 self.assertEqual(gth(target), expected)
230
231 def test_not_equality(self):
232 self.assertNotEqual(NoReturn, Never)
233 self.assertNotEqual(Never, NoReturn)
234
235
236 class NeverTests(BottomTypeTestsMixin, BaseTestCase):
237 bottom_type = Never
238
239 def test_repr(self):
240 self.assertEqual(repr(Never), 'typing.Never')
241
242 def test_get_type_hints(self):
243 def some(arg: Never) -> Never: ...
244 def some_str(arg: 'Never') -> 'typing.Never': ...
245
246 expected = {'arg': Never, 'return': Never}
247 for target in [some, some_str]:
248 with self.subTest(target=target):
249 self.assertEqual(gth(target), expected)
250
251
252 class AssertNeverTests(BaseTestCase):
253 def test_exception(self):
254 with self.assertRaises(AssertionError):
255 assert_never(None)
256
257 value = "some value"
258 with self.assertRaisesRegex(AssertionError, value):
259 assert_never(value)
260
261 # Make sure a huge value doesn't get printed in its entirety
262 huge_value = "a" * 10000
263 with self.assertRaises(AssertionError) as cm:
264 assert_never(huge_value)
265 self.assertLess(
266 len(cm.exception.args[0]),
267 typing._ASSERT_NEVER_REPR_MAX_LENGTH * 2,
268 )
269
270
271 class SelfTests(BaseTestCase):
272 def test_equality(self):
273 self.assertEqual(Self, Self)
274 self.assertIs(Self, Self)
275 self.assertNotEqual(Self, None)
276
277 def test_basics(self):
278 class Foo:
279 def bar(self) -> Self: ...
280 class FooStr:
281 def bar(self) -> 'Self': ...
282 class FooStrTyping:
283 def bar(self) -> 'typing.Self': ...
284
285 for target in [Foo, FooStr, FooStrTyping]:
286 with self.subTest(target=target):
287 self.assertEqual(gth(target.bar), {'return': Self})
288 self.assertIs(get_origin(Self), None)
289
290 def test_repr(self):
291 self.assertEqual(repr(Self), 'typing.Self')
292
293 def test_cannot_subscript(self):
294 with self.assertRaises(TypeError):
295 Self[int]
296
297 def test_cannot_subclass(self):
298 with self.assertRaises(TypeError):
299 class C(type(Self)):
300 pass
301 with self.assertRaises(TypeError):
302 class D(Self):
303 pass
304
305 def test_cannot_init(self):
306 with self.assertRaises(TypeError):
307 Self()
308 with self.assertRaises(TypeError):
309 type(Self)()
310
311 def test_no_isinstance(self):
312 with self.assertRaises(TypeError):
313 isinstance(1, Self)
314 with self.assertRaises(TypeError):
315 issubclass(int, Self)
316
317 def test_alias(self):
318 # TypeAliases are not actually part of the spec
319 alias_1 = Tuple[Self, Self]
320 alias_2 = List[Self]
321 alias_3 = ClassVar[Self]
322 self.assertEqual(get_args(alias_1), (Self, Self))
323 self.assertEqual(get_args(alias_2), (Self,))
324 self.assertEqual(get_args(alias_3), (Self,))
325
326
327 class LiteralStringTests(BaseTestCase):
328 def test_equality(self):
329 self.assertEqual(LiteralString, LiteralString)
330 self.assertIs(LiteralString, LiteralString)
331 self.assertNotEqual(LiteralString, None)
332
333 def test_basics(self):
334 class Foo:
335 def bar(self) -> LiteralString: ...
336 class FooStr:
337 def bar(self) -> 'LiteralString': ...
338 class FooStrTyping:
339 def bar(self) -> 'typing.LiteralString': ...
340
341 for target in [Foo, FooStr, FooStrTyping]:
342 with self.subTest(target=target):
343 self.assertEqual(gth(target.bar), {'return': LiteralString})
344 self.assertIs(get_origin(LiteralString), None)
345
346 def test_repr(self):
347 self.assertEqual(repr(LiteralString), 'typing.LiteralString')
348
349 def test_cannot_subscript(self):
350 with self.assertRaises(TypeError):
351 LiteralString[int]
352
353 def test_cannot_subclass(self):
354 with self.assertRaises(TypeError):
355 class C(type(LiteralString)):
356 pass
357 with self.assertRaises(TypeError):
358 class D(LiteralString):
359 pass
360
361 def test_cannot_init(self):
362 with self.assertRaises(TypeError):
363 LiteralString()
364 with self.assertRaises(TypeError):
365 type(LiteralString)()
366
367 def test_no_isinstance(self):
368 with self.assertRaises(TypeError):
369 isinstance(1, LiteralString)
370 with self.assertRaises(TypeError):
371 issubclass(int, LiteralString)
372
373 def test_alias(self):
374 alias_1 = Tuple[LiteralString, LiteralString]
375 alias_2 = List[LiteralString]
376 alias_3 = ClassVar[LiteralString]
377 self.assertEqual(get_args(alias_1), (LiteralString, LiteralString))
378 self.assertEqual(get_args(alias_2), (LiteralString,))
379 self.assertEqual(get_args(alias_3), (LiteralString,))
380
381 class TypeVarTests(BaseTestCase):
382 def test_basic_plain(self):
383 T = TypeVar('T')
384 # T equals itself.
385 self.assertEqual(T, T)
386 # T is an instance of TypeVar
387 self.assertIsInstance(T, TypeVar)
388 self.assertEqual(T.__name__, 'T')
389 self.assertEqual(T.__constraints__, ())
390 self.assertIs(T.__bound__, None)
391 self.assertIs(T.__covariant__, False)
392 self.assertIs(T.__contravariant__, False)
393
394 def test_attributes(self):
395 T_bound = TypeVar('T_bound', bound=int)
396 self.assertEqual(T_bound.__name__, 'T_bound')
397 self.assertEqual(T_bound.__constraints__, ())
398 self.assertIs(T_bound.__bound__, int)
399
400 T_constraints = TypeVar('T_constraints', int, str)
401 self.assertEqual(T_constraints.__name__, 'T_constraints')
402 self.assertEqual(T_constraints.__constraints__, (int, str))
403 self.assertIs(T_constraints.__bound__, None)
404
405 T_co = TypeVar('T_co', covariant=True)
406 self.assertEqual(T_co.__name__, 'T_co')
407 self.assertIs(T_co.__covariant__, True)
408 self.assertIs(T_co.__contravariant__, False)
409
410 T_contra = TypeVar('T_contra', contravariant=True)
411 self.assertEqual(T_contra.__name__, 'T_contra')
412 self.assertIs(T_contra.__covariant__, False)
413 self.assertIs(T_contra.__contravariant__, True)
414
415 def test_typevar_instance_type_error(self):
416 T = TypeVar('T')
417 with self.assertRaises(TypeError):
418 isinstance(42, T)
419
420 def test_typevar_subclass_type_error(self):
421 T = TypeVar('T')
422 with self.assertRaises(TypeError):
423 issubclass(int, T)
424 with self.assertRaises(TypeError):
425 issubclass(T, int)
426
427 def test_constrained_error(self):
428 with self.assertRaises(TypeError):
429 X = TypeVar('X', int)
430 X
431
432 def test_union_unique(self):
433 X = TypeVar('X')
434 Y = TypeVar('Y')
435 self.assertNotEqual(X, Y)
436 self.assertEqual(Union[X], X)
437 self.assertNotEqual(Union[X], Union[X, Y])
438 self.assertEqual(Union[X, X], X)
439 self.assertNotEqual(Union[X, int], Union[X])
440 self.assertNotEqual(Union[X, int], Union[int])
441 self.assertEqual(Union[X, int].__args__, (X, int))
442 self.assertEqual(Union[X, int].__parameters__, (X,))
443 self.assertIs(Union[X, int].__origin__, Union)
444
445 def test_or(self):
446 X = TypeVar('X')
447 # use a string because str doesn't implement
448 # __or__/__ror__ itself
449 self.assertEqual(X | "x", Union[X, "x"])
450 self.assertEqual("x" | X, Union["x", X])
451 # make sure the order is correct
452 self.assertEqual(get_args(X | "x"), (X, ForwardRef("x")))
453 self.assertEqual(get_args("x" | X), (ForwardRef("x"), X))
454
455 def test_union_constrained(self):
456 A = TypeVar('A', str, bytes)
457 self.assertNotEqual(Union[A, str], Union[A])
458
459 def test_repr(self):
460 self.assertEqual(repr(T), '~T')
461 self.assertEqual(repr(KT), '~KT')
462 self.assertEqual(repr(VT), '~VT')
463 self.assertEqual(repr(AnyStr), '~AnyStr')
464 T_co = TypeVar('T_co', covariant=True)
465 self.assertEqual(repr(T_co), '+T_co')
466 T_contra = TypeVar('T_contra', contravariant=True)
467 self.assertEqual(repr(T_contra), '-T_contra')
468
469 def test_no_redefinition(self):
470 self.assertNotEqual(TypeVar('T'), TypeVar('T'))
471 self.assertNotEqual(TypeVar('T', int, str), TypeVar('T', int, str))
472
473 def test_cannot_subclass_vars(self):
474 with self.assertRaises(TypeError):
475 class V(TypeVar('T')):
476 pass
477
478 def test_cannot_subclass_var_itself(self):
479 with self.assertRaises(TypeError):
480 class W(TypeVar):
481 pass
482
483 def test_cannot_instantiate_vars(self):
484 with self.assertRaises(TypeError):
485 TypeVar('A')()
486
487 def test_bound_errors(self):
488 with self.assertRaises(TypeError):
489 TypeVar('X', bound=Union)
490 with self.assertRaises(TypeError):
491 TypeVar('X', str, float, bound=Employee)
492
493 def test_missing__name__(self):
494 # See bpo-39942
495 code = ("import typing\n"
496 "T = typing.TypeVar('T')\n"
497 )
498 exec(code, {})
499
500 def test_no_bivariant(self):
501 with self.assertRaises(ValueError):
502 TypeVar('T', covariant=True, contravariant=True)
503
504 def test_var_substitution(self):
505 T = TypeVar('T')
506 subst = T.__typing_subst__
507 self.assertIs(subst(int), int)
508 self.assertEqual(subst(list[int]), list[int])
509 self.assertEqual(subst(List[int]), List[int])
510 self.assertEqual(subst(List), List)
511 self.assertIs(subst(Any), Any)
512 self.assertIs(subst(None), type(None))
513 self.assertIs(subst(T), T)
514 self.assertEqual(subst(int|str), int|str)
515 self.assertEqual(subst(Union[int, str]), Union[int, str])
516
517 def test_bad_var_substitution(self):
518 T = TypeVar('T')
519 bad_args = (
520 (), (int, str), Union,
521 Generic, Generic[T], Protocol, Protocol[T],
522 Final, Final[int], ClassVar, ClassVar[int],
523 )
524 for arg in bad_args:
525 with self.subTest(arg=arg):
526 with self.assertRaises(TypeError):
527 T.__typing_subst__(arg)
528 with self.assertRaises(TypeError):
529 List[T][arg]
530 with self.assertRaises(TypeError):
531 list[T][arg]
532
533
534 def template_replace(templates: list[str], replacements: dict[str, list[str]]) -> list[tuple[str]]:
535 """Renders templates with possible combinations of replacements.
536
537 Example 1: Suppose that:
538 templates = ["dog_breed are awesome", "dog_breed are cool"]
539 replacements = ["dog_breed": ["Huskies", "Beagles"]]
540 Then we would return:
541 [
542 ("Huskies are awesome", "Huskies are cool"),
543 ("Beagles are awesome", "Beagles are cool")
544 ]
545
546 Example 2: Suppose that:
547 templates = ["Huskies are word1 but also word2"]
548 replacements = {"word1": ["playful", "cute"],
549 "word2": ["feisty", "tiring"]}
550 Then we would return:
551 [
552 ("Huskies are playful but also feisty"),
553 ("Huskies are playful but also tiring"),
554 ("Huskies are cute but also feisty"),
555 ("Huskies are cute but also tiring")
556 ]
557
558 Note that if any of the replacements do not occur in any template:
559 templates = ["Huskies are word1", "Beagles!"]
560 replacements = {"word1": ["playful", "cute"],
561 "word2": ["feisty", "tiring"]}
562 Then we do not generate duplicates, returning:
563 [
564 ("Huskies are playful", "Beagles!"),
565 ("Huskies are cute", "Beagles!")
566 ]
567 """
568 # First, build a structure like:
569 # [
570 # [("word1", "playful"), ("word1", "cute")],
571 # [("word2", "feisty"), ("word2", "tiring")]
572 # ]
573 replacement_combos = []
574 for original, possible_replacements in replacements.items():
575 original_replacement_tuples = []
576 for replacement in possible_replacements:
577 original_replacement_tuples.append((original, replacement))
578 replacement_combos.append(original_replacement_tuples)
579
580 # Second, generate rendered templates, including possible duplicates.
581 rendered_templates = []
582 for replacement_combo in itertools.product(*replacement_combos):
583 # replacement_combo would be e.g.
584 # [("word1", "playful"), ("word2", "feisty")]
585 templates_with_replacements = []
586 for template in templates:
587 for original, replacement in replacement_combo:
588 template = template.replace(original, replacement)
589 templates_with_replacements.append(template)
590 rendered_templates.append(tuple(templates_with_replacements))
591
592 # Finally, remove the duplicates (but keep the order).
593 rendered_templates_no_duplicates = []
594 for x in rendered_templates:
595 # Inefficient, but should be fine for our purposes.
596 if x not in rendered_templates_no_duplicates:
597 rendered_templates_no_duplicates.append(x)
598
599 return rendered_templates_no_duplicates
600
601
602 class TemplateReplacementTests(BaseTestCase):
603
604 def test_two_templates_two_replacements_yields_correct_renders(self):
605 actual = template_replace(
606 templates=["Cats are word1", "Dogs are word2"],
607 replacements={
608 "word1": ["small", "cute"],
609 "word2": ["big", "fluffy"],
610 },
611 )
612 expected = [
613 ("Cats are small", "Dogs are big"),
614 ("Cats are small", "Dogs are fluffy"),
615 ("Cats are cute", "Dogs are big"),
616 ("Cats are cute", "Dogs are fluffy"),
617 ]
618 self.assertEqual(actual, expected)
619
620 def test_no_duplicates_if_replacement_not_in_templates(self):
621 actual = template_replace(
622 templates=["Cats are word1", "Dogs!"],
623 replacements={
624 "word1": ["small", "cute"],
625 "word2": ["big", "fluffy"],
626 },
627 )
628 expected = [
629 ("Cats are small", "Dogs!"),
630 ("Cats are cute", "Dogs!"),
631 ]
632 self.assertEqual(actual, expected)
633
634
635 class GenericAliasSubstitutionTests(BaseTestCase):
636 """Tests for type variable substitution in generic aliases.
637
638 For variadic cases, these tests should be regarded as the source of truth,
639 since we hadn't realised the full complexity of variadic substitution
640 at the time of finalizing PEP 646. For full discussion, see
641 https://github.com/python/cpython/issues/91162.
642 """
643
644 def test_one_parameter(self):
645 T = TypeVar('T')
646 Ts = TypeVarTuple('Ts')
647 Ts2 = TypeVarTuple('Ts2')
648
649 class C(Generic[T]): pass
650
651 generics = ['C', 'list', 'List']
652 tuple_types = ['tuple', 'Tuple']
653
654 tests = [
655 # Alias # Args # Expected result
656 ('generic[T]', '[()]', 'TypeError'),
657 ('generic[T]', '[int]', 'generic[int]'),
658 ('generic[T]', '[int, str]', 'TypeError'),
659 ('generic[T]', '[tuple_type[int, ...]]', 'generic[tuple_type[int, ...]]'),
660 ('generic[T]', '[*tuple_type[int]]', 'generic[int]'),
661 ('generic[T]', '[*tuple_type[()]]', 'TypeError'),
662 ('generic[T]', '[*tuple_type[int, str]]', 'TypeError'),
663 ('generic[T]', '[*tuple_type[int, ...]]', 'TypeError'),
664 ('generic[T]', '[*Ts]', 'TypeError'),
665 ('generic[T]', '[T, *Ts]', 'TypeError'),
666 ('generic[T]', '[*Ts, T]', 'TypeError'),
667 # Raises TypeError because C is not variadic.
668 # (If C _were_ variadic, it'd be fine.)
669 ('C[T, *tuple_type[int, ...]]', '[int]', 'TypeError'),
670 # Should definitely raise TypeError: list only takes one argument.
671 ('list[T, *tuple_type[int, ...]]', '[int]', 'list[int, *tuple_type[int, ...]]'),
672 ('List[T, *tuple_type[int, ...]]', '[int]', 'TypeError'),
673 # Should raise, because more than one `TypeVarTuple` is not supported.
674 ('generic[*Ts, *Ts2]', '[int]', 'TypeError'),
675 ]
676
677 for alias_template, args_template, expected_template in tests:
678 rendered_templates = template_replace(
679 templates=[alias_template, args_template, expected_template],
680 replacements={'generic': generics, 'tuple_type': tuple_types}
681 )
682 for alias_str, args_str, expected_str in rendered_templates:
683 with self.subTest(alias=alias_str, args=args_str, expected=expected_str):
684 if expected_str == 'TypeError':
685 with self.assertRaises(TypeError):
686 eval(alias_str + args_str)
687 else:
688 self.assertEqual(
689 eval(alias_str + args_str),
690 eval(expected_str)
691 )
692
693
694 def test_two_parameters(self):
695 T1 = TypeVar('T1')
696 T2 = TypeVar('T2')
697 Ts = TypeVarTuple('Ts')
698
699 class C(Generic[T1, T2]): pass
700
701 generics = ['C', 'dict', 'Dict']
702 tuple_types = ['tuple', 'Tuple']
703
704 tests = [
705 # Alias # Args # Expected result
706 ('generic[T1, T2]', '[()]', 'TypeError'),
707 ('generic[T1, T2]', '[int]', 'TypeError'),
708 ('generic[T1, T2]', '[int, str]', 'generic[int, str]'),
709 ('generic[T1, T2]', '[int, str, bool]', 'TypeError'),
710 ('generic[T1, T2]', '[*tuple_type[int]]', 'TypeError'),
711 ('generic[T1, T2]', '[*tuple_type[int, str]]', 'generic[int, str]'),
712 ('generic[T1, T2]', '[*tuple_type[int, str, bool]]', 'TypeError'),
713
714 ('generic[T1, T2]', '[int, *tuple_type[str]]', 'generic[int, str]'),
715 ('generic[T1, T2]', '[*tuple_type[int], str]', 'generic[int, str]'),
716 ('generic[T1, T2]', '[*tuple_type[int], *tuple_type[str]]', 'generic[int, str]'),
717 ('generic[T1, T2]', '[*tuple_type[int, str], *tuple_type[()]]', 'generic[int, str]'),
718 ('generic[T1, T2]', '[*tuple_type[()], *tuple_type[int, str]]', 'generic[int, str]'),
719 ('generic[T1, T2]', '[*tuple_type[int], *tuple_type[()]]', 'TypeError'),
720 ('generic[T1, T2]', '[*tuple_type[()], *tuple_type[int]]', 'TypeError'),
721 ('generic[T1, T2]', '[*tuple_type[int, str], *tuple_type[float]]', 'TypeError'),
722 ('generic[T1, T2]', '[*tuple_type[int], *tuple_type[str, float]]', 'TypeError'),
723 ('generic[T1, T2]', '[*tuple_type[int, str], *tuple_type[float, bool]]', 'TypeError'),
724
725 ('generic[T1, T2]', '[tuple_type[int, ...]]', 'TypeError'),
726 ('generic[T1, T2]', '[tuple_type[int, ...], tuple_type[str, ...]]', 'generic[tuple_type[int, ...], tuple_type[str, ...]]'),
727 ('generic[T1, T2]', '[*tuple_type[int, ...]]', 'TypeError'),
728 ('generic[T1, T2]', '[int, *tuple_type[str, ...]]', 'TypeError'),
729 ('generic[T1, T2]', '[*tuple_type[int, ...], str]', 'TypeError'),
730 ('generic[T1, T2]', '[*tuple_type[int, ...], *tuple_type[str, ...]]', 'TypeError'),
731 ('generic[T1, T2]', '[*Ts]', 'TypeError'),
732 ('generic[T1, T2]', '[T, *Ts]', 'TypeError'),
733 ('generic[T1, T2]', '[*Ts, T]', 'TypeError'),
734 # This one isn't technically valid - none of the things that
735 # `generic` can be (defined in `generics` above) are variadic, so we
736 # shouldn't really be able to do `generic[T1, *tuple_type[int, ...]]`.
737 # So even if type checkers shouldn't allow it, we allow it at
738 # runtime, in accordance with a general philosophy of "Keep the
739 # runtime lenient so people can experiment with typing constructs".
740 ('generic[T1, *tuple_type[int, ...]]', '[str]', 'generic[str, *tuple_type[int, ...]]'),
741 ]
742
743 for alias_template, args_template, expected_template in tests:
744 rendered_templates = template_replace(
745 templates=[alias_template, args_template, expected_template],
746 replacements={'generic': generics, 'tuple_type': tuple_types}
747 )
748 for alias_str, args_str, expected_str in rendered_templates:
749 with self.subTest(alias=alias_str, args=args_str, expected=expected_str):
750 if expected_str == 'TypeError':
751 with self.assertRaises(TypeError):
752 eval(alias_str + args_str)
753 else:
754 self.assertEqual(
755 eval(alias_str + args_str),
756 eval(expected_str)
757 )
758
759 def test_three_parameters(self):
760 T1 = TypeVar('T1')
761 T2 = TypeVar('T2')
762 T3 = TypeVar('T3')
763
764 class C(Generic[T1, T2, T3]): pass
765
766 generics = ['C']
767 tuple_types = ['tuple', 'Tuple']
768
769 tests = [
770 # Alias # Args # Expected result
771 ('generic[T1, bool, T2]', '[int, str]', 'generic[int, bool, str]'),
772 ('generic[T1, bool, T2]', '[*tuple_type[int, str]]', 'generic[int, bool, str]'),
773 ]
774
775 for alias_template, args_template, expected_template in tests:
776 rendered_templates = template_replace(
777 templates=[alias_template, args_template, expected_template],
778 replacements={'generic': generics, 'tuple_type': tuple_types}
779 )
780 for alias_str, args_str, expected_str in rendered_templates:
781 with self.subTest(alias=alias_str, args=args_str, expected=expected_str):
782 if expected_str == 'TypeError':
783 with self.assertRaises(TypeError):
784 eval(alias_str + args_str)
785 else:
786 self.assertEqual(
787 eval(alias_str + args_str),
788 eval(expected_str)
789 )
790
791 def test_variadic_parameters(self):
792 T1 = TypeVar('T1')
793 T2 = TypeVar('T2')
794 Ts = TypeVarTuple('Ts')
795
796 class C(Generic[*Ts]): pass
797
798 generics = ['C', 'tuple', 'Tuple']
799 tuple_types = ['tuple', 'Tuple']
800
801 tests = [
802 # Alias # Args # Expected result
803 ('generic[*Ts]', '[()]', 'generic[()]'),
804 ('generic[*Ts]', '[int]', 'generic[int]'),
805 ('generic[*Ts]', '[int, str]', 'generic[int, str]'),
806 ('generic[*Ts]', '[*tuple_type[int]]', 'generic[int]'),
807 ('generic[*Ts]', '[*tuple_type[*Ts]]', 'generic[*Ts]'),
808 ('generic[*Ts]', '[*tuple_type[int, str]]', 'generic[int, str]'),
809 ('generic[*Ts]', '[str, *tuple_type[int, ...], bool]', 'generic[str, *tuple_type[int, ...], bool]'),
810 ('generic[*Ts]', '[tuple_type[int, ...]]', 'generic[tuple_type[int, ...]]'),
811 ('generic[*Ts]', '[tuple_type[int, ...], tuple_type[str, ...]]', 'generic[tuple_type[int, ...], tuple_type[str, ...]]'),
812 ('generic[*Ts]', '[*tuple_type[int, ...]]', 'generic[*tuple_type[int, ...]]'),
813 ('generic[*Ts]', '[*tuple_type[int, ...], *tuple_type[str, ...]]', 'TypeError'),
814
815 ('generic[*Ts]', '[*Ts]', 'generic[*Ts]'),
816 ('generic[*Ts]', '[T, *Ts]', 'generic[T, *Ts]'),
817 ('generic[*Ts]', '[*Ts, T]', 'generic[*Ts, T]'),
818 ('generic[T, *Ts]', '[()]', 'TypeError'),
819 ('generic[T, *Ts]', '[int]', 'generic[int]'),
820 ('generic[T, *Ts]', '[int, str]', 'generic[int, str]'),
821 ('generic[T, *Ts]', '[int, str, bool]', 'generic[int, str, bool]'),
822 ('generic[list[T], *Ts]', '[()]', 'TypeError'),
823 ('generic[list[T], *Ts]', '[int]', 'generic[list[int]]'),
824 ('generic[list[T], *Ts]', '[int, str]', 'generic[list[int], str]'),
825 ('generic[list[T], *Ts]', '[int, str, bool]', 'generic[list[int], str, bool]'),
826
827 ('generic[*Ts, T]', '[()]', 'TypeError'),
828 ('generic[*Ts, T]', '[int]', 'generic[int]'),
829 ('generic[*Ts, T]', '[int, str]', 'generic[int, str]'),
830 ('generic[*Ts, T]', '[int, str, bool]', 'generic[int, str, bool]'),
831 ('generic[*Ts, list[T]]', '[()]', 'TypeError'),
832 ('generic[*Ts, list[T]]', '[int]', 'generic[list[int]]'),
833 ('generic[*Ts, list[T]]', '[int, str]', 'generic[int, list[str]]'),
834 ('generic[*Ts, list[T]]', '[int, str, bool]', 'generic[int, str, list[bool]]'),
835
836 ('generic[T1, T2, *Ts]', '[()]', 'TypeError'),
837 ('generic[T1, T2, *Ts]', '[int]', 'TypeError'),
838 ('generic[T1, T2, *Ts]', '[int, str]', 'generic[int, str]'),
839 ('generic[T1, T2, *Ts]', '[int, str, bool]', 'generic[int, str, bool]'),
840 ('generic[T1, T2, *Ts]', '[int, str, bool, bytes]', 'generic[int, str, bool, bytes]'),
841
842 ('generic[*Ts, T1, T2]', '[()]', 'TypeError'),
843 ('generic[*Ts, T1, T2]', '[int]', 'TypeError'),
844 ('generic[*Ts, T1, T2]', '[int, str]', 'generic[int, str]'),
845 ('generic[*Ts, T1, T2]', '[int, str, bool]', 'generic[int, str, bool]'),
846 ('generic[*Ts, T1, T2]', '[int, str, bool, bytes]', 'generic[int, str, bool, bytes]'),
847
848 ('generic[T1, *Ts, T2]', '[()]', 'TypeError'),
849 ('generic[T1, *Ts, T2]', '[int]', 'TypeError'),
850 ('generic[T1, *Ts, T2]', '[int, str]', 'generic[int, str]'),
851 ('generic[T1, *Ts, T2]', '[int, str, bool]', 'generic[int, str, bool]'),
852 ('generic[T1, *Ts, T2]', '[int, str, bool, bytes]', 'generic[int, str, bool, bytes]'),
853
854 ('generic[T, *Ts]', '[*tuple_type[int, ...]]', 'generic[int, *tuple_type[int, ...]]'),
855 ('generic[T, *Ts]', '[str, *tuple_type[int, ...]]', 'generic[str, *tuple_type[int, ...]]'),
856 ('generic[T, *Ts]', '[*tuple_type[int, ...], str]', 'generic[int, *tuple_type[int, ...], str]'),
857 ('generic[*Ts, T]', '[*tuple_type[int, ...]]', 'generic[*tuple_type[int, ...], int]'),
858 ('generic[*Ts, T]', '[str, *tuple_type[int, ...]]', 'generic[str, *tuple_type[int, ...], int]'),
859 ('generic[*Ts, T]', '[*tuple_type[int, ...], str]', 'generic[*tuple_type[int, ...], str]'),
860 ('generic[T1, *Ts, T2]', '[*tuple_type[int, ...]]', 'generic[int, *tuple_type[int, ...], int]'),
861 ('generic[T, str, *Ts]', '[*tuple_type[int, ...]]', 'generic[int, str, *tuple_type[int, ...]]'),
862 ('generic[*Ts, str, T]', '[*tuple_type[int, ...]]', 'generic[*tuple_type[int, ...], str, int]'),
863 ('generic[list[T], *Ts]', '[*tuple_type[int, ...]]', 'generic[list[int], *tuple_type[int, ...]]'),
864 ('generic[*Ts, list[T]]', '[*tuple_type[int, ...]]', 'generic[*tuple_type[int, ...], list[int]]'),
865
866 ('generic[T, *tuple_type[int, ...]]', '[str]', 'generic[str, *tuple_type[int, ...]]'),
867 ('generic[T1, T2, *tuple_type[int, ...]]', '[str, bool]', 'generic[str, bool, *tuple_type[int, ...]]'),
868 ('generic[T1, *tuple_type[int, ...], T2]', '[str, bool]', 'generic[str, *tuple_type[int, ...], bool]'),
869 ('generic[T1, *tuple_type[int, ...], T2]', '[str, bool, float]', 'TypeError'),
870
871 ('generic[T1, *tuple_type[T2, ...]]', '[int, str]', 'generic[int, *tuple_type[str, ...]]'),
872 ('generic[*tuple_type[T1, ...], T2]', '[int, str]', 'generic[*tuple_type[int, ...], str]'),
873 ('generic[T1, *tuple_type[generic[*Ts], ...]]', '[int, str, bool]', 'generic[int, *tuple_type[generic[str, bool], ...]]'),
874 ('generic[*tuple_type[generic[*Ts], ...], T1]', '[int, str, bool]', 'generic[*tuple_type[generic[int, str], ...], bool]'),
875 ]
876
877 for alias_template, args_template, expected_template in tests:
878 rendered_templates = template_replace(
879 templates=[alias_template, args_template, expected_template],
880 replacements={'generic': generics, 'tuple_type': tuple_types}
881 )
882 for alias_str, args_str, expected_str in rendered_templates:
883 with self.subTest(alias=alias_str, args=args_str, expected=expected_str):
884 if expected_str == 'TypeError':
885 with self.assertRaises(TypeError):
886 eval(alias_str + args_str)
887 else:
888 self.assertEqual(
889 eval(alias_str + args_str),
890 eval(expected_str)
891 )
892
893
894
895 class UnpackTests(BaseTestCase):
896
897 def test_accepts_single_type(self):
898 (*tuple[int],)
899 Unpack[Tuple[int]]
900
901 def test_dir(self):
902 dir_items = set(dir(Unpack[Tuple[int]]))
903 for required_item in [
904 '__args__', '__parameters__', '__origin__',
905 ]:
906 with self.subTest(required_item=required_item):
907 self.assertIn(required_item, dir_items)
908
909 def test_rejects_multiple_types(self):
910 with self.assertRaises(TypeError):
911 Unpack[Tuple[int], Tuple[str]]
912 # We can't do the equivalent for `*` here -
913 # *(Tuple[int], Tuple[str]) is just plain tuple unpacking,
914 # which is valid.
915
916 def test_rejects_multiple_parameterization(self):
917 with self.assertRaises(TypeError):
918 (*tuple[int],)[0][tuple[int]]
919 with self.assertRaises(TypeError):
920 Unpack[Tuple[int]][Tuple[int]]
921
922 def test_cannot_be_called(self):
923 with self.assertRaises(TypeError):
924 Unpack()
925
926
927 class TypeVarTupleTests(BaseTestCase):
928
929 def assertEndsWith(self, string, tail):
930 if not string.endswith(tail):
931 self.fail(f"String {string!r} does not end with {tail!r}")
932
933 def test_name(self):
934 Ts = TypeVarTuple('Ts')
935 self.assertEqual(Ts.__name__, 'Ts')
936 Ts2 = TypeVarTuple('Ts2')
937 self.assertEqual(Ts2.__name__, 'Ts2')
938
939 def test_instance_is_equal_to_itself(self):
940 Ts = TypeVarTuple('Ts')
941 self.assertEqual(Ts, Ts)
942
943 def test_different_instances_are_different(self):
944 self.assertNotEqual(TypeVarTuple('Ts'), TypeVarTuple('Ts'))
945
946 def test_instance_isinstance_of_typevartuple(self):
947 Ts = TypeVarTuple('Ts')
948 self.assertIsInstance(Ts, TypeVarTuple)
949
950 def test_cannot_call_instance(self):
951 Ts = TypeVarTuple('Ts')
952 with self.assertRaises(TypeError):
953 Ts()
954
955 def test_unpacked_typevartuple_is_equal_to_itself(self):
956 Ts = TypeVarTuple('Ts')
957 self.assertEqual((*Ts,)[0], (*Ts,)[0])
958 self.assertEqual(Unpack[Ts], Unpack[Ts])
959
960 def test_parameterised_tuple_is_equal_to_itself(self):
961 Ts = TypeVarTuple('Ts')
962 self.assertEqual(tuple[*Ts], tuple[*Ts])
963 self.assertEqual(Tuple[Unpack[Ts]], Tuple[Unpack[Ts]])
964
965 def tests_tuple_arg_ordering_matters(self):
966 Ts1 = TypeVarTuple('Ts1')
967 Ts2 = TypeVarTuple('Ts2')
968 self.assertNotEqual(
969 tuple[*Ts1, *Ts2],
970 tuple[*Ts2, *Ts1],
971 )
972 self.assertNotEqual(
973 Tuple[Unpack[Ts1], Unpack[Ts2]],
974 Tuple[Unpack[Ts2], Unpack[Ts1]],
975 )
976
977 def test_tuple_args_and_parameters_are_correct(self):
978 Ts = TypeVarTuple('Ts')
979 t1 = tuple[*Ts]
980 self.assertEqual(t1.__args__, (*Ts,))
981 self.assertEqual(t1.__parameters__, (Ts,))
982 t2 = Tuple[Unpack[Ts]]
983 self.assertEqual(t2.__args__, (Unpack[Ts],))
984 self.assertEqual(t2.__parameters__, (Ts,))
985
986 def test_var_substitution(self):
987 Ts = TypeVarTuple('Ts')
988 T = TypeVar('T')
989 T2 = TypeVar('T2')
990 class G1(Generic[*Ts]): pass
991 class G2(Generic[Unpack[Ts]]): pass
992
993 for A in G1, G2, Tuple, tuple:
994 B = A[*Ts]
995 self.assertEqual(B[()], A[()])
996 self.assertEqual(B[float], A[float])
997 self.assertEqual(B[float, str], A[float, str])
998
999 C = A[Unpack[Ts]]
1000 self.assertEqual(C[()], A[()])
1001 self.assertEqual(C[float], A[float])
1002 self.assertEqual(C[float, str], A[float, str])
1003
1004 D = list[A[*Ts]]
1005 self.assertEqual(D[()], list[A[()]])
1006 self.assertEqual(D[float], list[A[float]])
1007 self.assertEqual(D[float, str], list[A[float, str]])
1008
1009 E = List[A[Unpack[Ts]]]
1010 self.assertEqual(E[()], List[A[()]])
1011 self.assertEqual(E[float], List[A[float]])
1012 self.assertEqual(E[float, str], List[A[float, str]])
1013
1014 F = A[T, *Ts, T2]
1015 with self.assertRaises(TypeError):
1016 F[()]
1017 with self.assertRaises(TypeError):
1018 F[float]
1019 self.assertEqual(F[float, str], A[float, str])
1020 self.assertEqual(F[float, str, int], A[float, str, int])
1021 self.assertEqual(F[float, str, int, bytes], A[float, str, int, bytes])
1022
1023 G = A[T, Unpack[Ts], T2]
1024 with self.assertRaises(TypeError):
1025 G[()]
1026 with self.assertRaises(TypeError):
1027 G[float]
1028 self.assertEqual(G[float, str], A[float, str])
1029 self.assertEqual(G[float, str, int], A[float, str, int])
1030 self.assertEqual(G[float, str, int, bytes], A[float, str, int, bytes])
1031
1032 H = tuple[list[T], A[*Ts], list[T2]]
1033 with self.assertRaises(TypeError):
1034 H[()]
1035 with self.assertRaises(TypeError):
1036 H[float]
1037 if A != Tuple:
1038 self.assertEqual(H[float, str],
1039 tuple[list[float], A[()], list[str]])
1040 self.assertEqual(H[float, str, int],
1041 tuple[list[float], A[str], list[int]])
1042 self.assertEqual(H[float, str, int, bytes],
1043 tuple[list[float], A[str, int], list[bytes]])
1044
1045 I = Tuple[List[T], A[Unpack[Ts]], List[T2]]
1046 with self.assertRaises(TypeError):
1047 I[()]
1048 with self.assertRaises(TypeError):
1049 I[float]
1050 if A != Tuple:
1051 self.assertEqual(I[float, str],
1052 Tuple[List[float], A[()], List[str]])
1053 self.assertEqual(I[float, str, int],
1054 Tuple[List[float], A[str], List[int]])
1055 self.assertEqual(I[float, str, int, bytes],
1056 Tuple[List[float], A[str, int], List[bytes]])
1057
1058 def test_bad_var_substitution(self):
1059 Ts = TypeVarTuple('Ts')
1060 T = TypeVar('T')
1061 T2 = TypeVar('T2')
1062 class G1(Generic[*Ts]): pass
1063 class G2(Generic[Unpack[Ts]]): pass
1064
1065 for A in G1, G2, Tuple, tuple:
1066 B = A[Ts]
1067 with self.assertRaises(TypeError):
1068 B[int, str]
1069
1070 C = A[T, T2]
1071 with self.assertRaises(TypeError):
1072 C[*Ts]
1073 with self.assertRaises(TypeError):
1074 C[Unpack[Ts]]
1075
1076 B = A[T, *Ts, str, T2]
1077 with self.assertRaises(TypeError):
1078 B[int, *Ts]
1079 with self.assertRaises(TypeError):
1080 B[int, *Ts, *Ts]
1081
1082 C = A[T, Unpack[Ts], str, T2]
1083 with self.assertRaises(TypeError):
1084 C[int, Unpack[Ts]]
1085 with self.assertRaises(TypeError):
1086 C[int, Unpack[Ts], Unpack[Ts]]
1087
1088 def test_repr_is_correct(self):
1089 Ts = TypeVarTuple('Ts')
1090
1091 class G1(Generic[*Ts]): pass
1092 class G2(Generic[Unpack[Ts]]): pass
1093
1094 self.assertEqual(repr(Ts), 'Ts')
1095
1096 self.assertEqual(repr((*Ts,)[0]), '*Ts')
1097 self.assertEqual(repr(Unpack[Ts]), '*Ts')
1098
1099 self.assertEqual(repr(tuple[*Ts]), 'tuple[*Ts]')
1100 self.assertEqual(repr(Tuple[Unpack[Ts]]), 'typing.Tuple[*Ts]')
1101
1102 self.assertEqual(repr(*tuple[*Ts]), '*tuple[*Ts]')
1103 self.assertEqual(repr(Unpack[Tuple[Unpack[Ts]]]), '*typing.Tuple[*Ts]')
1104
1105 def test_variadic_class_repr_is_correct(self):
1106 Ts = TypeVarTuple('Ts')
1107 class A(Generic[*Ts]): pass
1108 class B(Generic[Unpack[Ts]]): pass
1109
1110 self.assertEndsWith(repr(A[()]), 'A[()]')
1111 self.assertEndsWith(repr(B[()]), 'B[()]')
1112 self.assertEndsWith(repr(A[float]), 'A[float]')
1113 self.assertEndsWith(repr(B[float]), 'B[float]')
1114 self.assertEndsWith(repr(A[float, str]), 'A[float, str]')
1115 self.assertEndsWith(repr(B[float, str]), 'B[float, str]')
1116
1117 self.assertEndsWith(repr(A[*tuple[int, ...]]),
1118 'A[*tuple[int, ...]]')
1119 self.assertEndsWith(repr(B[Unpack[Tuple[int, ...]]]),
1120 'B[*typing.Tuple[int, ...]]')
1121
1122 self.assertEndsWith(repr(A[float, *tuple[int, ...]]),
1123 'A[float, *tuple[int, ...]]')
1124 self.assertEndsWith(repr(A[float, Unpack[Tuple[int, ...]]]),
1125 'A[float, *typing.Tuple[int, ...]]')
1126
1127 self.assertEndsWith(repr(A[*tuple[int, ...], str]),
1128 'A[*tuple[int, ...], str]')
1129 self.assertEndsWith(repr(B[Unpack[Tuple[int, ...]], str]),
1130 'B[*typing.Tuple[int, ...], str]')
1131
1132 self.assertEndsWith(repr(A[float, *tuple[int, ...], str]),
1133 'A[float, *tuple[int, ...], str]')
1134 self.assertEndsWith(repr(B[float, Unpack[Tuple[int, ...]], str]),
1135 'B[float, *typing.Tuple[int, ...], str]')
1136
1137 def test_variadic_class_alias_repr_is_correct(self):
1138 Ts = TypeVarTuple('Ts')
1139 class A(Generic[Unpack[Ts]]): pass
1140
1141 B = A[*Ts]
1142 self.assertEndsWith(repr(B), 'A[*Ts]')
1143 self.assertEndsWith(repr(B[()]), 'A[()]')
1144 self.assertEndsWith(repr(B[float]), 'A[float]')
1145 self.assertEndsWith(repr(B[float, str]), 'A[float, str]')
1146
1147 C = A[Unpack[Ts]]
1148 self.assertEndsWith(repr(C), 'A[*Ts]')
1149 self.assertEndsWith(repr(C[()]), 'A[()]')
1150 self.assertEndsWith(repr(C[float]), 'A[float]')
1151 self.assertEndsWith(repr(C[float, str]), 'A[float, str]')
1152
1153 D = A[*Ts, int]
1154 self.assertEndsWith(repr(D), 'A[*Ts, int]')
1155 self.assertEndsWith(repr(D[()]), 'A[int]')
1156 self.assertEndsWith(repr(D[float]), 'A[float, int]')
1157 self.assertEndsWith(repr(D[float, str]), 'A[float, str, int]')
1158
1159 E = A[Unpack[Ts], int]
1160 self.assertEndsWith(repr(E), 'A[*Ts, int]')
1161 self.assertEndsWith(repr(E[()]), 'A[int]')
1162 self.assertEndsWith(repr(E[float]), 'A[float, int]')
1163 self.assertEndsWith(repr(E[float, str]), 'A[float, str, int]')
1164
1165 F = A[int, *Ts]
1166 self.assertEndsWith(repr(F), 'A[int, *Ts]')
1167 self.assertEndsWith(repr(F[()]), 'A[int]')
1168 self.assertEndsWith(repr(F[float]), 'A[int, float]')
1169 self.assertEndsWith(repr(F[float, str]), 'A[int, float, str]')
1170
1171 G = A[int, Unpack[Ts]]
1172 self.assertEndsWith(repr(G), 'A[int, *Ts]')
1173 self.assertEndsWith(repr(G[()]), 'A[int]')
1174 self.assertEndsWith(repr(G[float]), 'A[int, float]')
1175 self.assertEndsWith(repr(G[float, str]), 'A[int, float, str]')
1176
1177 H = A[int, *Ts, str]
1178 self.assertEndsWith(repr(H), 'A[int, *Ts, str]')
1179 self.assertEndsWith(repr(H[()]), 'A[int, str]')
1180 self.assertEndsWith(repr(H[float]), 'A[int, float, str]')
1181 self.assertEndsWith(repr(H[float, str]), 'A[int, float, str, str]')
1182
1183 I = A[int, Unpack[Ts], str]
1184 self.assertEndsWith(repr(I), 'A[int, *Ts, str]')
1185 self.assertEndsWith(repr(I[()]), 'A[int, str]')
1186 self.assertEndsWith(repr(I[float]), 'A[int, float, str]')
1187 self.assertEndsWith(repr(I[float, str]), 'A[int, float, str, str]')
1188
1189 J = A[*Ts, *tuple[str, ...]]
1190 self.assertEndsWith(repr(J), 'A[*Ts, *tuple[str, ...]]')
1191 self.assertEndsWith(repr(J[()]), 'A[*tuple[str, ...]]')
1192 self.assertEndsWith(repr(J[float]), 'A[float, *tuple[str, ...]]')
1193 self.assertEndsWith(repr(J[float, str]), 'A[float, str, *tuple[str, ...]]')
1194
1195 K = A[Unpack[Ts], Unpack[Tuple[str, ...]]]
1196 self.assertEndsWith(repr(K), 'A[*Ts, *typing.Tuple[str, ...]]')
1197 self.assertEndsWith(repr(K[()]), 'A[*typing.Tuple[str, ...]]')
1198 self.assertEndsWith(repr(K[float]), 'A[float, *typing.Tuple[str, ...]]')
1199 self.assertEndsWith(repr(K[float, str]), 'A[float, str, *typing.Tuple[str, ...]]')
1200
1201 def test_cannot_subclass_class(self):
1202 with self.assertRaises(TypeError):
1203 class C(TypeVarTuple): pass
1204
1205 def test_cannot_subclass_instance(self):
1206 Ts = TypeVarTuple('Ts')
1207 with self.assertRaises(TypeError):
1208 class D(Ts): pass
1209 with self.assertRaisesRegex(TypeError, CANNOT_SUBCLASS_TYPE):
1210 class E(type(Unpack)): pass
1211 with self.assertRaisesRegex(TypeError, CANNOT_SUBCLASS_TYPE):
1212 class F(type(*Ts)): pass
1213 with self.assertRaisesRegex(TypeError, CANNOT_SUBCLASS_TYPE):
1214 class G(type(Unpack[Ts])): pass
1215 with self.assertRaisesRegex(TypeError,
1216 r'Cannot subclass typing\.Unpack'):
1217 class H(Unpack): pass
1218 with self.assertRaisesRegex(TypeError, r'Cannot subclass \*Ts'):
1219 class I(*Ts): pass
1220 with self.assertRaisesRegex(TypeError, r'Cannot subclass \*Ts'):
1221 class J(Unpack[Ts]): pass
1222
1223 def test_variadic_class_args_are_correct(self):
1224 T = TypeVar('T')
1225 Ts = TypeVarTuple('Ts')
1226 class A(Generic[*Ts]): pass
1227 class B(Generic[Unpack[Ts]]): pass
1228
1229 C = A[()]
1230 D = B[()]
1231 self.assertEqual(C.__args__, ())
1232 self.assertEqual(D.__args__, ())
1233
1234 E = A[int]
1235 F = B[int]
1236 self.assertEqual(E.__args__, (int,))
1237 self.assertEqual(F.__args__, (int,))
1238
1239 G = A[int, str]
1240 H = B[int, str]
1241 self.assertEqual(G.__args__, (int, str))
1242 self.assertEqual(H.__args__, (int, str))
1243
1244 I = A[T]
1245 J = B[T]
1246 self.assertEqual(I.__args__, (T,))
1247 self.assertEqual(J.__args__, (T,))
1248
1249 K = A[*Ts]
1250 L = B[Unpack[Ts]]
1251 self.assertEqual(K.__args__, (*Ts,))
1252 self.assertEqual(L.__args__, (Unpack[Ts],))
1253
1254 M = A[T, *Ts]
1255 N = B[T, Unpack[Ts]]
1256 self.assertEqual(M.__args__, (T, *Ts))
1257 self.assertEqual(N.__args__, (T, Unpack[Ts]))
1258
1259 O = A[*Ts, T]
1260 P = B[Unpack[Ts], T]
1261 self.assertEqual(O.__args__, (*Ts, T))
1262 self.assertEqual(P.__args__, (Unpack[Ts], T))
1263
1264 def test_variadic_class_origin_is_correct(self):
1265 Ts = TypeVarTuple('Ts')
1266
1267 class C(Generic[*Ts]): pass
1268 self.assertIs(C[int].__origin__, C)
1269 self.assertIs(C[T].__origin__, C)
1270 self.assertIs(C[Unpack[Ts]].__origin__, C)
1271
1272 class D(Generic[Unpack[Ts]]): pass
1273 self.assertIs(D[int].__origin__, D)
1274 self.assertIs(D[T].__origin__, D)
1275 self.assertIs(D[Unpack[Ts]].__origin__, D)
1276
1277 def test_get_type_hints_on_unpack_args(self):
1278 Ts = TypeVarTuple('Ts')
1279
1280 def func1(*args: *Ts): pass
1281 self.assertEqual(gth(func1), {'args': Unpack[Ts]})
1282
1283 def func2(*args: *tuple[int, str]): pass
1284 self.assertEqual(gth(func2), {'args': Unpack[tuple[int, str]]})
1285
1286 class CustomVariadic(Generic[*Ts]): pass
1287
1288 def func3(*args: *CustomVariadic[int, str]): pass
1289 self.assertEqual(gth(func3), {'args': Unpack[CustomVariadic[int, str]]})
1290
1291 def test_get_type_hints_on_unpack_args_string(self):
1292 Ts = TypeVarTuple('Ts')
1293
1294 def func1(*args: '*Ts'): pass
1295 self.assertEqual(gth(func1, localns={'Ts': Ts}),
1296 {'args': Unpack[Ts]})
1297
1298 def func2(*args: '*tuple[int, str]'): pass
1299 self.assertEqual(gth(func2), {'args': Unpack[tuple[int, str]]})
1300
1301 class CustomVariadic(Generic[*Ts]): pass
1302
1303 def func3(*args: '*CustomVariadic[int, str]'): pass
1304 self.assertEqual(gth(func3, localns={'CustomVariadic': CustomVariadic}),
1305 {'args': Unpack[CustomVariadic[int, str]]})
1306
1307 def test_tuple_args_are_correct(self):
1308 Ts = TypeVarTuple('Ts')
1309
1310 self.assertEqual(tuple[*Ts].__args__, (*Ts,))
1311 self.assertEqual(Tuple[Unpack[Ts]].__args__, (Unpack[Ts],))
1312
1313 self.assertEqual(tuple[*Ts, int].__args__, (*Ts, int))
1314 self.assertEqual(Tuple[Unpack[Ts], int].__args__, (Unpack[Ts], int))
1315
1316 self.assertEqual(tuple[int, *Ts].__args__, (int, *Ts))
1317 self.assertEqual(Tuple[int, Unpack[Ts]].__args__, (int, Unpack[Ts]))
1318
1319 self.assertEqual(tuple[int, *Ts, str].__args__,
1320 (int, *Ts, str))
1321 self.assertEqual(Tuple[int, Unpack[Ts], str].__args__,
1322 (int, Unpack[Ts], str))
1323
1324 self.assertEqual(tuple[*Ts, int].__args__, (*Ts, int))
1325 self.assertEqual(Tuple[Unpack[Ts]].__args__, (Unpack[Ts],))
1326
1327 def test_callable_args_are_correct(self):
1328 Ts = TypeVarTuple('Ts')
1329 Ts1 = TypeVarTuple('Ts1')
1330 Ts2 = TypeVarTuple('Ts2')
1331
1332 # TypeVarTuple in the arguments
1333
1334 a = Callable[[*Ts], None]
1335 b = Callable[[Unpack[Ts]], None]
1336 self.assertEqual(a.__args__, (*Ts, type(None)))
1337 self.assertEqual(b.__args__, (Unpack[Ts], type(None)))
1338
1339 c = Callable[[int, *Ts], None]
1340 d = Callable[[int, Unpack[Ts]], None]
1341 self.assertEqual(c.__args__, (int, *Ts, type(None)))
1342 self.assertEqual(d.__args__, (int, Unpack[Ts], type(None)))
1343
1344 e = Callable[[*Ts, int], None]
1345 f = Callable[[Unpack[Ts], int], None]
1346 self.assertEqual(e.__args__, (*Ts, int, type(None)))
1347 self.assertEqual(f.__args__, (Unpack[Ts], int, type(None)))
1348
1349 g = Callable[[str, *Ts, int], None]
1350 h = Callable[[str, Unpack[Ts], int], None]
1351 self.assertEqual(g.__args__, (str, *Ts, int, type(None)))
1352 self.assertEqual(h.__args__, (str, Unpack[Ts], int, type(None)))
1353
1354 # TypeVarTuple as the return
1355
1356 i = Callable[[None], *Ts]
1357 j = Callable[[None], Unpack[Ts]]
1358 self.assertEqual(i.__args__, (type(None), *Ts))
1359 self.assertEqual(j.__args__, (type(None), Unpack[Ts]))
1360
1361 k = Callable[[None], tuple[int, *Ts]]
1362 l = Callable[[None], Tuple[int, Unpack[Ts]]]
1363 self.assertEqual(k.__args__, (type(None), tuple[int, *Ts]))
1364 self.assertEqual(l.__args__, (type(None), Tuple[int, Unpack[Ts]]))
1365
1366 m = Callable[[None], tuple[*Ts, int]]
1367 n = Callable[[None], Tuple[Unpack[Ts], int]]
1368 self.assertEqual(m.__args__, (type(None), tuple[*Ts, int]))
1369 self.assertEqual(n.__args__, (type(None), Tuple[Unpack[Ts], int]))
1370
1371 o = Callable[[None], tuple[str, *Ts, int]]
1372 p = Callable[[None], Tuple[str, Unpack[Ts], int]]
1373 self.assertEqual(o.__args__, (type(None), tuple[str, *Ts, int]))
1374 self.assertEqual(p.__args__, (type(None), Tuple[str, Unpack[Ts], int]))
1375
1376 # TypeVarTuple in both
1377
1378 q = Callable[[*Ts], *Ts]
1379 r = Callable[[Unpack[Ts]], Unpack[Ts]]
1380 self.assertEqual(q.__args__, (*Ts, *Ts))
1381 self.assertEqual(r.__args__, (Unpack[Ts], Unpack[Ts]))
1382
1383 s = Callable[[*Ts1], *Ts2]
1384 u = Callable[[Unpack[Ts1]], Unpack[Ts2]]
1385 self.assertEqual(s.__args__, (*Ts1, *Ts2))
1386 self.assertEqual(u.__args__, (Unpack[Ts1], Unpack[Ts2]))
1387
1388 def test_variadic_class_with_duplicate_typevartuples_fails(self):
1389 Ts1 = TypeVarTuple('Ts1')
1390 Ts2 = TypeVarTuple('Ts2')
1391
1392 with self.assertRaises(TypeError):
1393 class C(Generic[*Ts1, *Ts1]): pass
1394 with self.assertRaises(TypeError):
1395 class D(Generic[Unpack[Ts1], Unpack[Ts1]]): pass
1396
1397 with self.assertRaises(TypeError):
1398 class E(Generic[*Ts1, *Ts2, *Ts1]): pass
1399 with self.assertRaises(TypeError):
1400 class F(Generic[Unpack[Ts1], Unpack[Ts2], Unpack[Ts1]]): pass
1401
1402 def test_type_concatenation_in_variadic_class_argument_list_succeeds(self):
1403 Ts = TypeVarTuple('Ts')
1404 class C(Generic[Unpack[Ts]]): pass
1405
1406 C[int, *Ts]
1407 C[int, Unpack[Ts]]
1408
1409 C[*Ts, int]
1410 C[Unpack[Ts], int]
1411
1412 C[int, *Ts, str]
1413 C[int, Unpack[Ts], str]
1414
1415 C[int, bool, *Ts, float, str]
1416 C[int, bool, Unpack[Ts], float, str]
1417
1418 def test_type_concatenation_in_tuple_argument_list_succeeds(self):
1419 Ts = TypeVarTuple('Ts')
1420
1421 tuple[int, *Ts]
1422 tuple[*Ts, int]
1423 tuple[int, *Ts, str]
1424 tuple[int, bool, *Ts, float, str]
1425
1426 Tuple[int, Unpack[Ts]]
1427 Tuple[Unpack[Ts], int]
1428 Tuple[int, Unpack[Ts], str]
1429 Tuple[int, bool, Unpack[Ts], float, str]
1430
1431 def test_variadic_class_definition_using_packed_typevartuple_fails(self):
1432 Ts = TypeVarTuple('Ts')
1433 with self.assertRaises(TypeError):
1434 class C(Generic[Ts]): pass
1435
1436 def test_variadic_class_definition_using_concrete_types_fails(self):
1437 Ts = TypeVarTuple('Ts')
1438 with self.assertRaises(TypeError):
1439 class F(Generic[*Ts, int]): pass
1440 with self.assertRaises(TypeError):
1441 class E(Generic[Unpack[Ts], int]): pass
1442
1443 def test_variadic_class_with_2_typevars_accepts_2_or_more_args(self):
1444 Ts = TypeVarTuple('Ts')
1445 T1 = TypeVar('T1')
1446 T2 = TypeVar('T2')
1447
1448 class A(Generic[T1, T2, *Ts]): pass
1449 A[int, str]
1450 A[int, str, float]
1451 A[int, str, float, bool]
1452
1453 class B(Generic[T1, T2, Unpack[Ts]]): pass
1454 B[int, str]
1455 B[int, str, float]
1456 B[int, str, float, bool]
1457
1458 class C(Generic[T1, *Ts, T2]): pass
1459 C[int, str]
1460 C[int, str, float]
1461 C[int, str, float, bool]
1462
1463 class D(Generic[T1, Unpack[Ts], T2]): pass
1464 D[int, str]
1465 D[int, str, float]
1466 D[int, str, float, bool]
1467
1468 class E(Generic[*Ts, T1, T2]): pass
1469 E[int, str]
1470 E[int, str, float]
1471 E[int, str, float, bool]
1472
1473 class F(Generic[Unpack[Ts], T1, T2]): pass
1474 F[int, str]
1475 F[int, str, float]
1476 F[int, str, float, bool]
1477
1478 def test_variadic_args_annotations_are_correct(self):
1479 Ts = TypeVarTuple('Ts')
1480
1481 def f(*args: Unpack[Ts]): pass
1482 def g(*args: *Ts): pass
1483 self.assertEqual(f.__annotations__, {'args': Unpack[Ts]})
1484 self.assertEqual(g.__annotations__, {'args': (*Ts,)[0]})
1485
1486 def test_variadic_args_with_ellipsis_annotations_are_correct(self):
1487 def a(*args: *tuple[int, ...]): pass
1488 self.assertEqual(a.__annotations__,
1489 {'args': (*tuple[int, ...],)[0]})
1490
1491 def b(*args: Unpack[Tuple[int, ...]]): pass
1492 self.assertEqual(b.__annotations__,
1493 {'args': Unpack[Tuple[int, ...]]})
1494
1495 def test_concatenation_in_variadic_args_annotations_are_correct(self):
1496 Ts = TypeVarTuple('Ts')
1497
1498 # Unpacking using `*`, native `tuple` type
1499
1500 def a(*args: *tuple[int, *Ts]): pass
1501 self.assertEqual(
1502 a.__annotations__,
1503 {'args': (*tuple[int, *Ts],)[0]},
1504 )
1505
1506 def b(*args: *tuple[*Ts, int]): pass
1507 self.assertEqual(
1508 b.__annotations__,
1509 {'args': (*tuple[*Ts, int],)[0]},
1510 )
1511
1512 def c(*args: *tuple[str, *Ts, int]): pass
1513 self.assertEqual(
1514 c.__annotations__,
1515 {'args': (*tuple[str, *Ts, int],)[0]},
1516 )
1517
1518 def d(*args: *tuple[int, bool, *Ts, float, str]): pass
1519 self.assertEqual(
1520 d.__annotations__,
1521 {'args': (*tuple[int, bool, *Ts, float, str],)[0]},
1522 )
1523
1524 # Unpacking using `Unpack`, `Tuple` type from typing.py
1525
1526 def e(*args: Unpack[Tuple[int, Unpack[Ts]]]): pass
1527 self.assertEqual(
1528 e.__annotations__,
1529 {'args': Unpack[Tuple[int, Unpack[Ts]]]},
1530 )
1531
1532 def f(*args: Unpack[Tuple[Unpack[Ts], int]]): pass
1533 self.assertEqual(
1534 f.__annotations__,
1535 {'args': Unpack[Tuple[Unpack[Ts], int]]},
1536 )
1537
1538 def g(*args: Unpack[Tuple[str, Unpack[Ts], int]]): pass
1539 self.assertEqual(
1540 g.__annotations__,
1541 {'args': Unpack[Tuple[str, Unpack[Ts], int]]},
1542 )
1543
1544 def h(*args: Unpack[Tuple[int, bool, Unpack[Ts], float, str]]): pass
1545 self.assertEqual(
1546 h.__annotations__,
1547 {'args': Unpack[Tuple[int, bool, Unpack[Ts], float, str]]},
1548 )
1549
1550 def test_variadic_class_same_args_results_in_equalty(self):
1551 Ts = TypeVarTuple('Ts')
1552 class C(Generic[*Ts]): pass
1553 class D(Generic[Unpack[Ts]]): pass
1554
1555 self.assertEqual(C[int], C[int])
1556 self.assertEqual(D[int], D[int])
1557
1558 Ts1 = TypeVarTuple('Ts1')
1559 Ts2 = TypeVarTuple('Ts2')
1560
1561 self.assertEqual(
1562 C[*Ts1],
1563 C[*Ts1],
1564 )
1565 self.assertEqual(
1566 D[Unpack[Ts1]],
1567 D[Unpack[Ts1]],
1568 )
1569
1570 self.assertEqual(
1571 C[*Ts1, *Ts2],
1572 C[*Ts1, *Ts2],
1573 )
1574 self.assertEqual(
1575 D[Unpack[Ts1], Unpack[Ts2]],
1576 D[Unpack[Ts1], Unpack[Ts2]],
1577 )
1578
1579 self.assertEqual(
1580 C[int, *Ts1, *Ts2],
1581 C[int, *Ts1, *Ts2],
1582 )
1583 self.assertEqual(
1584 D[int, Unpack[Ts1], Unpack[Ts2]],
1585 D[int, Unpack[Ts1], Unpack[Ts2]],
1586 )
1587
1588 def test_variadic_class_arg_ordering_matters(self):
1589 Ts = TypeVarTuple('Ts')
1590 class C(Generic[*Ts]): pass
1591 class D(Generic[Unpack[Ts]]): pass
1592
1593 self.assertNotEqual(
1594 C[int, str],
1595 C[str, int],
1596 )
1597 self.assertNotEqual(
1598 D[int, str],
1599 D[str, int],
1600 )
1601
1602 Ts1 = TypeVarTuple('Ts1')
1603 Ts2 = TypeVarTuple('Ts2')
1604
1605 self.assertNotEqual(
1606 C[*Ts1, *Ts2],
1607 C[*Ts2, *Ts1],
1608 )
1609 self.assertNotEqual(
1610 D[Unpack[Ts1], Unpack[Ts2]],
1611 D[Unpack[Ts2], Unpack[Ts1]],
1612 )
1613
1614 def test_variadic_class_arg_typevartuple_identity_matters(self):
1615 Ts = TypeVarTuple('Ts')
1616 Ts1 = TypeVarTuple('Ts1')
1617 Ts2 = TypeVarTuple('Ts2')
1618
1619 class C(Generic[*Ts]): pass
1620 class D(Generic[Unpack[Ts]]): pass
1621
1622 self.assertNotEqual(C[*Ts1], C[*Ts2])
1623 self.assertNotEqual(D[Unpack[Ts1]], D[Unpack[Ts2]])
1624
1625
1626 class TypeVarTuplePicklingTests(BaseTestCase):
1627 # These are slightly awkward tests to run, because TypeVarTuples are only
1628 # picklable if defined in the global scope. We therefore need to push
1629 # various things defined in these tests into the global scope with `global`
1630 # statements at the start of each test.
1631
1632 @all_pickle_protocols
1633 def test_pickling_then_unpickling_results_in_same_identity(self, proto):
1634 global global_Ts1 # See explanation at start of class.
1635 global_Ts1 = TypeVarTuple('global_Ts1')
1636 global_Ts2 = pickle.loads(pickle.dumps(global_Ts1, proto))
1637 self.assertIs(global_Ts1, global_Ts2)
1638
1639 @all_pickle_protocols
1640 def test_pickling_then_unpickling_unpacked_results_in_same_identity(self, proto):
1641 global global_Ts # See explanation at start of class.
1642 global_Ts = TypeVarTuple('global_Ts')
1643
1644 unpacked1 = (*global_Ts,)[0]
1645 unpacked2 = pickle.loads(pickle.dumps(unpacked1, proto))
1646 self.assertIs(unpacked1, unpacked2)
1647
1648 unpacked3 = Unpack[global_Ts]
1649 unpacked4 = pickle.loads(pickle.dumps(unpacked3, proto))
1650 self.assertIs(unpacked3, unpacked4)
1651
1652 @all_pickle_protocols
1653 def test_pickling_then_unpickling_tuple_with_typevartuple_equality(
1654 self, proto
1655 ):
1656 global global_T, global_Ts # See explanation at start of class.
1657 global_T = TypeVar('global_T')
1658 global_Ts = TypeVarTuple('global_Ts')
1659
1660 tuples = [
1661 tuple[*global_Ts],
1662 Tuple[Unpack[global_Ts]],
1663
1664 tuple[T, *global_Ts],
1665 Tuple[T, Unpack[global_Ts]],
1666
1667 tuple[int, *global_Ts],
1668 Tuple[int, Unpack[global_Ts]],
1669 ]
1670 for t in tuples:
1671 t2 = pickle.loads(pickle.dumps(t, proto))
1672 self.assertEqual(t, t2)
1673
1674
1675 class UnionTests(BaseTestCase):
1676
1677 def test_basics(self):
1678 u = Union[int, float]
1679 self.assertNotEqual(u, Union)
1680
1681 def test_subclass_error(self):
1682 with self.assertRaises(TypeError):
1683 issubclass(int, Union)
1684 with self.assertRaises(TypeError):
1685 issubclass(Union, int)
1686 with self.assertRaises(TypeError):
1687 issubclass(Union[int, str], int)
1688
1689 def test_union_any(self):
1690 u = Union[Any]
1691 self.assertEqual(u, Any)
1692 u1 = Union[int, Any]
1693 u2 = Union[Any, int]
1694 u3 = Union[Any, object]
1695 self.assertEqual(u1, u2)
1696 self.assertNotEqual(u1, Any)
1697 self.assertNotEqual(u2, Any)
1698 self.assertNotEqual(u3, Any)
1699
1700 def test_union_object(self):
1701 u = Union[object]
1702 self.assertEqual(u, object)
1703 u1 = Union[int, object]
1704 u2 = Union[object, int]
1705 self.assertEqual(u1, u2)
1706 self.assertNotEqual(u1, object)
1707 self.assertNotEqual(u2, object)
1708
1709 def test_unordered(self):
1710 u1 = Union[int, float]
1711 u2 = Union[float, int]
1712 self.assertEqual(u1, u2)
1713
1714 def test_single_class_disappears(self):
1715 t = Union[Employee]
1716 self.assertIs(t, Employee)
1717
1718 def test_base_class_kept(self):
1719 u = Union[Employee, Manager]
1720 self.assertNotEqual(u, Employee)
1721 self.assertIn(Employee, u.__args__)
1722 self.assertIn(Manager, u.__args__)
1723
1724 def test_union_union(self):
1725 u = Union[int, float]
1726 v = Union[u, Employee]
1727 self.assertEqual(v, Union[int, float, Employee])
1728
1729 def test_union_of_unhashable(self):
1730 class UnhashableMeta(type):
1731 __hash__ = None
1732
1733 class A(metaclass=UnhashableMeta): ...
1734 class B(metaclass=UnhashableMeta): ...
1735
1736 self.assertEqual(Union[A, B].__args__, (A, B))
1737 union1 = Union[A, B]
1738 with self.assertRaises(TypeError):
1739 hash(union1)
1740
1741 union2 = Union[int, B]
1742 with self.assertRaises(TypeError):
1743 hash(union2)
1744
1745 union3 = Union[A, int]
1746 with self.assertRaises(TypeError):
1747 hash(union3)
1748
1749 def test_repr(self):
1750 self.assertEqual(repr(Union), 'typing.Union')
1751 u = Union[Employee, int]
1752 self.assertEqual(repr(u), 'typing.Union[%s.Employee, int]' % __name__)
1753 u = Union[int, Employee]
1754 self.assertEqual(repr(u), 'typing.Union[int, %s.Employee]' % __name__)
1755 T = TypeVar('T')
1756 u = Union[T, int][int]
1757 self.assertEqual(repr(u), repr(int))
1758 u = Union[List[int], int]
1759 self.assertEqual(repr(u), 'typing.Union[typing.List[int], int]')
1760 u = Union[list[int], dict[str, float]]
1761 self.assertEqual(repr(u), 'typing.Union[list[int], dict[str, float]]')
1762 u = Union[int | float]
1763 self.assertEqual(repr(u), 'typing.Union[int, float]')
1764
1765 u = Union[None, str]
1766 self.assertEqual(repr(u), 'typing.Optional[str]')
1767 u = Union[str, None]
1768 self.assertEqual(repr(u), 'typing.Optional[str]')
1769 u = Union[None, str, int]
1770 self.assertEqual(repr(u), 'typing.Union[NoneType, str, int]')
1771 u = Optional[str]
1772 self.assertEqual(repr(u), 'typing.Optional[str]')
1773
1774 def test_dir(self):
1775 dir_items = set(dir(Union[str, int]))
1776 for required_item in [
1777 '__args__', '__parameters__', '__origin__',
1778 ]:
1779 with self.subTest(required_item=required_item):
1780 self.assertIn(required_item, dir_items)
1781
1782 def test_cannot_subclass(self):
1783 with self.assertRaises(TypeError):
1784 class C(Union):
1785 pass
1786 with self.assertRaises(TypeError):
1787 class D(type(Union)):
1788 pass
1789 with self.assertRaises(TypeError):
1790 class E(Union[int, str]):
1791 pass
1792
1793 def test_cannot_instantiate(self):
1794 with self.assertRaises(TypeError):
1795 Union()
1796 with self.assertRaises(TypeError):
1797 type(Union)()
1798 u = Union[int, float]
1799 with self.assertRaises(TypeError):
1800 u()
1801 with self.assertRaises(TypeError):
1802 type(u)()
1803
1804 def test_union_generalization(self):
1805 self.assertFalse(Union[str, typing.Iterable[int]] == str)
1806 self.assertFalse(Union[str, typing.Iterable[int]] == typing.Iterable[int])
1807 self.assertIn(str, Union[str, typing.Iterable[int]].__args__)
1808 self.assertIn(typing.Iterable[int], Union[str, typing.Iterable[int]].__args__)
1809
1810 def test_union_compare_other(self):
1811 self.assertNotEqual(Union, object)
1812 self.assertNotEqual(Union, Any)
1813 self.assertNotEqual(ClassVar, Union)
1814 self.assertNotEqual(Optional, Union)
1815 self.assertNotEqual([None], Optional)
1816 self.assertNotEqual(Optional, typing.Mapping)
1817 self.assertNotEqual(Optional[typing.MutableMapping], Union)
1818
1819 def test_optional(self):
1820 o = Optional[int]
1821 u = Union[int, None]
1822 self.assertEqual(o, u)
1823
1824 def test_empty(self):
1825 with self.assertRaises(TypeError):
1826 Union[()]
1827
1828 def test_no_eval_union(self):
1829 u = Union[int, str]
1830 def f(x: u): ...
1831 self.assertIs(get_type_hints(f)['x'], u)
1832
1833 def test_function_repr_union(self):
1834 def fun() -> int: ...
1835 self.assertEqual(repr(Union[fun, int]), 'typing.Union[fun, int]')
1836
1837 def test_union_str_pattern(self):
1838 # Shouldn't crash; see http://bugs.python.org/issue25390
1839 A = Union[str, Pattern]
1840 A
1841
1842 def test_etree(self):
1843 # See https://github.com/python/typing/issues/229
1844 # (Only relevant for Python 2.)
1845 from xml.etree.ElementTree import Element
1846
1847 Union[Element, str] # Shouldn't crash
1848
1849 def Elem(*args):
1850 return Element(*args)
1851
1852 Union[Elem, str] # Nor should this
1853
1854 def test_union_of_literals(self):
1855 self.assertEqual(Union[Literal[1], Literal[2]].__args__,
1856 (Literal[1], Literal[2]))
1857 self.assertEqual(Union[Literal[1], Literal[1]],
1858 Literal[1])
1859
1860 self.assertEqual(Union[Literal[False], Literal[0]].__args__,
1861 (Literal[False], Literal[0]))
1862 self.assertEqual(Union[Literal[True], Literal[1]].__args__,
1863 (Literal[True], Literal[1]))
1864
1865 import enum
1866 class Ints(enum.IntEnum):
1867 A = 0
1868 B = 1
1869
1870 self.assertEqual(Union[Literal[Ints.A], Literal[Ints.A]],
1871 Literal[Ints.A])
1872 self.assertEqual(Union[Literal[Ints.B], Literal[Ints.B]],
1873 Literal[Ints.B])
1874
1875 self.assertEqual(Union[Literal[Ints.A], Literal[Ints.B]].__args__,
1876 (Literal[Ints.A], Literal[Ints.B]))
1877
1878 self.assertEqual(Union[Literal[0], Literal[Ints.A], Literal[False]].__args__,
1879 (Literal[0], Literal[Ints.A], Literal[False]))
1880 self.assertEqual(Union[Literal[1], Literal[Ints.B], Literal[True]].__args__,
1881 (Literal[1], Literal[Ints.B], Literal[True]))
1882
1883
1884 class TupleTests(BaseTestCase):
1885
1886 def test_basics(self):
1887 with self.assertRaises(TypeError):
1888 issubclass(Tuple, Tuple[int, str])
1889 with self.assertRaises(TypeError):
1890 issubclass(tuple, Tuple[int, str])
1891
1892 class TP(tuple): ...
1893 self.assertIsSubclass(tuple, Tuple)
1894 self.assertIsSubclass(TP, Tuple)
1895
1896 def test_equality(self):
1897 self.assertEqual(Tuple[int], Tuple[int])
1898 self.assertEqual(Tuple[int, ...], Tuple[int, ...])
1899 self.assertNotEqual(Tuple[int], Tuple[int, int])
1900 self.assertNotEqual(Tuple[int], Tuple[int, ...])
1901
1902 def test_tuple_subclass(self):
1903 class MyTuple(tuple):
1904 pass
1905 self.assertIsSubclass(MyTuple, Tuple)
1906 self.assertIsSubclass(Tuple, Tuple)
1907 self.assertIsSubclass(tuple, Tuple)
1908
1909 def test_tuple_instance_type_error(self):
1910 with self.assertRaises(TypeError):
1911 isinstance((0, 0), Tuple[int, int])
1912 self.assertIsInstance((0, 0), Tuple)
1913
1914 def test_repr(self):
1915 self.assertEqual(repr(Tuple), 'typing.Tuple')
1916 self.assertEqual(repr(Tuple[()]), 'typing.Tuple[()]')
1917 self.assertEqual(repr(Tuple[int, float]), 'typing.Tuple[int, float]')
1918 self.assertEqual(repr(Tuple[int, ...]), 'typing.Tuple[int, ...]')
1919 self.assertEqual(repr(Tuple[list[int]]), 'typing.Tuple[list[int]]')
1920
1921 def test_errors(self):
1922 with self.assertRaises(TypeError):
1923 issubclass(42, Tuple)
1924 with self.assertRaises(TypeError):
1925 issubclass(42, Tuple[int])
1926
1927
1928 class BaseCallableTests:
1929
1930 def test_self_subclass(self):
1931 Callable = self.Callable
1932 with self.assertRaises(TypeError):
1933 issubclass(types.FunctionType, Callable[[int], int])
1934 self.assertIsSubclass(types.FunctionType, Callable)
1935 self.assertIsSubclass(Callable, Callable)
1936
1937 def test_eq_hash(self):
1938 Callable = self.Callable
1939 C = Callable[[int], int]
1940 self.assertEqual(C, Callable[[int], int])
1941 self.assertEqual(len({C, Callable[[int], int]}), 1)
1942 self.assertNotEqual(C, Callable[[int], str])
1943 self.assertNotEqual(C, Callable[[str], int])
1944 self.assertNotEqual(C, Callable[[int, int], int])
1945 self.assertNotEqual(C, Callable[[], int])
1946 self.assertNotEqual(C, Callable[..., int])
1947 self.assertNotEqual(C, Callable)
1948
1949 def test_dir(self):
1950 Callable = self.Callable
1951 dir_items = set(dir(Callable[..., int]))
1952 for required_item in [
1953 '__args__', '__parameters__', '__origin__',
1954 ]:
1955 with self.subTest(required_item=required_item):
1956 self.assertIn(required_item, dir_items)
1957
1958 def test_cannot_instantiate(self):
1959 Callable = self.Callable
1960 with self.assertRaises(TypeError):
1961 Callable()
1962 with self.assertRaises(TypeError):
1963 type(Callable)()
1964 c = Callable[[int], str]
1965 with self.assertRaises(TypeError):
1966 c()
1967 with self.assertRaises(TypeError):
1968 type(c)()
1969
1970 def test_callable_wrong_forms(self):
1971 Callable = self.Callable
1972 with self.assertRaises(TypeError):
1973 Callable[int]
1974
1975 def test_callable_instance_works(self):
1976 Callable = self.Callable
1977 def f():
1978 pass
1979 self.assertIsInstance(f, Callable)
1980 self.assertNotIsInstance(None, Callable)
1981
1982 def test_callable_instance_type_error(self):
1983 Callable = self.Callable
1984 def f():
1985 pass
1986 with self.assertRaises(TypeError):
1987 isinstance(f, Callable[[], None])
1988 with self.assertRaises(TypeError):
1989 isinstance(f, Callable[[], Any])
1990 with self.assertRaises(TypeError):
1991 isinstance(None, Callable[[], None])
1992 with self.assertRaises(TypeError):
1993 isinstance(None, Callable[[], Any])
1994
1995 def test_repr(self):
1996 Callable = self.Callable
1997 fullname = f'{Callable.__module__}.Callable'
1998 ct0 = Callable[[], bool]
1999 self.assertEqual(repr(ct0), f'{fullname}[[], bool]')
2000 ct2 = Callable[[str, float], int]
2001 self.assertEqual(repr(ct2), f'{fullname}[[str, float], int]')
2002 ctv = Callable[..., str]
2003 self.assertEqual(repr(ctv), f'{fullname}[..., str]')
2004 ct3 = Callable[[str, float], list[int]]
2005 self.assertEqual(repr(ct3), f'{fullname}[[str, float], list[int]]')
2006
2007 def test_callable_with_ellipsis(self):
2008 Callable = self.Callable
2009 def foo(a: Callable[..., T]):
2010 pass
2011
2012 self.assertEqual(get_type_hints(foo, globals(), locals()),
2013 {'a': Callable[..., T]})
2014
2015 def test_ellipsis_in_generic(self):
2016 Callable = self.Callable
2017 # Shouldn't crash; see https://github.com/python/typing/issues/259
2018 typing.List[Callable[..., str]]
2019
2020 def test_or_and_ror(self):
2021 Callable = self.Callable
2022 self.assertEqual(Callable | Tuple, Union[Callable, Tuple])
2023 self.assertEqual(Tuple | Callable, Union[Tuple, Callable])
2024
2025 def test_basic(self):
2026 Callable = self.Callable
2027 alias = Callable[[int, str], float]
2028 if Callable is collections.abc.Callable:
2029 self.assertIsInstance(alias, types.GenericAlias)
2030 self.assertIs(alias.__origin__, collections.abc.Callable)
2031 self.assertEqual(alias.__args__, (int, str, float))
2032 self.assertEqual(alias.__parameters__, ())
2033
2034 def test_weakref(self):
2035 Callable = self.Callable
2036 alias = Callable[[int, str], float]
2037 self.assertEqual(weakref.ref(alias)(), alias)
2038
2039 def test_pickle(self):
2040 global T_pickle, P_pickle, TS_pickle # needed for pickling
2041 Callable = self.Callable
2042 T_pickle = TypeVar('T_pickle')
2043 P_pickle = ParamSpec('P_pickle')
2044 TS_pickle = TypeVarTuple('TS_pickle')
2045
2046 samples = [
2047 Callable[[int, str], float],
2048 Callable[P_pickle, int],
2049 Callable[P_pickle, T_pickle],
2050 Callable[Concatenate[int, P_pickle], int],
2051 Callable[Concatenate[*TS_pickle, P_pickle], int],
2052 ]
2053 for alias in samples:
2054 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
2055 with self.subTest(alias=alias, proto=proto):
2056 s = pickle.dumps(alias, proto)
2057 loaded = pickle.loads(s)
2058 self.assertEqual(alias.__origin__, loaded.__origin__)
2059 self.assertEqual(alias.__args__, loaded.__args__)
2060 self.assertEqual(alias.__parameters__, loaded.__parameters__)
2061
2062 del T_pickle, P_pickle, TS_pickle # cleaning up global state
2063
2064 def test_var_substitution(self):
2065 Callable = self.Callable
2066 fullname = f"{Callable.__module__}.Callable"
2067 C1 = Callable[[int, T], T]
2068 C2 = Callable[[KT, T], VT]
2069 C3 = Callable[..., T]
2070 self.assertEqual(C1[str], Callable[[int, str], str])
2071 self.assertEqual(C1[None], Callable[[int, type(None)], type(None)])
2072 self.assertEqual(C2[int, float, str], Callable[[int, float], str])
2073 self.assertEqual(C3[int], Callable[..., int])
2074 self.assertEqual(C3[NoReturn], Callable[..., NoReturn])
2075
2076 # multi chaining
2077 C4 = C2[int, VT, str]
2078 self.assertEqual(repr(C4), f"{fullname}[[int, ~VT], str]")
2079 self.assertEqual(repr(C4[dict]), f"{fullname}[[int, dict], str]")
2080 self.assertEqual(C4[dict], Callable[[int, dict], str])
2081
2082 # substitute a nested GenericAlias (both typing and the builtin
2083 # version)
2084 C5 = Callable[[typing.List[T], tuple[KT, T], VT], int]
2085 self.assertEqual(C5[int, str, float],
2086 Callable[[typing.List[int], tuple[str, int], float], int])
2087
2088 def test_type_subst_error(self):
2089 Callable = self.Callable
2090 P = ParamSpec('P')
2091 T = TypeVar('T')
2092
2093 pat = "Expected a list of types, an ellipsis, ParamSpec, or Concatenate."
2094
2095 with self.assertRaisesRegex(TypeError, pat):
2096 Callable[P, T][0, int]
2097
2098 def test_type_erasure(self):
2099 Callable = self.Callable
2100 class C1(Callable):
2101 def __call__(self):
2102 return None
2103 a = C1[[int], T]
2104 self.assertIs(a().__class__, C1)
2105 self.assertEqual(a().__orig_class__, C1[[int], T])
2106
2107 def test_paramspec(self):
2108 Callable = self.Callable
2109 fullname = f"{Callable.__module__}.Callable"
2110 P = ParamSpec('P')
2111 P2 = ParamSpec('P2')
2112 C1 = Callable[P, T]
2113 # substitution
2114 self.assertEqual(C1[[int], str], Callable[[int], str])
2115 self.assertEqual(C1[[int, str], str], Callable[[int, str], str])
2116 self.assertEqual(C1[[], str], Callable[[], str])
2117 self.assertEqual(C1[..., str], Callable[..., str])
2118 self.assertEqual(C1[P2, str], Callable[P2, str])
2119 self.assertEqual(C1[Concatenate[int, P2], str],
2120 Callable[Concatenate[int, P2], str])
2121 self.assertEqual(repr(C1), f"{fullname}[~P, ~T]")
2122 self.assertEqual(repr(C1[[int, str], str]), f"{fullname}[[int, str], str]")
2123 with self.assertRaises(TypeError):
2124 C1[int, str]
2125
2126 C2 = Callable[P, int]
2127 self.assertEqual(C2[[int]], Callable[[int], int])
2128 self.assertEqual(C2[[int, str]], Callable[[int, str], int])
2129 self.assertEqual(C2[[]], Callable[[], int])
2130 self.assertEqual(C2[...], Callable[..., int])
2131 self.assertEqual(C2[P2], Callable[P2, int])
2132 self.assertEqual(C2[Concatenate[int, P2]],
2133 Callable[Concatenate[int, P2], int])
2134 # special case in PEP 612 where
2135 # X[int, str, float] == X[[int, str, float]]
2136 self.assertEqual(C2[int], Callable[[int], int])
2137 self.assertEqual(C2[int, str], Callable[[int, str], int])
2138 self.assertEqual(repr(C2), f"{fullname}[~P, int]")
2139 self.assertEqual(repr(C2[int, str]), f"{fullname}[[int, str], int]")
2140
2141 def test_concatenate(self):
2142 Callable = self.Callable
2143 fullname = f"{Callable.__module__}.Callable"
2144 T = TypeVar('T')
2145 P = ParamSpec('P')
2146 P2 = ParamSpec('P2')
2147 C = Callable[Concatenate[int, P], T]
2148 self.assertEqual(repr(C),
2149 f"{fullname}[typing.Concatenate[int, ~P], ~T]")
2150 self.assertEqual(C[P2, int], Callable[Concatenate[int, P2], int])
2151 self.assertEqual(C[[str, float], int], Callable[[int, str, float], int])
2152 self.assertEqual(C[[], int], Callable[[int], int])
2153 self.assertEqual(C[Concatenate[str, P2], int],
2154 Callable[Concatenate[int, str, P2], int])
2155 self.assertEqual(C[..., int], Callable[Concatenate[int, ...], int])
2156
2157 C = Callable[Concatenate[int, P], int]
2158 self.assertEqual(repr(C),
2159 f"{fullname}[typing.Concatenate[int, ~P], int]")
2160 self.assertEqual(C[P2], Callable[Concatenate[int, P2], int])
2161 self.assertEqual(C[[str, float]], Callable[[int, str, float], int])
2162 self.assertEqual(C[str, float], Callable[[int, str, float], int])
2163 self.assertEqual(C[[]], Callable[[int], int])
2164 self.assertEqual(C[Concatenate[str, P2]],
2165 Callable[Concatenate[int, str, P2], int])
2166 self.assertEqual(C[...], Callable[Concatenate[int, ...], int])
2167
2168 def test_nested_paramspec(self):
2169 # Since Callable has some special treatment, we want to be sure
2170 # that substituion works correctly, see gh-103054
2171 Callable = self.Callable
2172 P = ParamSpec('P')
2173 P2 = ParamSpec('P2')
2174 T = TypeVar('T')
2175 T2 = TypeVar('T2')
2176 Ts = TypeVarTuple('Ts')
2177 class My(Generic[P, T]):
2178 pass
2179
2180 self.assertEqual(My.__parameters__, (P, T))
2181
2182 C1 = My[[int, T2], Callable[P2, T2]]
2183 self.assertEqual(C1.__args__, ((int, T2), Callable[P2, T2]))
2184 self.assertEqual(C1.__parameters__, (T2, P2))
2185 self.assertEqual(C1[str, [list[int], bytes]],
2186 My[[int, str], Callable[[list[int], bytes], str]])
2187
2188 C2 = My[[Callable[[T2], int], list[T2]], str]
2189 self.assertEqual(C2.__args__, ((Callable[[T2], int], list[T2]), str))
2190 self.assertEqual(C2.__parameters__, (T2,))
2191 self.assertEqual(C2[list[str]],
2192 My[[Callable[[list[str]], int], list[list[str]]], str])
2193
2194 C3 = My[[Callable[P2, T2], T2], T2]
2195 self.assertEqual(C3.__args__, ((Callable[P2, T2], T2), T2))
2196 self.assertEqual(C3.__parameters__, (P2, T2))
2197 self.assertEqual(C3[[], int],
2198 My[[Callable[[], int], int], int])
2199 self.assertEqual(C3[[str, bool], int],
2200 My[[Callable[[str, bool], int], int], int])
2201 self.assertEqual(C3[[str, bool], T][int],
2202 My[[Callable[[str, bool], int], int], int])
2203
2204 C4 = My[[Callable[[int, *Ts, str], T2], T2], T2]
2205 self.assertEqual(C4.__args__, ((Callable[[int, *Ts, str], T2], T2), T2))
2206 self.assertEqual(C4.__parameters__, (Ts, T2))
2207 self.assertEqual(C4[bool, bytes, float],
2208 My[[Callable[[int, bool, bytes, str], float], float], float])
2209
2210 def test_errors(self):
2211 Callable = self.Callable
2212 alias = Callable[[int, str], float]
2213 with self.assertRaisesRegex(TypeError, "is not a generic class"):
2214 alias[int]
2215 P = ParamSpec('P')
2216 C1 = Callable[P, T]
2217 with self.assertRaisesRegex(TypeError, "many arguments for"):
2218 C1[int, str, str]
2219 with self.assertRaisesRegex(TypeError, "few arguments for"):
2220 C1[int]
2221
2222 class TypingCallableTests(BaseCallableTests, BaseTestCase):
2223 Callable = typing.Callable
2224
2225 def test_consistency(self):
2226 # bpo-42195
2227 # Testing collections.abc.Callable's consistency with typing.Callable
2228 c1 = typing.Callable[[int, str], dict]
2229 c2 = collections.abc.Callable[[int, str], dict]
2230 self.assertEqual(c1.__args__, c2.__args__)
2231 self.assertEqual(hash(c1.__args__), hash(c2.__args__))
2232
2233
2234 class CollectionsCallableTests(BaseCallableTests, BaseTestCase):
2235 Callable = collections.abc.Callable
2236
2237
2238 class LiteralTests(BaseTestCase):
2239 def test_basics(self):
2240 # All of these are allowed.
2241 Literal[1]
2242 Literal[1, 2, 3]
2243 Literal["x", "y", "z"]
2244 Literal[None]
2245 Literal[True]
2246 Literal[1, "2", False]
2247 Literal[Literal[1, 2], Literal[4, 5]]
2248 Literal[b"foo", u"bar"]
2249
2250 def test_enum(self):
2251 import enum
2252 class My(enum.Enum):
2253 A = 'A'
2254
2255 self.assertEqual(Literal[My.A].__args__, (My.A,))
2256
2257 def test_illegal_parameters_do_not_raise_runtime_errors(self):
2258 # Type checkers should reject these types, but we do not
2259 # raise errors at runtime to maintain maximum flexibility.
2260 Literal[int]
2261 Literal[3j + 2, ..., ()]
2262 Literal[{"foo": 3, "bar": 4}]
2263 Literal[T]
2264
2265 def test_literals_inside_other_types(self):
2266 List[Literal[1, 2, 3]]
2267 List[Literal[("foo", "bar", "baz")]]
2268
2269 def test_repr(self):
2270 self.assertEqual(repr(Literal[1]), "typing.Literal[1]")
2271 self.assertEqual(repr(Literal[1, True, "foo"]), "typing.Literal[1, True, 'foo']")
2272 self.assertEqual(repr(Literal[int]), "typing.Literal[int]")
2273 self.assertEqual(repr(Literal), "typing.Literal")
2274 self.assertEqual(repr(Literal[None]), "typing.Literal[None]")
2275 self.assertEqual(repr(Literal[1, 2, 3, 3]), "typing.Literal[1, 2, 3]")
2276
2277 def test_dir(self):
2278 dir_items = set(dir(Literal[1, 2, 3]))
2279 for required_item in [
2280 '__args__', '__parameters__', '__origin__',
2281 ]:
2282 with self.subTest(required_item=required_item):
2283 self.assertIn(required_item, dir_items)
2284
2285 def test_cannot_init(self):
2286 with self.assertRaises(TypeError):
2287 Literal()
2288 with self.assertRaises(TypeError):
2289 Literal[1]()
2290 with self.assertRaises(TypeError):
2291 type(Literal)()
2292 with self.assertRaises(TypeError):
2293 type(Literal[1])()
2294
2295 def test_no_isinstance_or_issubclass(self):
2296 with self.assertRaises(TypeError):
2297 isinstance(1, Literal[1])
2298 with self.assertRaises(TypeError):
2299 isinstance(int, Literal[1])
2300 with self.assertRaises(TypeError):
2301 issubclass(1, Literal[1])
2302 with self.assertRaises(TypeError):
2303 issubclass(int, Literal[1])
2304
2305 def test_no_subclassing(self):
2306 with self.assertRaises(TypeError):
2307 class Foo(Literal[1]): pass
2308 with self.assertRaises(TypeError):
2309 class Bar(Literal): pass
2310
2311 def test_no_multiple_subscripts(self):
2312 with self.assertRaises(TypeError):
2313 Literal[1][1]
2314
2315 def test_equal(self):
2316 self.assertNotEqual(Literal[0], Literal[False])
2317 self.assertNotEqual(Literal[True], Literal[1])
2318 self.assertNotEqual(Literal[1], Literal[2])
2319 self.assertNotEqual(Literal[1, True], Literal[1])
2320 self.assertNotEqual(Literal[1, True], Literal[1, 1])
2321 self.assertNotEqual(Literal[1, 2], Literal[True, 2])
2322 self.assertEqual(Literal[1], Literal[1])
2323 self.assertEqual(Literal[1, 2], Literal[2, 1])
2324 self.assertEqual(Literal[1, 2, 3], Literal[1, 2, 3, 3])
2325
2326 def test_hash(self):
2327 self.assertEqual(hash(Literal[1]), hash(Literal[1]))
2328 self.assertEqual(hash(Literal[1, 2]), hash(Literal[2, 1]))
2329 self.assertEqual(hash(Literal[1, 2, 3]), hash(Literal[1, 2, 3, 3]))
2330
2331 def test_args(self):
2332 self.assertEqual(Literal[1, 2, 3].__args__, (1, 2, 3))
2333 self.assertEqual(Literal[1, 2, 3, 3].__args__, (1, 2, 3))
2334 self.assertEqual(Literal[1, Literal[2], Literal[3, 4]].__args__, (1, 2, 3, 4))
2335 # Mutable arguments will not be deduplicated
2336 self.assertEqual(Literal[[], []].__args__, ([], []))
2337
2338 def test_flatten(self):
2339 l1 = Literal[Literal[1], Literal[2], Literal[3]]
2340 l2 = Literal[Literal[1, 2], 3]
2341 l3 = Literal[Literal[1, 2, 3]]
2342 for l in l1, l2, l3:
2343 self.assertEqual(l, Literal[1, 2, 3])
2344 self.assertEqual(l.__args__, (1, 2, 3))
2345
2346 def test_does_not_flatten_enum(self):
2347 import enum
2348 class Ints(enum.IntEnum):
2349 A = 1
2350 B = 2
2351
2352 l = Literal[
2353 Literal[Ints.A],
2354 Literal[Ints.B],
2355 Literal[1],
2356 Literal[2],
2357 ]
2358 self.assertEqual(l.__args__, (Ints.A, Ints.B, 1, 2))
2359
2360
2361 XK = TypeVar('XK', str, bytes)
2362 XV = TypeVar('XV')
2363
2364
2365 class SimpleMapping(Generic[XK, XV]):
2366
2367 def __getitem__(self, key: XK) -> XV:
2368 ...
2369
2370 def __setitem__(self, key: XK, value: XV):
2371 ...
2372
2373 def get(self, key: XK, default: XV = None) -> XV:
2374 ...
2375
2376
2377 class MySimpleMapping(SimpleMapping[XK, XV]):
2378
2379 def __init__(self):
2380 self.store = {}
2381
2382 def __getitem__(self, key: str):
2383 return self.store[key]
2384
2385 def __setitem__(self, key: str, value):
2386 self.store[key] = value
2387
2388 def get(self, key: str, default=None):
2389 try:
2390 return self.store[key]
2391 except KeyError:
2392 return default
2393
2394
2395 class Coordinate(Protocol):
2396 x: int
2397 y: int
2398
2399 @runtime_checkable
2400 class Point(Coordinate, Protocol):
2401 label: str
2402
2403 class MyPoint:
2404 x: int
2405 y: int
2406 label: str
2407
2408 class XAxis(Protocol):
2409 x: int
2410
2411 class YAxis(Protocol):
2412 y: int
2413
2414 @runtime_checkable
2415 class Position(XAxis, YAxis, Protocol):
2416 pass
2417
2418 @runtime_checkable
2419 class Proto(Protocol):
2420 attr: int
2421 def meth(self, arg: str) -> int:
2422 ...
2423
2424 class Concrete(Proto):
2425 pass
2426
2427 class Other:
2428 attr: int = 1
2429 def meth(self, arg: str) -> int:
2430 if arg == 'this':
2431 return 1
2432 return 0
2433
2434 class NT(NamedTuple):
2435 x: int
2436 y: int
2437
2438 @runtime_checkable
2439 class HasCallProtocol(Protocol):
2440 __call__: typing.Callable
2441
2442
2443 class ProtocolTests(BaseTestCase):
2444 def test_basic_protocol(self):
2445 @runtime_checkable
2446 class P(Protocol):
2447 def meth(self):
2448 pass
2449
2450 class C: pass
2451
2452 class D:
2453 def meth(self):
2454 pass
2455
2456 def f():
2457 pass
2458
2459 self.assertIsSubclass(D, P)
2460 self.assertIsInstance(D(), P)
2461 self.assertNotIsSubclass(C, P)
2462 self.assertNotIsInstance(C(), P)
2463 self.assertNotIsSubclass(types.FunctionType, P)
2464 self.assertNotIsInstance(f, P)
2465
2466 def test_everything_implements_empty_protocol(self):
2467 @runtime_checkable
2468 class Empty(Protocol):
2469 pass
2470
2471 class C:
2472 pass
2473
2474 def f():
2475 pass
2476
2477 for thing in (object, type, tuple, C, types.FunctionType):
2478 self.assertIsSubclass(thing, Empty)
2479 for thing in (object(), 1, (), typing, f):
2480 self.assertIsInstance(thing, Empty)
2481
2482 def test_function_implements_protocol(self):
2483 def f():
2484 pass
2485
2486 self.assertIsInstance(f, HasCallProtocol)
2487
2488 def test_no_inheritance_from_nominal(self):
2489 class C: pass
2490
2491 class BP(Protocol): pass
2492
2493 with self.assertRaises(TypeError):
2494 class P(C, Protocol):
2495 pass
2496 with self.assertRaises(TypeError):
2497 class Q(Protocol, C):
2498 pass
2499 with self.assertRaises(TypeError):
2500 class R(BP, C, Protocol):
2501 pass
2502
2503 class D(BP, C): pass
2504
2505 class E(C, BP): pass
2506
2507 self.assertNotIsInstance(D(), E)
2508 self.assertNotIsInstance(E(), D)
2509
2510 def test_no_instantiation(self):
2511 class P(Protocol): pass
2512
2513 with self.assertRaises(TypeError):
2514 P()
2515
2516 class C(P): pass
2517
2518 self.assertIsInstance(C(), C)
2519 with self.assertRaises(TypeError):
2520 C(42)
2521
2522 T = TypeVar('T')
2523
2524 class PG(Protocol[T]): pass
2525
2526 with self.assertRaises(TypeError):
2527 PG()
2528 with self.assertRaises(TypeError):
2529 PG[int]()
2530 with self.assertRaises(TypeError):
2531 PG[T]()
2532
2533 class CG(PG[T]): pass
2534
2535 self.assertIsInstance(CG[int](), CG)
2536 with self.assertRaises(TypeError):
2537 CG[int](42)
2538
2539 def test_protocol_defining_init_does_not_get_overridden(self):
2540 # check that P.__init__ doesn't get clobbered
2541 # see https://bugs.python.org/issue44807
2542
2543 class P(Protocol):
2544 x: int
2545 def __init__(self, x: int) -> None:
2546 self.x = x
2547 class C: pass
2548
2549 c = C()
2550 P.__init__(c, 1)
2551 self.assertEqual(c.x, 1)
2552
2553 def test_concrete_class_inheriting_init_from_protocol(self):
2554 class P(Protocol):
2555 x: int
2556 def __init__(self, x: int) -> None:
2557 self.x = x
2558
2559 class C(P): pass
2560
2561 c = C(1)
2562 self.assertIsInstance(c, C)
2563 self.assertEqual(c.x, 1)
2564
2565 def test_cannot_instantiate_abstract(self):
2566 @runtime_checkable
2567 class P(Protocol):
2568 @abc.abstractmethod
2569 def ameth(self) -> int:
2570 raise NotImplementedError
2571
2572 class B(P):
2573 pass
2574
2575 class C(B):
2576 def ameth(self) -> int:
2577 return 26
2578
2579 with self.assertRaises(TypeError):
2580 B()
2581 self.assertIsInstance(C(), P)
2582
2583 def test_subprotocols_extending(self):
2584 class P1(Protocol):
2585 def meth1(self):
2586 pass
2587
2588 @runtime_checkable
2589 class P2(P1, Protocol):
2590 def meth2(self):
2591 pass
2592
2593 class C:
2594 def meth1(self):
2595 pass
2596
2597 def meth2(self):
2598 pass
2599
2600 class C1:
2601 def meth1(self):
2602 pass
2603
2604 class C2:
2605 def meth2(self):
2606 pass
2607
2608 self.assertNotIsInstance(C1(), P2)
2609 self.assertNotIsInstance(C2(), P2)
2610 self.assertNotIsSubclass(C1, P2)
2611 self.assertNotIsSubclass(C2, P2)
2612 self.assertIsInstance(C(), P2)
2613 self.assertIsSubclass(C, P2)
2614
2615 def test_subprotocols_merging(self):
2616 class P1(Protocol):
2617 def meth1(self):
2618 pass
2619
2620 class P2(Protocol):
2621 def meth2(self):
2622 pass
2623
2624 @runtime_checkable
2625 class P(P1, P2, Protocol):
2626 pass
2627
2628 class C:
2629 def meth1(self):
2630 pass
2631
2632 def meth2(self):
2633 pass
2634
2635 class C1:
2636 def meth1(self):
2637 pass
2638
2639 class C2:
2640 def meth2(self):
2641 pass
2642
2643 self.assertNotIsInstance(C1(), P)
2644 self.assertNotIsInstance(C2(), P)
2645 self.assertNotIsSubclass(C1, P)
2646 self.assertNotIsSubclass(C2, P)
2647 self.assertIsInstance(C(), P)
2648 self.assertIsSubclass(C, P)
2649
2650 def test_protocols_issubclass(self):
2651 T = TypeVar('T')
2652
2653 @runtime_checkable
2654 class P(Protocol):
2655 def x(self): ...
2656
2657 @runtime_checkable
2658 class PG(Protocol[T]):
2659 def x(self): ...
2660
2661 class BadP(Protocol):
2662 def x(self): ...
2663
2664 class BadPG(Protocol[T]):
2665 def x(self): ...
2666
2667 class C:
2668 def x(self): ...
2669
2670 self.assertIsSubclass(C, P)
2671 self.assertIsSubclass(C, PG)
2672 self.assertIsSubclass(BadP, PG)
2673
2674 with self.assertRaises(TypeError):
2675 issubclass(C, PG[T])
2676 with self.assertRaises(TypeError):
2677 issubclass(C, PG[C])
2678 with self.assertRaises(TypeError):
2679 issubclass(C, BadP)
2680 with self.assertRaises(TypeError):
2681 issubclass(C, BadPG)
2682 with self.assertRaises(TypeError):
2683 issubclass(P, PG[T])
2684 with self.assertRaises(TypeError):
2685 issubclass(PG, PG[int])
2686
2687 only_classes_allowed = r"issubclass\(\) arg 1 must be a class"
2688
2689 with self.assertRaisesRegex(TypeError, only_classes_allowed):
2690 issubclass(1, P)
2691 with self.assertRaisesRegex(TypeError, only_classes_allowed):
2692 issubclass(1, PG)
2693 with self.assertRaisesRegex(TypeError, only_classes_allowed):
2694 issubclass(1, BadP)
2695 with self.assertRaisesRegex(TypeError, only_classes_allowed):
2696 issubclass(1, BadPG)
2697
2698 def test_implicit_issubclass_between_two_protocols(self):
2699 @runtime_checkable
2700 class CallableMembersProto(Protocol):
2701 def meth(self): ...
2702
2703 # All the below protocols should be considered "subclasses"
2704 # of CallableMembersProto at runtime,
2705 # even though none of them explicitly subclass CallableMembersProto
2706
2707 class IdenticalProto(Protocol):
2708 def meth(self): ...
2709
2710 class SupersetProto(Protocol):
2711 def meth(self): ...
2712 def meth2(self): ...
2713
2714 class NonCallableMembersProto(Protocol):
2715 meth: Callable[[], None]
2716
2717 class NonCallableMembersSupersetProto(Protocol):
2718 meth: Callable[[], None]
2719 meth2: Callable[[str, int], bool]
2720
2721 class MixedMembersProto1(Protocol):
2722 meth: Callable[[], None]
2723 def meth2(self): ...
2724
2725 class MixedMembersProto2(Protocol):
2726 def meth(self): ...
2727 meth2: Callable[[str, int], bool]
2728
2729 for proto in (
2730 IdenticalProto, SupersetProto, NonCallableMembersProto,
2731 NonCallableMembersSupersetProto, MixedMembersProto1, MixedMembersProto2
2732 ):
2733 with self.subTest(proto=proto.__name__):
2734 self.assertIsSubclass(proto, CallableMembersProto)
2735
2736 # These two shouldn't be considered subclasses of CallableMembersProto, however,
2737 # since they don't have the `meth` protocol member
2738
2739 class EmptyProtocol(Protocol): ...
2740 class UnrelatedProtocol(Protocol):
2741 def wut(self): ...
2742
2743 self.assertNotIsSubclass(EmptyProtocol, CallableMembersProto)
2744 self.assertNotIsSubclass(UnrelatedProtocol, CallableMembersProto)
2745
2746 # These aren't protocols at all (despite having annotations),
2747 # so they should only be considered subclasses of CallableMembersProto
2748 # if they *actually have an attribute* matching the `meth` member
2749 # (just having an annotation is insufficient)
2750
2751 class AnnotatedButNotAProtocol:
2752 meth: Callable[[], None]
2753
2754 class NotAProtocolButAnImplicitSubclass:
2755 def meth(self): pass
2756
2757 class NotAProtocolButAnImplicitSubclass2:
2758 meth: Callable[[], None]
2759 def meth(self): pass
2760
2761 class NotAProtocolButAnImplicitSubclass3:
2762 meth: Callable[[], None]
2763 meth2: Callable[[int, str], bool]
2764 def meth(self): pass
2765 def meth2(self, x, y): return True
2766
2767 self.assertNotIsSubclass(AnnotatedButNotAProtocol, CallableMembersProto)
2768 self.assertIsSubclass(NotAProtocolButAnImplicitSubclass, CallableMembersProto)
2769 self.assertIsSubclass(NotAProtocolButAnImplicitSubclass2, CallableMembersProto)
2770 self.assertIsSubclass(NotAProtocolButAnImplicitSubclass3, CallableMembersProto)
2771
2772 def test_isinstance_checks_not_at_whim_of_gc(self):
2773 self.addCleanup(gc.enable)
2774 gc.disable()
2775
2776 with self.assertRaisesRegex(
2777 TypeError,
2778 "Protocols can only inherit from other protocols"
2779 ):
2780 class Foo(collections.abc.Mapping, Protocol):
2781 pass
2782
2783 self.assertNotIsInstance([], collections.abc.Mapping)
2784
2785 def test_protocols_issubclass_non_callable(self):
2786 class C:
2787 x = 1
2788
2789 @runtime_checkable
2790 class PNonCall(Protocol):
2791 x = 1
2792
2793 with self.assertRaises(TypeError):
2794 issubclass(C, PNonCall)
2795 self.assertIsInstance(C(), PNonCall)
2796 PNonCall.register(C)
2797 with self.assertRaises(TypeError):
2798 issubclass(C, PNonCall)
2799 self.assertIsInstance(C(), PNonCall)
2800
2801 # check that non-protocol subclasses are not affected
2802 class D(PNonCall): ...
2803
2804 self.assertNotIsSubclass(C, D)
2805 self.assertNotIsInstance(C(), D)
2806 D.register(C)
2807 self.assertIsSubclass(C, D)
2808 self.assertIsInstance(C(), D)
2809 with self.assertRaises(TypeError):
2810 issubclass(D, PNonCall)
2811
2812 def test_protocols_isinstance(self):
2813 T = TypeVar('T')
2814
2815 @runtime_checkable
2816 class P(Protocol):
2817 def meth(x): ...
2818
2819 @runtime_checkable
2820 class PG(Protocol[T]):
2821 def meth(x): ...
2822
2823 @runtime_checkable
2824 class WeirdProto(Protocol):
2825 meth = str.maketrans
2826
2827 @runtime_checkable
2828 class WeirdProto2(Protocol):
2829 meth = lambda *args, **kwargs: None
2830
2831 class CustomCallable:
2832 def __call__(self, *args, **kwargs):
2833 pass
2834
2835 @runtime_checkable
2836 class WeirderProto(Protocol):
2837 meth = CustomCallable()
2838
2839 class BadP(Protocol):
2840 def meth(x): ...
2841
2842 class BadPG(Protocol[T]):
2843 def meth(x): ...
2844
2845 class C:
2846 def meth(x): ...
2847
2848 class C2:
2849 def __init__(self):
2850 self.meth = lambda: None
2851
2852 for klass in C, C2:
2853 for proto in P, PG, WeirdProto, WeirdProto2, WeirderProto:
2854 with self.subTest(klass=klass.__name__, proto=proto.__name__):
2855 self.assertIsInstance(klass(), proto)
2856
2857 with self.assertRaises(TypeError):
2858 isinstance(C(), PG[T])
2859 with self.assertRaises(TypeError):
2860 isinstance(C(), PG[C])
2861 with self.assertRaises(TypeError):
2862 isinstance(C(), BadP)
2863 with self.assertRaises(TypeError):
2864 isinstance(C(), BadPG)
2865
2866 def test_protocols_isinstance_properties_and_descriptors(self):
2867 class C:
2868 @property
2869 def attr(self):
2870 return 42
2871
2872 class CustomDescriptor:
2873 def __get__(self, obj, objtype=None):
2874 return 42
2875
2876 class D:
2877 attr = CustomDescriptor()
2878
2879 # Check that properties set on superclasses
2880 # are still found by the isinstance() logic
2881 class E(C): ...
2882 class F(D): ...
2883
2884 class Empty: ...
2885
2886 T = TypeVar('T')
2887
2888 @runtime_checkable
2889 class P(Protocol):
2890 @property
2891 def attr(self): ...
2892
2893 @runtime_checkable
2894 class P1(Protocol):
2895 attr: int
2896
2897 @runtime_checkable
2898 class PG(Protocol[T]):
2899 @property
2900 def attr(self): ...
2901
2902 @runtime_checkable
2903 class PG1(Protocol[T]):
2904 attr: T
2905
2906 for protocol_class in P, P1, PG, PG1:
2907 for klass in C, D, E, F:
2908 with self.subTest(
2909 klass=klass.__name__,
2910 protocol_class=protocol_class.__name__
2911 ):
2912 self.assertIsInstance(klass(), protocol_class)
2913
2914 with self.subTest(klass="Empty", protocol_class=protocol_class.__name__):
2915 self.assertNotIsInstance(Empty(), protocol_class)
2916
2917 class BadP(Protocol):
2918 @property
2919 def attr(self): ...
2920
2921 class BadP1(Protocol):
2922 attr: int
2923
2924 class BadPG(Protocol[T]):
2925 @property
2926 def attr(self): ...
2927
2928 class BadPG1(Protocol[T]):
2929 attr: T
2930
2931 for obj in PG[T], PG[C], PG1[T], PG1[C], BadP, BadP1, BadPG, BadPG1:
2932 for klass in C, D, E, F, Empty:
2933 with self.subTest(klass=klass.__name__, obj=obj):
2934 with self.assertRaises(TypeError):
2935 isinstance(klass(), obj)
2936
2937 def test_protocols_isinstance_not_fooled_by_custom_dir(self):
2938 @runtime_checkable
2939 class HasX(Protocol):
2940 x: int
2941
2942 class CustomDirWithX:
2943 x = 10
2944 def __dir__(self):
2945 return []
2946
2947 class CustomDirWithoutX:
2948 def __dir__(self):
2949 return ["x"]
2950
2951 self.assertIsInstance(CustomDirWithX(), HasX)
2952 self.assertNotIsInstance(CustomDirWithoutX(), HasX)
2953
2954 def test_protocols_isinstance_py36(self):
2955 class APoint:
2956 def __init__(self, x, y, label):
2957 self.x = x
2958 self.y = y
2959 self.label = label
2960
2961 class BPoint:
2962 label = 'B'
2963
2964 def __init__(self, x, y):
2965 self.x = x
2966 self.y = y
2967
2968 class C:
2969 def __init__(self, attr):
2970 self.attr = attr
2971
2972 def meth(self, arg):
2973 return 0
2974
2975 class Bad: pass
2976
2977 self.assertIsInstance(APoint(1, 2, 'A'), Point)
2978 self.assertIsInstance(BPoint(1, 2), Point)
2979 self.assertNotIsInstance(MyPoint(), Point)
2980 self.assertIsInstance(BPoint(1, 2), Position)
2981 self.assertIsInstance(Other(), Proto)
2982 self.assertIsInstance(Concrete(), Proto)
2983 self.assertIsInstance(C(42), Proto)
2984 self.assertNotIsInstance(Bad(), Proto)
2985 self.assertNotIsInstance(Bad(), Point)
2986 self.assertNotIsInstance(Bad(), Position)
2987 self.assertNotIsInstance(Bad(), Concrete)
2988 self.assertNotIsInstance(Other(), Concrete)
2989 self.assertIsInstance(NT(1, 2), Position)
2990
2991 def test_protocols_isinstance_init(self):
2992 T = TypeVar('T')
2993
2994 @runtime_checkable
2995 class P(Protocol):
2996 x = 1
2997
2998 @runtime_checkable
2999 class PG(Protocol[T]):
3000 x = 1
3001
3002 class C:
3003 def __init__(self, x):
3004 self.x = x
3005
3006 self.assertIsInstance(C(1), P)
3007 self.assertIsInstance(C(1), PG)
3008
3009 def test_protocols_isinstance_monkeypatching(self):
3010 @runtime_checkable
3011 class HasX(Protocol):
3012 x: int
3013
3014 class Foo: ...
3015
3016 f = Foo()
3017 self.assertNotIsInstance(f, HasX)
3018 f.x = 42
3019 self.assertIsInstance(f, HasX)
3020 del f.x
3021 self.assertNotIsInstance(f, HasX)
3022
3023 def test_protocol_checks_after_subscript(self):
3024 class P(Protocol[T]): pass
3025 class C(P[T]): pass
3026 class Other1: pass
3027 class Other2: pass
3028 CA = C[Any]
3029
3030 self.assertNotIsInstance(Other1(), C)
3031 self.assertNotIsSubclass(Other2, C)
3032
3033 class D1(C[Any]): pass
3034 class D2(C[Any]): pass
3035 CI = C[int]
3036
3037 self.assertIsInstance(D1(), C)
3038 self.assertIsSubclass(D2, C)
3039
3040 def test_protocols_support_register(self):
3041 @runtime_checkable
3042 class P(Protocol):
3043 x = 1
3044
3045 class PM(Protocol):
3046 def meth(self): pass
3047
3048 class D(PM): pass
3049
3050 class C: pass
3051
3052 D.register(C)
3053 P.register(C)
3054 self.assertIsInstance(C(), P)
3055 self.assertIsInstance(C(), D)
3056
3057 def test_none_on_non_callable_doesnt_block_implementation(self):
3058 @runtime_checkable
3059 class P(Protocol):
3060 x = 1
3061
3062 class A:
3063 x = 1
3064
3065 class B(A):
3066 x = None
3067
3068 class C:
3069 def __init__(self):
3070 self.x = None
3071
3072 self.assertIsInstance(B(), P)
3073 self.assertIsInstance(C(), P)
3074
3075 def test_none_on_callable_blocks_implementation(self):
3076 @runtime_checkable
3077 class P(Protocol):
3078 def x(self): ...
3079
3080 class A:
3081 def x(self): ...
3082
3083 class B(A):
3084 x = None
3085
3086 class C:
3087 def __init__(self):
3088 self.x = None
3089
3090 self.assertNotIsInstance(B(), P)
3091 self.assertNotIsInstance(C(), P)
3092
3093 def test_non_protocol_subclasses(self):
3094 class P(Protocol):
3095 x = 1
3096
3097 @runtime_checkable
3098 class PR(Protocol):
3099 def meth(self): pass
3100
3101 class NonP(P):
3102 x = 1
3103
3104 class NonPR(PR): pass
3105
3106 class C:
3107 x = 1
3108
3109 class D:
3110 def meth(self): pass
3111
3112 self.assertNotIsInstance(C(), NonP)
3113 self.assertNotIsInstance(D(), NonPR)
3114 self.assertNotIsSubclass(C, NonP)
3115 self.assertNotIsSubclass(D, NonPR)
3116 self.assertIsInstance(NonPR(), PR)
3117 self.assertIsSubclass(NonPR, PR)
3118
3119 def test_custom_subclasshook(self):
3120 class P(Protocol):
3121 x = 1
3122
3123 class OKClass: pass
3124
3125 class BadClass:
3126 x = 1
3127
3128 class C(P):
3129 @classmethod
3130 def __subclasshook__(cls, other):
3131 return other.__name__.startswith("OK")
3132
3133 self.assertIsInstance(OKClass(), C)
3134 self.assertNotIsInstance(BadClass(), C)
3135 self.assertIsSubclass(OKClass, C)
3136 self.assertNotIsSubclass(BadClass, C)
3137
3138 def test_issubclass_fails_correctly(self):
3139 @runtime_checkable
3140 class P(Protocol):
3141 x = 1
3142
3143 class C: pass
3144
3145 with self.assertRaises(TypeError):
3146 issubclass(C(), P)
3147
3148 def test_defining_generic_protocols(self):
3149 T = TypeVar('T')
3150 S = TypeVar('S')
3151
3152 @runtime_checkable
3153 class PR(Protocol[T, S]):
3154 def meth(self): pass
3155
3156 class P(PR[int, T], Protocol[T]):
3157 y = 1
3158
3159 with self.assertRaises(TypeError):
3160 PR[int]
3161 with self.assertRaises(TypeError):
3162 P[int, str]
3163
3164 class C(PR[int, T]): pass
3165
3166 self.assertIsInstance(C[str](), C)
3167
3168 def test_defining_generic_protocols_old_style(self):
3169 T = TypeVar('T')
3170 S = TypeVar('S')
3171
3172 @runtime_checkable
3173 class PR(Protocol, Generic[T, S]):
3174 def meth(self): pass
3175
3176 class P(PR[int, str], Protocol):
3177 y = 1
3178
3179 with self.assertRaises(TypeError):
3180 issubclass(PR[int, str], PR)
3181 self.assertIsSubclass(P, PR)
3182 with self.assertRaises(TypeError):
3183 PR[int]
3184
3185 class P1(Protocol, Generic[T]):
3186 def bar(self, x: T) -> str: ...
3187
3188 class P2(Generic[T], Protocol):
3189 def bar(self, x: T) -> str: ...
3190
3191 @runtime_checkable
3192 class PSub(P1[str], Protocol):
3193 x = 1
3194
3195 class Test:
3196 x = 1
3197
3198 def bar(self, x: str) -> str:
3199 return x
3200
3201 self.assertIsInstance(Test(), PSub)
3202
3203 def test_init_called(self):
3204 T = TypeVar('T')
3205
3206 class P(Protocol[T]): pass
3207
3208 class C(P[T]):
3209 def __init__(self):
3210 self.test = 'OK'
3211
3212 self.assertEqual(C[int]().test, 'OK')
3213
3214 class B:
3215 def __init__(self):
3216 self.test = 'OK'
3217
3218 class D1(B, P[T]):
3219 pass
3220
3221 self.assertEqual(D1[int]().test, 'OK')
3222
3223 class D2(P[T], B):
3224 pass
3225
3226 self.assertEqual(D2[int]().test, 'OK')
3227
3228 def test_new_called(self):
3229 T = TypeVar('T')
3230
3231 class P(Protocol[T]): pass
3232
3233 class C(P[T]):
3234 def __new__(cls, *args):
3235 self = super().__new__(cls, *args)
3236 self.test = 'OK'
3237 return self
3238
3239 self.assertEqual(C[int]().test, 'OK')
3240 with self.assertRaises(TypeError):
3241 C[int](42)
3242 with self.assertRaises(TypeError):
3243 C[int](a=42)
3244
3245 def test_protocols_bad_subscripts(self):
3246 T = TypeVar('T')
3247 S = TypeVar('S')
3248 with self.assertRaises(TypeError):
3249 class P(Protocol[T, T]): pass
3250 with self.assertRaises(TypeError):
3251 class Q(Protocol[int]): pass
3252 with self.assertRaises(TypeError):
3253 class R(Protocol[T], Protocol[S]): pass
3254 with self.assertRaises(TypeError):
3255 class S(typing.Mapping[T, S], Protocol[T]): pass
3256
3257 def test_generic_protocols_repr(self):
3258 T = TypeVar('T')
3259 S = TypeVar('S')
3260
3261 class P(Protocol[T, S]): pass
3262
3263 self.assertTrue(repr(P[T, S]).endswith('P[~T, ~S]'))
3264 self.assertTrue(repr(P[int, str]).endswith('P[int, str]'))
3265
3266 def test_generic_protocols_eq(self):
3267 T = TypeVar('T')
3268 S = TypeVar('S')
3269
3270 class P(Protocol[T, S]): pass
3271
3272 self.assertEqual(P, P)
3273 self.assertEqual(P[int, T], P[int, T])
3274 self.assertEqual(P[T, T][Tuple[T, S]][int, str],
3275 P[Tuple[int, str], Tuple[int, str]])
3276
3277 def test_generic_protocols_special_from_generic(self):
3278 T = TypeVar('T')
3279
3280 class P(Protocol[T]): pass
3281
3282 self.assertEqual(P.__parameters__, (T,))
3283 self.assertEqual(P[int].__parameters__, ())
3284 self.assertEqual(P[int].__args__, (int,))
3285 self.assertIs(P[int].__origin__, P)
3286
3287 def test_generic_protocols_special_from_protocol(self):
3288 @runtime_checkable
3289 class PR(Protocol):
3290 x = 1
3291
3292 class P(Protocol):
3293 def meth(self):
3294 pass
3295
3296 T = TypeVar('T')
3297
3298 class PG(Protocol[T]):
3299 x = 1
3300
3301 def meth(self):
3302 pass
3303
3304 self.assertTrue(P._is_protocol)
3305 self.assertTrue(PR._is_protocol)
3306 self.assertTrue(PG._is_protocol)
3307 self.assertFalse(P._is_runtime_protocol)
3308 self.assertTrue(PR._is_runtime_protocol)
3309 self.assertTrue(PG[int]._is_protocol)
3310 self.assertEqual(typing._get_protocol_attrs(P), {'meth'})
3311 self.assertEqual(typing._get_protocol_attrs(PR), {'x'})
3312 self.assertEqual(frozenset(typing._get_protocol_attrs(PG)),
3313 frozenset({'x', 'meth'}))
3314
3315 def test_no_runtime_deco_on_nominal(self):
3316 with self.assertRaises(TypeError):
3317 @runtime_checkable
3318 class C: pass
3319
3320 class Proto(Protocol):
3321 x = 1
3322
3323 with self.assertRaises(TypeError):
3324 @runtime_checkable
3325 class Concrete(Proto):
3326 pass
3327
3328 def test_none_treated_correctly(self):
3329 @runtime_checkable
3330 class P(Protocol):
3331 x = None # type: int
3332
3333 class B(object): pass
3334
3335 self.assertNotIsInstance(B(), P)
3336
3337 class C:
3338 x = 1
3339
3340 class D:
3341 x = None
3342
3343 self.assertIsInstance(C(), P)
3344 self.assertIsInstance(D(), P)
3345
3346 class CI:
3347 def __init__(self):
3348 self.x = 1
3349
3350 class DI:
3351 def __init__(self):
3352 self.x = None
3353
3354 self.assertIsInstance(CI(), P)
3355 self.assertIsInstance(DI(), P)
3356
3357 def test_protocols_in_unions(self):
3358 class P(Protocol):
3359 x = None # type: int
3360
3361 Alias = typing.Union[typing.Iterable, P]
3362 Alias2 = typing.Union[P, typing.Iterable]
3363 self.assertEqual(Alias, Alias2)
3364
3365 def test_protocols_pickleable(self):
3366 global P, CP # pickle wants to reference the class by name
3367 T = TypeVar('T')
3368
3369 @runtime_checkable
3370 class P(Protocol[T]):
3371 x = 1
3372
3373 class CP(P[int]):
3374 pass
3375
3376 c = CP()
3377 c.foo = 42
3378 c.bar = 'abc'
3379 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
3380 z = pickle.dumps(c, proto)
3381 x = pickle.loads(z)
3382 self.assertEqual(x.foo, 42)
3383 self.assertEqual(x.bar, 'abc')
3384 self.assertEqual(x.x, 1)
3385 self.assertEqual(x.__dict__, {'foo': 42, 'bar': 'abc'})
3386 s = pickle.dumps(P, proto)
3387 D = pickle.loads(s)
3388
3389 class E:
3390 x = 1
3391
3392 self.assertIsInstance(E(), D)
3393
3394 def test_supports_int(self):
3395 self.assertIsSubclass(int, typing.SupportsInt)
3396 self.assertNotIsSubclass(str, typing.SupportsInt)
3397
3398 def test_supports_float(self):
3399 self.assertIsSubclass(float, typing.SupportsFloat)
3400 self.assertNotIsSubclass(str, typing.SupportsFloat)
3401
3402 def test_supports_complex(self):
3403
3404 class C:
3405 def __complex__(self):
3406 return 0j
3407
3408 self.assertIsSubclass(complex, typing.SupportsComplex)
3409 self.assertIsSubclass(C, typing.SupportsComplex)
3410 self.assertNotIsSubclass(str, typing.SupportsComplex)
3411
3412 def test_supports_bytes(self):
3413
3414 class B:
3415 def __bytes__(self):
3416 return b''
3417
3418 self.assertIsSubclass(bytes, typing.SupportsBytes)
3419 self.assertIsSubclass(B, typing.SupportsBytes)
3420 self.assertNotIsSubclass(str, typing.SupportsBytes)
3421
3422 def test_supports_abs(self):
3423 self.assertIsSubclass(float, typing.SupportsAbs)
3424 self.assertIsSubclass(int, typing.SupportsAbs)
3425 self.assertNotIsSubclass(str, typing.SupportsAbs)
3426
3427 def test_supports_round(self):
3428 issubclass(float, typing.SupportsRound)
3429 self.assertIsSubclass(float, typing.SupportsRound)
3430 self.assertIsSubclass(int, typing.SupportsRound)
3431 self.assertNotIsSubclass(str, typing.SupportsRound)
3432
3433 def test_reversible(self):
3434 self.assertIsSubclass(list, typing.Reversible)
3435 self.assertNotIsSubclass(int, typing.Reversible)
3436
3437 def test_supports_index(self):
3438 self.assertIsSubclass(int, typing.SupportsIndex)
3439 self.assertNotIsSubclass(str, typing.SupportsIndex)
3440
3441 def test_bundled_protocol_instance_works(self):
3442 self.assertIsInstance(0, typing.SupportsAbs)
3443 class C1(typing.SupportsInt):
3444 def __int__(self) -> int:
3445 return 42
3446 class C2(C1):
3447 pass
3448 c = C2()
3449 self.assertIsInstance(c, C1)
3450
3451 def test_collections_protocols_allowed(self):
3452 @runtime_checkable
3453 class Custom(collections.abc.Iterable, Protocol):
3454 def close(self): ...
3455
3456 class A: pass
3457 class B:
3458 def __iter__(self):
3459 return []
3460 def close(self):
3461 return 0
3462
3463 self.assertIsSubclass(B, Custom)
3464 self.assertNotIsSubclass(A, Custom)
3465
3466 def test_builtin_protocol_allowlist(self):
3467 with self.assertRaises(TypeError):
3468 class CustomProtocol(TestCase, Protocol):
3469 pass
3470
3471 class CustomContextManager(typing.ContextManager, Protocol):
3472 pass
3473
3474 def test_non_runtime_protocol_isinstance_check(self):
3475 class P(Protocol):
3476 x: int
3477
3478 with self.assertRaisesRegex(TypeError, "@runtime_checkable"):
3479 isinstance(1, P)
3480
3481 def test_super_call_init(self):
3482 class P(Protocol):
3483 x: int
3484
3485 class Foo(P):
3486 def __init__(self):
3487 super().__init__()
3488
3489 Foo() # Previously triggered RecursionError
3490
3491 def test_empty_protocol_decorated_with_final(self):
3492 @final
3493 @runtime_checkable
3494 class EmptyProtocol(Protocol): ...
3495
3496 self.assertIsSubclass(object, EmptyProtocol)
3497 self.assertIsInstance(object(), EmptyProtocol)
3498
3499 def test_protocol_decorated_with_final_callable_members(self):
3500 @final
3501 @runtime_checkable
3502 class ProtocolWithMethod(Protocol):
3503 def startswith(self, string: str) -> bool: ...
3504
3505 self.assertIsSubclass(str, ProtocolWithMethod)
3506 self.assertNotIsSubclass(int, ProtocolWithMethod)
3507 self.assertIsInstance('foo', ProtocolWithMethod)
3508 self.assertNotIsInstance(42, ProtocolWithMethod)
3509
3510 def test_protocol_decorated_with_final_noncallable_members(self):
3511 @final
3512 @runtime_checkable
3513 class ProtocolWithNonCallableMember(Protocol):
3514 x: int
3515
3516 class Foo:
3517 x = 42
3518
3519 only_callable_members_please = (
3520 r"Protocols with non-method members don't support issubclass()"
3521 )
3522
3523 with self.assertRaisesRegex(TypeError, only_callable_members_please):
3524 issubclass(Foo, ProtocolWithNonCallableMember)
3525
3526 with self.assertRaisesRegex(TypeError, only_callable_members_please):
3527 issubclass(int, ProtocolWithNonCallableMember)
3528
3529 self.assertIsInstance(Foo(), ProtocolWithNonCallableMember)
3530 self.assertNotIsInstance(42, ProtocolWithNonCallableMember)
3531
3532 def test_protocol_decorated_with_final_mixed_members(self):
3533 @final
3534 @runtime_checkable
3535 class ProtocolWithMixedMembers(Protocol):
3536 x: int
3537 def method(self) -> None: ...
3538
3539 class Foo:
3540 x = 42
3541 def method(self) -> None: ...
3542
3543 only_callable_members_please = (
3544 r"Protocols with non-method members don't support issubclass()"
3545 )
3546
3547 with self.assertRaisesRegex(TypeError, only_callable_members_please):
3548 issubclass(Foo, ProtocolWithMixedMembers)
3549
3550 with self.assertRaisesRegex(TypeError, only_callable_members_please):
3551 issubclass(int, ProtocolWithMixedMembers)
3552
3553 self.assertIsInstance(Foo(), ProtocolWithMixedMembers)
3554 self.assertNotIsInstance(42, ProtocolWithMixedMembers)
3555
3556
3557 class GenericTests(BaseTestCase):
3558
3559 def test_basics(self):
3560 X = SimpleMapping[str, Any]
3561 self.assertEqual(X.__parameters__, ())
3562 with self.assertRaises(TypeError):
3563 X[str]
3564 with self.assertRaises(TypeError):
3565 X[str, str]
3566 Y = SimpleMapping[XK, str]
3567 self.assertEqual(Y.__parameters__, (XK,))
3568 Y[str]
3569 with self.assertRaises(TypeError):
3570 Y[str, str]
3571 SM1 = SimpleMapping[str, int]
3572 with self.assertRaises(TypeError):
3573 issubclass(SM1, SimpleMapping)
3574 self.assertIsInstance(SM1(), SimpleMapping)
3575 T = TypeVar("T")
3576 self.assertEqual(List[list[T] | float].__parameters__, (T,))
3577
3578 def test_generic_errors(self):
3579 T = TypeVar('T')
3580 S = TypeVar('S')
3581 with self.assertRaises(TypeError):
3582 Generic[T][T]
3583 with self.assertRaises(TypeError):
3584 Generic[T][S]
3585 with self.assertRaises(TypeError):
3586 class C(Generic[T], Generic[T]): ...
3587 with self.assertRaises(TypeError):
3588 isinstance([], List[int])
3589 with self.assertRaises(TypeError):
3590 issubclass(list, List[int])
3591 with self.assertRaises(TypeError):
3592 class NewGeneric(Generic): ...
3593 with self.assertRaises(TypeError):
3594 class MyGeneric(Generic[T], Generic[S]): ...
3595 with self.assertRaises(TypeError):
3596 class MyGeneric2(List[T], Generic[S]): ...
3597 with self.assertRaises(TypeError):
3598 Generic[()]
3599 class D(Generic[T]): pass
3600 with self.assertRaises(TypeError):
3601 D[()]
3602
3603 def test_init(self):
3604 T = TypeVar('T')
3605 S = TypeVar('S')
3606 with self.assertRaises(TypeError):
3607 Generic[T, T]
3608 with self.assertRaises(TypeError):
3609 Generic[T, S, T]
3610
3611 def test_init_subclass(self):
3612 class X(typing.Generic[T]):
3613 def __init_subclass__(cls, **kwargs):
3614 super().__init_subclass__(**kwargs)
3615 cls.attr = 42
3616 class Y(X):
3617 pass
3618 self.assertEqual(Y.attr, 42)
3619 with self.assertRaises(AttributeError):
3620 X.attr
3621 X.attr = 1
3622 Y.attr = 2
3623 class Z(Y):
3624 pass
3625 class W(X[int]):
3626 pass
3627 self.assertEqual(Y.attr, 2)
3628 self.assertEqual(Z.attr, 42)
3629 self.assertEqual(W.attr, 42)
3630
3631 def test_repr(self):
3632 self.assertEqual(repr(SimpleMapping),
3633 f"<class '{__name__}.SimpleMapping'>")
3634 self.assertEqual(repr(MySimpleMapping),
3635 f"<class '{__name__}.MySimpleMapping'>")
3636
3637 def test_chain_repr(self):
3638 T = TypeVar('T')
3639 S = TypeVar('S')
3640
3641 class C(Generic[T]):
3642 pass
3643
3644 X = C[Tuple[S, T]]
3645 self.assertEqual(X, C[Tuple[S, T]])
3646 self.assertNotEqual(X, C[Tuple[T, S]])
3647
3648 Y = X[T, int]
3649 self.assertEqual(Y, X[T, int])
3650 self.assertNotEqual(Y, X[S, int])
3651 self.assertNotEqual(Y, X[T, str])
3652
3653 Z = Y[str]
3654 self.assertEqual(Z, Y[str])
3655 self.assertNotEqual(Z, Y[int])
3656 self.assertNotEqual(Z, Y[T])
3657
3658 self.assertTrue(str(Z).endswith(
3659 '.C[typing.Tuple[str, int]]'))
3660
3661 def test_new_repr(self):
3662 T = TypeVar('T')
3663 U = TypeVar('U', covariant=True)
3664 S = TypeVar('S')
3665
3666 self.assertEqual(repr(List), 'typing.List')
3667 self.assertEqual(repr(List[T]), 'typing.List[~T]')
3668 self.assertEqual(repr(List[U]), 'typing.List[+U]')
3669 self.assertEqual(repr(List[S][T][int]), 'typing.List[int]')
3670 self.assertEqual(repr(List[int]), 'typing.List[int]')
3671
3672 def test_new_repr_complex(self):
3673 T = TypeVar('T')
3674 TS = TypeVar('TS')
3675
3676 self.assertEqual(repr(typing.Mapping[T, TS][TS, T]), 'typing.Mapping[~TS, ~T]')
3677 self.assertEqual(repr(List[Tuple[T, TS]][int, T]),
3678 'typing.List[typing.Tuple[int, ~T]]')
3679 self.assertEqual(
3680 repr(List[Tuple[T, T]][List[int]]),
3681 'typing.List[typing.Tuple[typing.List[int], typing.List[int]]]'
3682 )
3683
3684 def test_new_repr_bare(self):
3685 T = TypeVar('T')
3686 self.assertEqual(repr(Generic[T]), 'typing.Generic[~T]')
3687 self.assertEqual(repr(typing.Protocol[T]), 'typing.Protocol[~T]')
3688 class C(typing.Dict[Any, Any]): ...
3689 # this line should just work
3690 repr(C.__mro__)
3691
3692 def test_dict(self):
3693 T = TypeVar('T')
3694
3695 class B(Generic[T]):
3696 pass
3697
3698 b = B()
3699 b.foo = 42
3700 self.assertEqual(b.__dict__, {'foo': 42})
3701
3702 class C(B[int]):
3703 pass
3704
3705 c = C()
3706 c.bar = 'abc'
3707 self.assertEqual(c.__dict__, {'bar': 'abc'})
3708
3709 def test_setattr_exceptions(self):
3710 T = TypeVar("T")
3711 class Immutable(Generic[T]):
3712 def __setattr__(self, key, value):
3713 raise RuntimeError("immutable")
3714
3715 # gh-115165: This used to cause RuntimeError to be raised
3716 # when we tried to set `__orig_class__` on the `Immutable` instance
3717 # returned by the `Immutable[int]()` call
3718 self.assertIsInstance(Immutable[int](), Immutable)
3719
3720 def test_subscripted_generics_as_proxies(self):
3721 T = TypeVar('T')
3722 class C(Generic[T]):
3723 x = 'def'
3724 self.assertEqual(C[int].x, 'def')
3725 self.assertEqual(C[C[int]].x, 'def')
3726 C[C[int]].x = 'changed'
3727 self.assertEqual(C.x, 'changed')
3728 self.assertEqual(C[str].x, 'changed')
3729 C[List[str]].z = 'new'
3730 self.assertEqual(C.z, 'new')
3731 self.assertEqual(C[Tuple[int]].z, 'new')
3732
3733 self.assertEqual(C().x, 'changed')
3734 self.assertEqual(C[Tuple[str]]().z, 'new')
3735
3736 class D(C[T]):
3737 pass
3738 self.assertEqual(D[int].x, 'changed')
3739 self.assertEqual(D.z, 'new')
3740 D.z = 'from derived z'
3741 D[int].x = 'from derived x'
3742 self.assertEqual(C.x, 'changed')
3743 self.assertEqual(C[int].z, 'new')
3744 self.assertEqual(D.x, 'from derived x')
3745 self.assertEqual(D[str].z, 'from derived z')
3746
3747 def test_abc_registry_kept(self):
3748 T = TypeVar('T')
3749 class C(collections.abc.Mapping, Generic[T]): ...
3750 C.register(int)
3751 self.assertIsInstance(1, C)
3752 C[int]
3753 self.assertIsInstance(1, C)
3754 C._abc_registry_clear()
3755 C._abc_caches_clear() # To keep refleak hunting mode clean
3756
3757 def test_false_subclasses(self):
3758 class MyMapping(MutableMapping[str, str]): pass
3759 self.assertNotIsInstance({}, MyMapping)
3760 self.assertNotIsSubclass(dict, MyMapping)
3761
3762 def test_abc_bases(self):
3763 class MM(MutableMapping[str, str]):
3764 def __getitem__(self, k):
3765 return None
3766 def __setitem__(self, k, v):
3767 pass
3768 def __delitem__(self, k):
3769 pass
3770 def __iter__(self):
3771 return iter(())
3772 def __len__(self):
3773 return 0
3774 # this should just work
3775 MM().update()
3776 self.assertIsInstance(MM(), collections.abc.MutableMapping)
3777 self.assertIsInstance(MM(), MutableMapping)
3778 self.assertNotIsInstance(MM(), List)
3779 self.assertNotIsInstance({}, MM)
3780
3781 def test_multiple_bases(self):
3782 class MM1(MutableMapping[str, str], collections.abc.MutableMapping):
3783 pass
3784 class MM2(collections.abc.MutableMapping, MutableMapping[str, str]):
3785 pass
3786 self.assertEqual(MM2.__bases__, (collections.abc.MutableMapping, Generic))
3787
3788 def test_orig_bases(self):
3789 T = TypeVar('T')
3790 class C(typing.Dict[str, T]): ...
3791 self.assertEqual(C.__orig_bases__, (typing.Dict[str, T],))
3792
3793 def test_naive_runtime_checks(self):
3794 def naive_dict_check(obj, tp):
3795 # Check if a dictionary conforms to Dict type
3796 if len(tp.__parameters__) > 0:
3797 raise NotImplementedError
3798 if tp.__args__:
3799 KT, VT = tp.__args__
3800 return all(
3801 isinstance(k, KT) and isinstance(v, VT)
3802 for k, v in obj.items()
3803 )
3804 self.assertTrue(naive_dict_check({'x': 1}, typing.Dict[str, int]))
3805 self.assertFalse(naive_dict_check({1: 'x'}, typing.Dict[str, int]))
3806 with self.assertRaises(NotImplementedError):
3807 naive_dict_check({1: 'x'}, typing.Dict[str, T])
3808
3809 def naive_generic_check(obj, tp):
3810 # Check if an instance conforms to the generic class
3811 if not hasattr(obj, '__orig_class__'):
3812 raise NotImplementedError
3813 return obj.__orig_class__ == tp
3814 class Node(Generic[T]): ...
3815 self.assertTrue(naive_generic_check(Node[int](), Node[int]))
3816 self.assertFalse(naive_generic_check(Node[str](), Node[int]))
3817 self.assertFalse(naive_generic_check(Node[str](), List))
3818 with self.assertRaises(NotImplementedError):
3819 naive_generic_check([1, 2, 3], Node[int])
3820
3821 def naive_list_base_check(obj, tp):
3822 # Check if list conforms to a List subclass
3823 return all(isinstance(x, tp.__orig_bases__[0].__args__[0])
3824 for x in obj)
3825 class C(List[int]): ...
3826 self.assertTrue(naive_list_base_check([1, 2, 3], C))
3827 self.assertFalse(naive_list_base_check(['a', 'b'], C))
3828
3829 def test_multi_subscr_base(self):
3830 T = TypeVar('T')
3831 U = TypeVar('U')
3832 V = TypeVar('V')
3833 class C(List[T][U][V]): ...
3834 class D(C, List[T][U][V]): ...
3835 self.assertEqual(C.__parameters__, (V,))
3836 self.assertEqual(D.__parameters__, (V,))
3837 self.assertEqual(C[int].__parameters__, ())
3838 self.assertEqual(D[int].__parameters__, ())
3839 self.assertEqual(C[int].__args__, (int,))
3840 self.assertEqual(D[int].__args__, (int,))
3841 self.assertEqual(C.__bases__, (list, Generic))
3842 self.assertEqual(D.__bases__, (C, list, Generic))
3843 self.assertEqual(C.__orig_bases__, (List[T][U][V],))
3844 self.assertEqual(D.__orig_bases__, (C, List[T][U][V]))
3845
3846 def test_subscript_meta(self):
3847 T = TypeVar('T')
3848 class Meta(type): ...
3849 self.assertEqual(Type[Meta], Type[Meta])
3850 self.assertEqual(Union[T, int][Meta], Union[Meta, int])
3851 self.assertEqual(Callable[..., Meta].__args__, (Ellipsis, Meta))
3852
3853 def test_generic_hashes(self):
3854 class A(Generic[T]):
3855 ...
3856
3857 class B(Generic[T]):
3858 class A(Generic[T]):
3859 ...
3860
3861 self.assertEqual(A, A)
3862 self.assertEqual(mod_generics_cache.A[str], mod_generics_cache.A[str])
3863 self.assertEqual(B.A, B.A)
3864 self.assertEqual(mod_generics_cache.B.A[B.A[str]],
3865 mod_generics_cache.B.A[B.A[str]])
3866
3867 self.assertNotEqual(A, B.A)
3868 self.assertNotEqual(A, mod_generics_cache.A)
3869 self.assertNotEqual(A, mod_generics_cache.B.A)
3870 self.assertNotEqual(B.A, mod_generics_cache.A)
3871 self.assertNotEqual(B.A, mod_generics_cache.B.A)
3872
3873 self.assertNotEqual(A[str], B.A[str])
3874 self.assertNotEqual(A[List[Any]], B.A[List[Any]])
3875 self.assertNotEqual(A[str], mod_generics_cache.A[str])
3876 self.assertNotEqual(A[str], mod_generics_cache.B.A[str])
3877 self.assertNotEqual(B.A[int], mod_generics_cache.A[int])
3878 self.assertNotEqual(B.A[List[Any]], mod_generics_cache.B.A[List[Any]])
3879
3880 self.assertNotEqual(Tuple[A[str]], Tuple[B.A[str]])
3881 self.assertNotEqual(Tuple[A[List[Any]]], Tuple[B.A[List[Any]]])
3882 self.assertNotEqual(Union[str, A[str]], Union[str, mod_generics_cache.A[str]])
3883 self.assertNotEqual(Union[A[str], A[str]],
3884 Union[A[str], mod_generics_cache.A[str]])
3885 self.assertNotEqual(typing.FrozenSet[A[str]],
3886 typing.FrozenSet[mod_generics_cache.B.A[str]])
3887
3888 self.assertTrue(repr(Tuple[A[str]]).endswith('<locals>.A[str]]'))
3889 self.assertTrue(repr(Tuple[B.A[str]]).endswith('<locals>.B.A[str]]'))
3890 self.assertTrue(repr(Tuple[mod_generics_cache.A[str]])
3891 .endswith('mod_generics_cache.A[str]]'))
3892 self.assertTrue(repr(Tuple[mod_generics_cache.B.A[str]])
3893 .endswith('mod_generics_cache.B.A[str]]'))
3894
3895 def test_extended_generic_rules_eq(self):
3896 T = TypeVar('T')
3897 U = TypeVar('U')
3898 self.assertEqual(Tuple[T, T][int], Tuple[int, int])
3899 self.assertEqual(typing.Iterable[Tuple[T, T]][T], typing.Iterable[Tuple[T, T]])
3900 with self.assertRaises(TypeError):
3901 Tuple[T, int][()]
3902
3903 self.assertEqual(Union[T, int][int], int)
3904 self.assertEqual(Union[T, U][int, Union[int, str]], Union[int, str])
3905 class Base: ...
3906 class Derived(Base): ...
3907 self.assertEqual(Union[T, Base][Union[Base, Derived]], Union[Base, Derived])
3908 self.assertEqual(Callable[[T], T][KT], Callable[[KT], KT])
3909 self.assertEqual(Callable[..., List[T]][int], Callable[..., List[int]])
3910
3911 def test_extended_generic_rules_repr(self):
3912 T = TypeVar('T')
3913 self.assertEqual(repr(Union[Tuple, Callable]).replace('typing.', ''),
3914 'Union[Tuple, Callable]')
3915 self.assertEqual(repr(Union[Tuple, Tuple[int]]).replace('typing.', ''),
3916 'Union[Tuple, Tuple[int]]')
3917 self.assertEqual(repr(Callable[..., Optional[T]][int]).replace('typing.', ''),
3918 'Callable[..., Optional[int]]')
3919 self.assertEqual(repr(Callable[[], List[T]][int]).replace('typing.', ''),
3920 'Callable[[], List[int]]')
3921
3922 def test_generic_forward_ref(self):
3923 def foobar(x: List[List['CC']]): ...
3924 def foobar2(x: list[list[ForwardRef('CC')]]): ...
3925 def foobar3(x: list[ForwardRef('CC | int')] | int): ...
3926 class CC: ...
3927 self.assertEqual(
3928 get_type_hints(foobar, globals(), locals()),
3929 {'x': List[List[CC]]}
3930 )
3931 self.assertEqual(
3932 get_type_hints(foobar2, globals(), locals()),
3933 {'x': list[list[CC]]}
3934 )
3935 self.assertEqual(
3936 get_type_hints(foobar3, globals(), locals()),
3937 {'x': list[CC | int] | int}
3938 )
3939
3940 T = TypeVar('T')
3941 AT = Tuple[T, ...]
3942 def barfoo(x: AT): ...
3943 self.assertIs(get_type_hints(barfoo, globals(), locals())['x'], AT)
3944 CT = Callable[..., List[T]]
3945 def barfoo2(x: CT): ...
3946 self.assertIs(get_type_hints(barfoo2, globals(), locals())['x'], CT)
3947
3948 def test_generic_pep585_forward_ref(self):
3949 # See https://bugs.python.org/issue41370
3950
3951 class C1:
3952 a: list['C1']
3953 self.assertEqual(
3954 get_type_hints(C1, globals(), locals()),
3955 {'a': list[C1]}
3956 )
3957
3958 class C2:
3959 a: dict['C1', list[List[list['C2']]]]
3960 self.assertEqual(
3961 get_type_hints(C2, globals(), locals()),
3962 {'a': dict[C1, list[List[list[C2]]]]}
3963 )
3964
3965 # Test stringified annotations
3966 scope = {}
3967 exec(textwrap.dedent('''
3968 from __future__ import annotations
3969 class C3:
3970 a: List[list["C2"]]
3971 '''), scope)
3972 C3 = scope['C3']
3973 self.assertEqual(C3.__annotations__['a'], "List[list['C2']]")
3974 self.assertEqual(
3975 get_type_hints(C3, globals(), locals()),
3976 {'a': List[list[C2]]}
3977 )
3978
3979 # Test recursive types
3980 X = list["X"]
3981 def f(x: X): ...
3982 self.assertEqual(
3983 get_type_hints(f, globals(), locals()),
3984 {'x': list[list[ForwardRef('X')]]}
3985 )
3986
3987 def test_extended_generic_rules_subclassing(self):
3988 class T1(Tuple[T, KT]): ...
3989 class T2(Tuple[T, ...]): ...
3990 class C1(typing.Container[T]):
3991 def __contains__(self, item):
3992 return False
3993
3994 self.assertEqual(T1.__parameters__, (T, KT))
3995 self.assertEqual(T1[int, str].__args__, (int, str))
3996 self.assertEqual(T1[int, T].__origin__, T1)
3997
3998 self.assertEqual(T2.__parameters__, (T,))
3999 # These don't work because of tuple.__class_item__
4000 ## with self.assertRaises(TypeError):
4001 ## T1[int]
4002 ## with self.assertRaises(TypeError):
4003 ## T2[int, str]
4004
4005 self.assertEqual(repr(C1[int]).split('.')[-1], 'C1[int]')
4006 self.assertEqual(C1.__parameters__, (T,))
4007 self.assertIsInstance(C1(), collections.abc.Container)
4008 self.assertIsSubclass(C1, collections.abc.Container)
4009 self.assertIsInstance(T1(), tuple)
4010 self.assertIsSubclass(T2, tuple)
4011 with self.assertRaises(TypeError):
4012 issubclass(Tuple[int, ...], typing.Sequence)
4013 with self.assertRaises(TypeError):
4014 issubclass(Tuple[int, ...], typing.Iterable)
4015
4016 def test_fail_with_bare_union(self):
4017 with self.assertRaises(TypeError):
4018 List[Union]
4019 with self.assertRaises(TypeError):
4020 Tuple[Optional]
4021 with self.assertRaises(TypeError):
4022 ClassVar[ClassVar[int]]
4023 with self.assertRaises(TypeError):
4024 List[ClassVar[int]]
4025
4026 def test_fail_with_bare_generic(self):
4027 T = TypeVar('T')
4028 with self.assertRaises(TypeError):
4029 List[Generic]
4030 with self.assertRaises(TypeError):
4031 Tuple[Generic[T]]
4032 with self.assertRaises(TypeError):
4033 List[typing.Protocol]
4034
4035 def test_type_erasure_special(self):
4036 T = TypeVar('T')
4037 # this is the only test that checks type caching
4038 self.clear_caches()
4039 class MyTup(Tuple[T, T]): ...
4040 self.assertIs(MyTup[int]().__class__, MyTup)
4041 self.assertEqual(MyTup[int]().__orig_class__, MyTup[int])
4042 class MyDict(typing.Dict[T, T]): ...
4043 self.assertIs(MyDict[int]().__class__, MyDict)
4044 self.assertEqual(MyDict[int]().__orig_class__, MyDict[int])
4045 class MyDef(typing.DefaultDict[str, T]): ...
4046 self.assertIs(MyDef[int]().__class__, MyDef)
4047 self.assertEqual(MyDef[int]().__orig_class__, MyDef[int])
4048 class MyChain(typing.ChainMap[str, T]): ...
4049 self.assertIs(MyChain[int]().__class__, MyChain)
4050 self.assertEqual(MyChain[int]().__orig_class__, MyChain[int])
4051
4052 def test_all_repr_eq_any(self):
4053 objs = (getattr(typing, el) for el in typing.__all__)
4054 for obj in objs:
4055 self.assertNotEqual(repr(obj), '')
4056 self.assertEqual(obj, obj)
4057 if (getattr(obj, '__parameters__', None)
4058 and not isinstance(obj, typing.TypeVar)
4059 and isinstance(obj.__parameters__, tuple)
4060 and len(obj.__parameters__) == 1):
4061 self.assertEqual(obj[Any].__args__, (Any,))
4062 if isinstance(obj, type):
4063 for base in obj.__mro__:
4064 self.assertNotEqual(repr(base), '')
4065 self.assertEqual(base, base)
4066
4067 def test_pickle(self):
4068 global C # pickle wants to reference the class by name
4069 T = TypeVar('T')
4070
4071 class B(Generic[T]):
4072 pass
4073
4074 class C(B[int]):
4075 pass
4076
4077 c = C()
4078 c.foo = 42
4079 c.bar = 'abc'
4080 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
4081 z = pickle.dumps(c, proto)
4082 x = pickle.loads(z)
4083 self.assertEqual(x.foo, 42)
4084 self.assertEqual(x.bar, 'abc')
4085 self.assertEqual(x.__dict__, {'foo': 42, 'bar': 'abc'})
4086 samples = [Any, Union, Tuple, Callable, ClassVar,
4087 Union[int, str], ClassVar[List], Tuple[int, ...], Tuple[()],
4088 Callable[[str], bytes],
4089 typing.DefaultDict, typing.FrozenSet[int]]
4090 for s in samples:
4091 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
4092 z = pickle.dumps(s, proto)
4093 x = pickle.loads(z)
4094 self.assertEqual(s, x)
4095 more_samples = [List, typing.Iterable, typing.Type, List[int],
4096 typing.Type[typing.Mapping], typing.AbstractSet[Tuple[int, str]]]
4097 for s in more_samples:
4098 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
4099 z = pickle.dumps(s, proto)
4100 x = pickle.loads(z)
4101 self.assertEqual(s, x)
4102
4103 def test_copy_and_deepcopy(self):
4104 T = TypeVar('T')
4105 class Node(Generic[T]): ...
4106 things = [Union[T, int], Tuple[T, int], Tuple[()],
4107 Callable[..., T], Callable[[int], int],
4108 Tuple[Any, Any], Node[T], Node[int], Node[Any], typing.Iterable[T],
4109 typing.Iterable[Any], typing.Iterable[int], typing.Dict[int, str],
4110 typing.Dict[T, Any], ClassVar[int], ClassVar[List[T]], Tuple['T', 'T'],
4111 Union['T', int], List['T'], typing.Mapping['T', int]]
4112 for t in things + [Any]:
4113 self.assertEqual(t, copy(t))
4114 self.assertEqual(t, deepcopy(t))
4115
4116 def test_immutability_by_copy_and_pickle(self):
4117 # Special forms like Union, Any, etc., generic aliases to containers like List,
4118 # Mapping, etc., and type variabcles are considered immutable by copy and pickle.
4119 global TP, TPB, TPV, PP # for pickle
4120 TP = TypeVar('TP')
4121 TPB = TypeVar('TPB', bound=int)
4122 TPV = TypeVar('TPV', bytes, str)
4123 PP = ParamSpec('PP')
4124 for X in [TP, TPB, TPV, PP,
4125 List, typing.Mapping, ClassVar, typing.Iterable,
4126 Union, Any, Tuple, Callable]:
4127 with self.subTest(thing=X):
4128 self.assertIs(copy(X), X)
4129 self.assertIs(deepcopy(X), X)
4130 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
4131 self.assertIs(pickle.loads(pickle.dumps(X, proto)), X)
4132 del TP, TPB, TPV, PP
4133
4134 # Check that local type variables are copyable.
4135 TL = TypeVar('TL')
4136 TLB = TypeVar('TLB', bound=int)
4137 TLV = TypeVar('TLV', bytes, str)
4138 PL = ParamSpec('PL')
4139 for X in [TL, TLB, TLV, PL]:
4140 with self.subTest(thing=X):
4141 self.assertIs(copy(X), X)
4142 self.assertIs(deepcopy(X), X)
4143
4144 def test_copy_generic_instances(self):
4145 T = TypeVar('T')
4146 class C(Generic[T]):
4147 def __init__(self, attr: T) -> None:
4148 self.attr = attr
4149
4150 c = C(42)
4151 self.assertEqual(copy(c).attr, 42)
4152 self.assertEqual(deepcopy(c).attr, 42)
4153 self.assertIsNot(copy(c), c)
4154 self.assertIsNot(deepcopy(c), c)
4155 c.attr = 1
4156 self.assertEqual(copy(c).attr, 1)
4157 self.assertEqual(deepcopy(c).attr, 1)
4158 ci = C[int](42)
4159 self.assertEqual(copy(ci).attr, 42)
4160 self.assertEqual(deepcopy(ci).attr, 42)
4161 self.assertIsNot(copy(ci), ci)
4162 self.assertIsNot(deepcopy(ci), ci)
4163 ci.attr = 1
4164 self.assertEqual(copy(ci).attr, 1)
4165 self.assertEqual(deepcopy(ci).attr, 1)
4166 self.assertEqual(ci.__orig_class__, C[int])
4167
4168 def test_weakref_all(self):
4169 T = TypeVar('T')
4170 things = [Any, Union[T, int], Callable[..., T], Tuple[Any, Any],
4171 Optional[List[int]], typing.Mapping[int, str],
4172 typing.Match[bytes], typing.Iterable['whatever']]
4173 for t in things:
4174 self.assertEqual(weakref.ref(t)(), t)
4175
4176 def test_parameterized_slots(self):
4177 T = TypeVar('T')
4178 class C(Generic[T]):
4179 __slots__ = ('potato',)
4180
4181 c = C()
4182 c_int = C[int]()
4183
4184 c.potato = 0
4185 c_int.potato = 0
4186 with self.assertRaises(AttributeError):
4187 c.tomato = 0
4188 with self.assertRaises(AttributeError):
4189 c_int.tomato = 0
4190
4191 def foo(x: C['C']): ...
4192 self.assertEqual(get_type_hints(foo, globals(), locals())['x'], C[C])
4193 self.assertEqual(copy(C[int]), deepcopy(C[int]))
4194
4195 def test_parameterized_slots_dict(self):
4196 T = TypeVar('T')
4197 class D(Generic[T]):
4198 __slots__ = {'banana': 42}
4199
4200 d = D()
4201 d_int = D[int]()
4202
4203 d.banana = 'yes'
4204 d_int.banana = 'yes'
4205 with self.assertRaises(AttributeError):
4206 d.foobar = 'no'
4207 with self.assertRaises(AttributeError):
4208 d_int.foobar = 'no'
4209
4210 def test_errors(self):
4211 with self.assertRaises(TypeError):
4212 B = SimpleMapping[XK, Any]
4213
4214 class C(Generic[B]):
4215 pass
4216
4217 def test_repr_2(self):
4218 class C(Generic[T]):
4219 pass
4220
4221 self.assertEqual(C.__module__, __name__)
4222 self.assertEqual(C.__qualname__,
4223 'GenericTests.test_repr_2.<locals>.C')
4224 X = C[int]
4225 self.assertEqual(X.__module__, __name__)
4226 self.assertEqual(repr(X).split('.')[-1], 'C[int]')
4227
4228 class Y(C[int]):
4229 pass
4230
4231 self.assertEqual(Y.__module__, __name__)
4232 self.assertEqual(Y.__qualname__,
4233 'GenericTests.test_repr_2.<locals>.Y')
4234
4235 def test_eq_1(self):
4236 self.assertEqual(Generic, Generic)
4237 self.assertEqual(Generic[T], Generic[T])
4238 self.assertNotEqual(Generic[KT], Generic[VT])
4239
4240 def test_eq_2(self):
4241
4242 class A(Generic[T]):
4243 pass
4244
4245 class B(Generic[T]):
4246 pass
4247
4248 self.assertEqual(A, A)
4249 self.assertNotEqual(A, B)
4250 self.assertEqual(A[T], A[T])
4251 self.assertNotEqual(A[T], B[T])
4252
4253 def test_multiple_inheritance(self):
4254
4255 class A(Generic[T, VT]):
4256 pass
4257
4258 class B(Generic[KT, T]):
4259 pass
4260
4261 class C(A[T, VT], Generic[VT, T, KT], B[KT, T]):
4262 pass
4263
4264 self.assertEqual(C.__parameters__, (VT, T, KT))
4265
4266 def test_multiple_inheritance_special(self):
4267 S = TypeVar('S')
4268 class B(Generic[S]): ...
4269 class C(List[int], B): ...
4270 self.assertEqual(C.__mro__, (C, list, B, Generic, object))
4271
4272 def test_init_subclass_super_called(self):
4273 class FinalException(Exception):
4274 pass
4275
4276 class Final:
4277 def __init_subclass__(cls, **kwargs) -> None:
4278 for base in cls.__bases__:
4279 if base is not Final and issubclass(base, Final):
4280 raise FinalException(base)
4281 super().__init_subclass__(**kwargs)
4282 class Test(Generic[T], Final):
4283 pass
4284 with self.assertRaises(FinalException):
4285 class Subclass(Test):
4286 pass
4287 with self.assertRaises(FinalException):
4288 class Subclass2(Test[int]):
4289 pass
4290
4291 def test_nested(self):
4292
4293 G = Generic
4294
4295 class Visitor(G[T]):
4296
4297 a = None
4298
4299 def set(self, a: T):
4300 self.a = a
4301
4302 def get(self):
4303 return self.a
4304
4305 def visit(self) -> T:
4306 return self.a
4307
4308 V = Visitor[typing.List[int]]
4309
4310 class IntListVisitor(V):
4311
4312 def append(self, x: int):
4313 self.a.append(x)
4314
4315 a = IntListVisitor()
4316 a.set([])
4317 a.append(1)
4318 a.append(42)
4319 self.assertEqual(a.get(), [1, 42])
4320
4321 def test_type_erasure(self):
4322 T = TypeVar('T')
4323
4324 class Node(Generic[T]):
4325 def __init__(self, label: T,
4326 left: 'Node[T]' = None,
4327 right: 'Node[T]' = None):
4328 self.label = label # type: T
4329 self.left = left # type: Optional[Node[T]]
4330 self.right = right # type: Optional[Node[T]]
4331
4332 def foo(x: T):
4333 a = Node(x)
4334 b = Node[T](x)
4335 c = Node[Any](x)
4336 self.assertIs(type(a), Node)
4337 self.assertIs(type(b), Node)
4338 self.assertIs(type(c), Node)
4339 self.assertEqual(a.label, x)
4340 self.assertEqual(b.label, x)
4341 self.assertEqual(c.label, x)
4342
4343 foo(42)
4344
4345 def test_implicit_any(self):
4346 T = TypeVar('T')
4347
4348 class C(Generic[T]):
4349 pass
4350
4351 class D(C):
4352 pass
4353
4354 self.assertEqual(D.__parameters__, ())
4355
4356 with self.assertRaises(TypeError):
4357 D[int]
4358 with self.assertRaises(TypeError):
4359 D[Any]
4360 with self.assertRaises(TypeError):
4361 D[T]
4362
4363 def test_new_with_args(self):
4364
4365 class A(Generic[T]):
4366 pass
4367
4368 class B:
4369 def __new__(cls, arg):
4370 # call object
4371 obj = super().__new__(cls)
4372 obj.arg = arg
4373 return obj
4374
4375 # mro: C, A, Generic, B, object
4376 class C(A, B):
4377 pass
4378
4379 c = C('foo')
4380 self.assertEqual(c.arg, 'foo')
4381
4382 def test_new_with_args2(self):
4383
4384 class A:
4385 def __init__(self, arg):
4386 self.from_a = arg
4387 # call object
4388 super().__init__()
4389
4390 # mro: C, Generic, A, object
4391 class C(Generic[T], A):
4392 def __init__(self, arg):
4393 self.from_c = arg
4394 # call Generic
4395 super().__init__(arg)
4396
4397 c = C('foo')
4398 self.assertEqual(c.from_a, 'foo')
4399 self.assertEqual(c.from_c, 'foo')
4400
4401 def test_new_no_args(self):
4402
4403 class A(Generic[T]):
4404 pass
4405
4406 with self.assertRaises(TypeError):
4407 A('foo')
4408
4409 class B:
4410 def __new__(cls):
4411 # call object
4412 obj = super().__new__(cls)
4413 obj.from_b = 'b'
4414 return obj
4415
4416 # mro: C, A, Generic, B, object
4417 class C(A, B):
4418 def __init__(self, arg):
4419 self.arg = arg
4420
4421 def __new__(cls, arg):
4422 # call A
4423 obj = super().__new__(cls)
4424 obj.from_c = 'c'
4425 return obj
4426
4427 c = C('foo')
4428 self.assertEqual(c.arg, 'foo')
4429 self.assertEqual(c.from_b, 'b')
4430 self.assertEqual(c.from_c, 'c')
4431
4432 def test_subclass_special_form(self):
4433 for obj in (
4434 ClassVar[int],
4435 Final[int],
4436 Union[int, float],
4437 Optional[int],
4438 Literal[1, 2],
4439 Concatenate[int, ParamSpec("P")],
4440 TypeGuard[int],
4441 ):
4442 with self.subTest(msg=obj):
4443 with self.assertRaisesRegex(
4444 TypeError, f'^{re.escape(f"Cannot subclass {obj!r}")}$'
4445 ):
4446 class Foo(obj):
4447 pass
4448
4449 def test_complex_subclasses(self):
4450 T_co = TypeVar("T_co", covariant=True)
4451
4452 class Base(Generic[T_co]):
4453 ...
4454
4455 T = TypeVar("T")
4456
4457 # see gh-94607: this fails in that bug
4458 class Sub(Base, Generic[T]):
4459 ...
4460
4461 def test_parameter_detection(self):
4462 self.assertEqual(List[T].__parameters__, (T,))
4463 self.assertEqual(List[List[T]].__parameters__, (T,))
4464 class A:
4465 __parameters__ = (T,)
4466 # Bare classes should be skipped
4467 for a in (List, list):
4468 for b in (A, int, TypeVar, TypeVarTuple, ParamSpec, types.GenericAlias, types.UnionType):
4469 with self.subTest(generic=a, sub=b):
4470 with self.assertRaisesRegex(TypeError, '.* is not a generic class'):
4471 a[b][str]
4472 # Duck-typing anything that looks like it has __parameters__.
4473 # These tests are optional and failure is okay.
4474 self.assertEqual(List[A()].__parameters__, (T,))
4475 # C version of GenericAlias
4476 self.assertEqual(list[A()].__parameters__, (T,))
4477
4478 def test_non_generic_subscript(self):
4479 T = TypeVar('T')
4480 class G(Generic[T]):
4481 pass
4482 class A:
4483 __parameters__ = (T,)
4484
4485 for s in (int, G, A, List, list,
4486 TypeVar, TypeVarTuple, ParamSpec,
4487 types.GenericAlias, types.UnionType):
4488
4489 for t in Tuple, tuple:
4490 with self.subTest(tuple=t, sub=s):
4491 self.assertEqual(t[s, T][int], t[s, int])
4492 self.assertEqual(t[T, s][int], t[int, s])
4493 a = t[s]
4494 with self.assertRaises(TypeError):
4495 a[int]
4496
4497 for c in Callable, collections.abc.Callable:
4498 with self.subTest(callable=c, sub=s):
4499 self.assertEqual(c[[s], T][int], c[[s], int])
4500 self.assertEqual(c[[T], s][int], c[[int], s])
4501 a = c[[s], s]
4502 with self.assertRaises(TypeError):
4503 a[int]
4504
4505
4506 class ClassVarTests(BaseTestCase):
4507
4508 def test_basics(self):
4509 with self.assertRaises(TypeError):
4510 ClassVar[int, str]
4511 with self.assertRaises(TypeError):
4512 ClassVar[int][str]
4513
4514 def test_repr(self):
4515 self.assertEqual(repr(ClassVar), 'typing.ClassVar')
4516 cv = ClassVar[int]
4517 self.assertEqual(repr(cv), 'typing.ClassVar[int]')
4518 cv = ClassVar[Employee]
4519 self.assertEqual(repr(cv), 'typing.ClassVar[%s.Employee]' % __name__)
4520
4521 def test_cannot_subclass(self):
4522 with self.assertRaises(TypeError):
4523 class C(type(ClassVar)):
4524 pass
4525 with self.assertRaises(TypeError):
4526 class D(type(ClassVar[int])):
4527 pass
4528
4529 def test_cannot_init(self):
4530 with self.assertRaises(TypeError):
4531 ClassVar()
4532 with self.assertRaises(TypeError):
4533 type(ClassVar)()
4534 with self.assertRaises(TypeError):
4535 type(ClassVar[Optional[int]])()
4536
4537 def test_no_isinstance(self):
4538 with self.assertRaises(TypeError):
4539 isinstance(1, ClassVar[int])
4540 with self.assertRaises(TypeError):
4541 issubclass(int, ClassVar)
4542
4543 class FinalTests(BaseTestCase):
4544
4545 def test_basics(self):
4546 Final[int] # OK
4547 with self.assertRaises(TypeError):
4548 Final[int, str]
4549 with self.assertRaises(TypeError):
4550 Final[int][str]
4551 with self.assertRaises(TypeError):
4552 Optional[Final[int]]
4553
4554 def test_repr(self):
4555 self.assertEqual(repr(Final), 'typing.Final')
4556 cv = Final[int]
4557 self.assertEqual(repr(cv), 'typing.Final[int]')
4558 cv = Final[Employee]
4559 self.assertEqual(repr(cv), 'typing.Final[%s.Employee]' % __name__)
4560 cv = Final[tuple[int]]
4561 self.assertEqual(repr(cv), 'typing.Final[tuple[int]]')
4562
4563 def test_cannot_subclass(self):
4564 with self.assertRaises(TypeError):
4565 class C(type(Final)):
4566 pass
4567 with self.assertRaises(TypeError):
4568 class D(type(Final[int])):
4569 pass
4570
4571 def test_cannot_init(self):
4572 with self.assertRaises(TypeError):
4573 Final()
4574 with self.assertRaises(TypeError):
4575 type(Final)()
4576 with self.assertRaises(TypeError):
4577 type(Final[Optional[int]])()
4578
4579 def test_no_isinstance(self):
4580 with self.assertRaises(TypeError):
4581 isinstance(1, Final[int])
4582 with self.assertRaises(TypeError):
4583 issubclass(int, Final)
4584
4585
4586 class FinalDecoratorTests(BaseTestCase):
4587 def test_final_unmodified(self):
4588 def func(x): ...
4589 self.assertIs(func, final(func))
4590
4591 def test_dunder_final(self):
4592 @final
4593 def func(): ...
4594 @final
4595 class Cls: ...
4596 self.assertIs(True, func.__final__)
4597 self.assertIs(True, Cls.__final__)
4598
4599 class Wrapper:
4600 __slots__ = ("func",)
4601 def __init__(self, func):
4602 self.func = func
4603 def __call__(self, *args, **kwargs):
4604 return self.func(*args, **kwargs)
4605
4606 # Check that no error is thrown if the attribute
4607 # is not writable.
4608 @final
4609 @Wrapper
4610 def wrapped(): ...
4611 self.assertIsInstance(wrapped, Wrapper)
4612 self.assertIs(False, hasattr(wrapped, "__final__"))
4613
4614 class Meta(type):
4615 @property
4616 def __final__(self): return "can't set me"
4617 @final
4618 class WithMeta(metaclass=Meta): ...
4619 self.assertEqual(WithMeta.__final__, "can't set me")
4620
4621 # Builtin classes throw TypeError if you try to set an
4622 # attribute.
4623 final(int)
4624 self.assertIs(False, hasattr(int, "__final__"))
4625
4626 # Make sure it works with common builtin decorators
4627 class Methods:
4628 @final
4629 @classmethod
4630 def clsmethod(cls): ...
4631
4632 @final
4633 @staticmethod
4634 def stmethod(): ...
4635
4636 # The other order doesn't work because property objects
4637 # don't allow attribute assignment.
4638 @property
4639 @final
4640 def prop(self): ...
4641
4642 @final
4643 @lru_cache()
4644 def cached(self): ...
4645
4646 # Use getattr_static because the descriptor returns the
4647 # underlying function, which doesn't have __final__.
4648 self.assertIs(
4649 True,
4650 inspect.getattr_static(Methods, "clsmethod").__final__
4651 )
4652 self.assertIs(
4653 True,
4654 inspect.getattr_static(Methods, "stmethod").__final__
4655 )
4656 self.assertIs(True, Methods.prop.fget.__final__)
4657 self.assertIs(True, Methods.cached.__final__)
4658
4659
4660 class CastTests(BaseTestCase):
4661
4662 def test_basics(self):
4663 self.assertEqual(cast(int, 42), 42)
4664 self.assertEqual(cast(float, 42), 42)
4665 self.assertIs(type(cast(float, 42)), int)
4666 self.assertEqual(cast(Any, 42), 42)
4667 self.assertEqual(cast(list, 42), 42)
4668 self.assertEqual(cast(Union[str, float], 42), 42)
4669 self.assertEqual(cast(AnyStr, 42), 42)
4670 self.assertEqual(cast(None, 42), 42)
4671
4672 def test_errors(self):
4673 # Bogus calls are not expected to fail.
4674 cast(42, 42)
4675 cast('hello', 42)
4676
4677
4678 class AssertTypeTests(BaseTestCase):
4679
4680 def test_basics(self):
4681 arg = 42
4682 self.assertIs(assert_type(arg, int), arg)
4683 self.assertIs(assert_type(arg, str | float), arg)
4684 self.assertIs(assert_type(arg, AnyStr), arg)
4685 self.assertIs(assert_type(arg, None), arg)
4686
4687 def test_errors(self):
4688 # Bogus calls are not expected to fail.
4689 arg = 42
4690 self.assertIs(assert_type(arg, 42), arg)
4691 self.assertIs(assert_type(arg, 'hello'), arg)
4692
4693
4694 # We need this to make sure that `@no_type_check` respects `__module__` attr:
4695 from test.typinganndata import ann_module8
4696
4697 @no_type_check
4698 class NoTypeCheck_Outer:
4699 Inner = ann_module8.NoTypeCheck_Outer.Inner
4700
4701 @no_type_check
4702 class NoTypeCheck_WithFunction:
4703 NoTypeCheck_function = ann_module8.NoTypeCheck_function
4704
4705
4706 class ForwardRefTests(BaseTestCase):
4707
4708 def test_basics(self):
4709
4710 class Node(Generic[T]):
4711
4712 def __init__(self, label: T):
4713 self.label = label
4714 self.left = self.right = None
4715
4716 def add_both(self,
4717 left: 'Optional[Node[T]]',
4718 right: 'Node[T]' = None,
4719 stuff: int = None,
4720 blah=None):
4721 self.left = left
4722 self.right = right
4723
4724 def add_left(self, node: Optional['Node[T]']):
4725 self.add_both(node, None)
4726
4727 def add_right(self, node: 'Node[T]' = None):
4728 self.add_both(None, node)
4729
4730 t = Node[int]
4731 both_hints = get_type_hints(t.add_both, globals(), locals())
4732 self.assertEqual(both_hints['left'], Optional[Node[T]])
4733 self.assertEqual(both_hints['right'], Node[T])
4734 self.assertEqual(both_hints['stuff'], int)
4735 self.assertNotIn('blah', both_hints)
4736
4737 left_hints = get_type_hints(t.add_left, globals(), locals())
4738 self.assertEqual(left_hints['node'], Optional[Node[T]])
4739
4740 right_hints = get_type_hints(t.add_right, globals(), locals())
4741 self.assertEqual(right_hints['node'], Node[T])
4742
4743 def test_forwardref_instance_type_error(self):
4744 fr = typing.ForwardRef('int')
4745 with self.assertRaises(TypeError):
4746 isinstance(42, fr)
4747
4748 def test_forwardref_subclass_type_error(self):
4749 fr = typing.ForwardRef('int')
4750 with self.assertRaises(TypeError):
4751 issubclass(int, fr)
4752
4753 def test_forwardref_only_str_arg(self):
4754 with self.assertRaises(TypeError):
4755 typing.ForwardRef(1) # only `str` type is allowed
4756
4757 def test_forward_equality(self):
4758 fr = typing.ForwardRef('int')
4759 self.assertEqual(fr, typing.ForwardRef('int'))
4760 self.assertNotEqual(List['int'], List[int])
4761 self.assertNotEqual(fr, typing.ForwardRef('int', module=__name__))
4762 frm = typing.ForwardRef('int', module=__name__)
4763 self.assertEqual(frm, typing.ForwardRef('int', module=__name__))
4764 self.assertNotEqual(frm, typing.ForwardRef('int', module='__other_name__'))
4765
4766 def test_forward_equality_gth(self):
4767 c1 = typing.ForwardRef('C')
4768 c1_gth = typing.ForwardRef('C')
4769 c2 = typing.ForwardRef('C')
4770 c2_gth = typing.ForwardRef('C')
4771
4772 class C:
4773 pass
4774 def foo(a: c1_gth, b: c2_gth):
4775 pass
4776
4777 self.assertEqual(get_type_hints(foo, globals(), locals()), {'a': C, 'b': C})
4778 self.assertEqual(c1, c2)
4779 self.assertEqual(c1, c1_gth)
4780 self.assertEqual(c1_gth, c2_gth)
4781 self.assertEqual(List[c1], List[c1_gth])
4782 self.assertNotEqual(List[c1], List[C])
4783 self.assertNotEqual(List[c1_gth], List[C])
4784 self.assertEqual(Union[c1, c1_gth], Union[c1])
4785 self.assertEqual(Union[c1, c1_gth, int], Union[c1, int])
4786
4787 def test_forward_equality_hash(self):
4788 c1 = typing.ForwardRef('int')
4789 c1_gth = typing.ForwardRef('int')
4790 c2 = typing.ForwardRef('int')
4791 c2_gth = typing.ForwardRef('int')
4792
4793 def foo(a: c1_gth, b: c2_gth):
4794 pass
4795 get_type_hints(foo, globals(), locals())
4796
4797 self.assertEqual(hash(c1), hash(c2))
4798 self.assertEqual(hash(c1_gth), hash(c2_gth))
4799 self.assertEqual(hash(c1), hash(c1_gth))
4800
4801 c3 = typing.ForwardRef('int', module=__name__)
4802 c4 = typing.ForwardRef('int', module='__other_name__')
4803
4804 self.assertNotEqual(hash(c3), hash(c1))
4805 self.assertNotEqual(hash(c3), hash(c1_gth))
4806 self.assertNotEqual(hash(c3), hash(c4))
4807 self.assertEqual(hash(c3), hash(typing.ForwardRef('int', module=__name__)))
4808
4809 def test_forward_equality_namespace(self):
4810 class A:
4811 pass
4812 def namespace1():
4813 a = typing.ForwardRef('A')
4814 def fun(x: a):
4815 pass
4816 get_type_hints(fun, globals(), locals())
4817 return a
4818
4819 def namespace2():
4820 a = typing.ForwardRef('A')
4821
4822 class A:
4823 pass
4824 def fun(x: a):
4825 pass
4826
4827 get_type_hints(fun, globals(), locals())
4828 return a
4829
4830 self.assertEqual(namespace1(), namespace1())
4831 self.assertNotEqual(namespace1(), namespace2())
4832
4833 def test_forward_repr(self):
4834 self.assertEqual(repr(List['int']), "typing.List[ForwardRef('int')]")
4835 self.assertEqual(repr(List[ForwardRef('int', module='mod')]),
4836 "typing.List[ForwardRef('int', module='mod')]")
4837
4838 def test_union_forward(self):
4839
4840 def foo(a: Union['T']):
4841 pass
4842
4843 self.assertEqual(get_type_hints(foo, globals(), locals()),
4844 {'a': Union[T]})
4845
4846 def foo(a: tuple[ForwardRef('T')] | int):
4847 pass
4848
4849 self.assertEqual(get_type_hints(foo, globals(), locals()),
4850 {'a': tuple[T] | int})
4851
4852 def test_tuple_forward(self):
4853
4854 def foo(a: Tuple['T']):
4855 pass
4856
4857 self.assertEqual(get_type_hints(foo, globals(), locals()),
4858 {'a': Tuple[T]})
4859
4860 def foo(a: tuple[ForwardRef('T')]):
4861 pass
4862
4863 self.assertEqual(get_type_hints(foo, globals(), locals()),
4864 {'a': tuple[T]})
4865
4866 def test_double_forward(self):
4867 def foo(a: 'List[\'int\']'):
4868 pass
4869 self.assertEqual(get_type_hints(foo, globals(), locals()),
4870 {'a': List[int]})
4871
4872 def test_forward_recursion_actually(self):
4873 def namespace1():
4874 a = typing.ForwardRef('A')
4875 A = a
4876 def fun(x: a): pass
4877
4878 ret = get_type_hints(fun, globals(), locals())
4879 return a
4880
4881 def namespace2():
4882 a = typing.ForwardRef('A')
4883 A = a
4884 def fun(x: a): pass
4885
4886 ret = get_type_hints(fun, globals(), locals())
4887 return a
4888
4889 def cmp(o1, o2):
4890 return o1 == o2
4891
4892 r1 = namespace1()
4893 r2 = namespace2()
4894 self.assertIsNot(r1, r2)
4895 self.assertRaises(RecursionError, cmp, r1, r2)
4896
4897 def test_union_forward_recursion(self):
4898 ValueList = List['Value']
4899 Value = Union[str, ValueList]
4900
4901 class C:
4902 foo: List[Value]
4903 class D:
4904 foo: Union[Value, ValueList]
4905 class E:
4906 foo: Union[List[Value], ValueList]
4907 class F:
4908 foo: Union[Value, List[Value], ValueList]
4909
4910 self.assertEqual(get_type_hints(C, globals(), locals()), get_type_hints(C, globals(), locals()))
4911 self.assertEqual(get_type_hints(C, globals(), locals()),
4912 {'foo': List[Union[str, List[Union[str, List['Value']]]]]})
4913 self.assertEqual(get_type_hints(D, globals(), locals()),
4914 {'foo': Union[str, List[Union[str, List['Value']]]]})
4915 self.assertEqual(get_type_hints(E, globals(), locals()),
4916 {'foo': Union[
4917 List[Union[str, List[Union[str, List['Value']]]]],
4918 List[Union[str, List['Value']]]
4919 ]
4920 })
4921 self.assertEqual(get_type_hints(F, globals(), locals()),
4922 {'foo': Union[
4923 str,
4924 List[Union[str, List['Value']]],
4925 List[Union[str, List[Union[str, List['Value']]]]]
4926 ]
4927 })
4928
4929 def test_callable_forward(self):
4930
4931 def foo(a: Callable[['T'], 'T']):
4932 pass
4933
4934 self.assertEqual(get_type_hints(foo, globals(), locals()),
4935 {'a': Callable[[T], T]})
4936
4937 def test_callable_with_ellipsis_forward(self):
4938
4939 def foo(a: 'Callable[..., T]'):
4940 pass
4941
4942 self.assertEqual(get_type_hints(foo, globals(), locals()),
4943 {'a': Callable[..., T]})
4944
4945 def test_special_forms_forward(self):
4946
4947 class C:
4948 a: Annotated['ClassVar[int]', (3, 5)] = 4
4949 b: Annotated['Final[int]', "const"] = 4
4950 x: 'ClassVar' = 4
4951 y: 'Final' = 4
4952
4953 class CF:
4954 b: List['Final[int]'] = 4
4955
4956 self.assertEqual(get_type_hints(C, globals())['a'], ClassVar[int])
4957 self.assertEqual(get_type_hints(C, globals())['b'], Final[int])
4958 self.assertEqual(get_type_hints(C, globals())['x'], ClassVar)
4959 self.assertEqual(get_type_hints(C, globals())['y'], Final)
4960 with self.assertRaises(TypeError):
4961 get_type_hints(CF, globals()),
4962
4963 def test_syntax_error(self):
4964
4965 with self.assertRaises(SyntaxError):
4966 Generic['/T']
4967
4968 def test_delayed_syntax_error(self):
4969
4970 def foo(a: 'Node[T'):
4971 pass
4972
4973 with self.assertRaises(SyntaxError):
4974 get_type_hints(foo)
4975
4976 def test_syntax_error_empty_string(self):
4977 for form in [typing.List, typing.Set, typing.Type, typing.Deque]:
4978 with self.subTest(form=form):
4979 with self.assertRaises(SyntaxError):
4980 form['']
4981
4982 def test_name_error(self):
4983
4984 def foo(a: 'Noode[T]'):
4985 pass
4986
4987 with self.assertRaises(NameError):
4988 get_type_hints(foo, locals())
4989
4990 def test_no_type_check(self):
4991
4992 @no_type_check
4993 def foo(a: 'whatevers') -> {}:
4994 pass
4995
4996 th = get_type_hints(foo)
4997 self.assertEqual(th, {})
4998
4999 def test_no_type_check_class(self):
5000
5001 @no_type_check
5002 class C:
5003 def foo(a: 'whatevers') -> {}:
5004 pass
5005
5006 cth = get_type_hints(C.foo)
5007 self.assertEqual(cth, {})
5008 ith = get_type_hints(C().foo)
5009 self.assertEqual(ith, {})
5010
5011 def test_no_type_check_no_bases(self):
5012 class C:
5013 def meth(self, x: int): ...
5014 @no_type_check
5015 class D(C):
5016 c = C
5017
5018 # verify that @no_type_check never affects bases
5019 self.assertEqual(get_type_hints(C.meth), {'x': int})
5020
5021 # and never child classes:
5022 class Child(D):
5023 def foo(self, x: int): ...
5024
5025 self.assertEqual(get_type_hints(Child.foo), {'x': int})
5026
5027 def test_no_type_check_nested_types(self):
5028 # See https://bugs.python.org/issue46571
5029 class Other:
5030 o: int
5031 class B: # Has the same `__name__`` as `A.B` and different `__qualname__`
5032 o: int
5033 @no_type_check
5034 class A:
5035 a: int
5036 class B:
5037 b: int
5038 class C:
5039 c: int
5040 class D:
5041 d: int
5042
5043 Other = Other
5044
5045 for klass in [A, A.B, A.B.C, A.D]:
5046 with self.subTest(klass=klass):
5047 self.assertTrue(klass.__no_type_check__)
5048 self.assertEqual(get_type_hints(klass), {})
5049
5050 for not_modified in [Other, B]:
5051 with self.subTest(not_modified=not_modified):
5052 with self.assertRaises(AttributeError):
5053 not_modified.__no_type_check__
5054 self.assertNotEqual(get_type_hints(not_modified), {})
5055
5056 def test_no_type_check_class_and_static_methods(self):
5057 @no_type_check
5058 class Some:
5059 @staticmethod
5060 def st(x: int) -> int: ...
5061 @classmethod
5062 def cl(cls, y: int) -> int: ...
5063
5064 self.assertTrue(Some.st.__no_type_check__)
5065 self.assertEqual(get_type_hints(Some.st), {})
5066 self.assertTrue(Some.cl.__no_type_check__)
5067 self.assertEqual(get_type_hints(Some.cl), {})
5068
5069 def test_no_type_check_other_module(self):
5070 self.assertTrue(NoTypeCheck_Outer.__no_type_check__)
5071 with self.assertRaises(AttributeError):
5072 ann_module8.NoTypeCheck_Outer.__no_type_check__
5073 with self.assertRaises(AttributeError):
5074 ann_module8.NoTypeCheck_Outer.Inner.__no_type_check__
5075
5076 self.assertTrue(NoTypeCheck_WithFunction.__no_type_check__)
5077 with self.assertRaises(AttributeError):
5078 ann_module8.NoTypeCheck_function.__no_type_check__
5079
5080 def test_no_type_check_foreign_functions(self):
5081 # We should not modify this function:
5082 def some(*args: int) -> int:
5083 ...
5084
5085 @no_type_check
5086 class A:
5087 some_alias = some
5088 some_class = classmethod(some)
5089 some_static = staticmethod(some)
5090
5091 with self.assertRaises(AttributeError):
5092 some.__no_type_check__
5093 self.assertEqual(get_type_hints(some), {'args': int, 'return': int})
5094
5095 def test_no_type_check_lambda(self):
5096 @no_type_check
5097 class A:
5098 # Corner case: `lambda` is both an assignment and a function:
5099 bar: Callable[[int], int] = lambda arg: arg
5100
5101 self.assertTrue(A.bar.__no_type_check__)
5102 self.assertEqual(get_type_hints(A.bar), {})
5103
5104 def test_no_type_check_TypeError(self):
5105 # This simply should not fail with
5106 # `TypeError: can't set attributes of built-in/extension type 'dict'`
5107 no_type_check(dict)
5108
5109 def test_no_type_check_forward_ref_as_string(self):
5110 class C:
5111 foo: typing.ClassVar[int] = 7
5112 class D:
5113 foo: ClassVar[int] = 7
5114 class E:
5115 foo: 'typing.ClassVar[int]' = 7
5116 class F:
5117 foo: 'ClassVar[int]' = 7
5118
5119 expected_result = {'foo': typing.ClassVar[int]}
5120 for clazz in [C, D, E, F]:
5121 self.assertEqual(get_type_hints(clazz), expected_result)
5122
5123 def test_nested_classvar_fails_forward_ref_check(self):
5124 class E:
5125 foo: 'typing.ClassVar[typing.ClassVar[int]]' = 7
5126 class F:
5127 foo: ClassVar['ClassVar[int]'] = 7
5128
5129 for clazz in [E, F]:
5130 with self.assertRaises(TypeError):
5131 get_type_hints(clazz)
5132
5133 def test_meta_no_type_check(self):
5134
5135 @no_type_check_decorator
5136 def magic_decorator(func):
5137 return func
5138
5139 self.assertEqual(magic_decorator.__name__, 'magic_decorator')
5140
5141 @magic_decorator
5142 def foo(a: 'whatevers') -> {}:
5143 pass
5144
5145 @magic_decorator
5146 class C:
5147 def foo(a: 'whatevers') -> {}:
5148 pass
5149
5150 self.assertEqual(foo.__name__, 'foo')
5151 th = get_type_hints(foo)
5152 self.assertEqual(th, {})
5153 cth = get_type_hints(C.foo)
5154 self.assertEqual(cth, {})
5155 ith = get_type_hints(C().foo)
5156 self.assertEqual(ith, {})
5157
5158 def test_default_globals(self):
5159 code = ("class C:\n"
5160 " def foo(self, a: 'C') -> 'D': pass\n"
5161 "class D:\n"
5162 " def bar(self, b: 'D') -> C: pass\n"
5163 )
5164 ns = {}
5165 exec(code, ns)
5166 hints = get_type_hints(ns['C'].foo)
5167 self.assertEqual(hints, {'a': ns['C'], 'return': ns['D']})
5168
5169 def test_final_forward_ref(self):
5170 self.assertEqual(gth(Loop, globals())['attr'], Final[Loop])
5171 self.assertNotEqual(gth(Loop, globals())['attr'], Final[int])
5172 self.assertNotEqual(gth(Loop, globals())['attr'], Final)
5173
5174 def test_or(self):
5175 X = ForwardRef('X')
5176 # __or__/__ror__ itself
5177 self.assertEqual(X | "x", Union[X, "x"])
5178 self.assertEqual("x" | X, Union["x", X])
5179
5180
5181 @lru_cache()
5182 def cached_func(x, y):
5183 return 3 * x + y
5184
5185
5186 class MethodHolder:
5187 @classmethod
5188 def clsmethod(cls): ...
5189 @staticmethod
5190 def stmethod(): ...
5191 def method(self): ...
5192
5193
5194 class OverloadTests(BaseTestCase):
5195
5196 def test_overload_fails(self):
5197 with self.assertRaises(NotImplementedError):
5198
5199 @overload
5200 def blah():
5201 pass
5202
5203 blah()
5204
5205 def test_overload_succeeds(self):
5206 @overload
5207 def blah():
5208 pass
5209
5210 def blah():
5211 pass
5212
5213 blah()
5214
5215 @cpython_only # gh-98713
5216 def test_overload_on_compiled_functions(self):
5217 with patch("typing._overload_registry",
5218 defaultdict(lambda: defaultdict(dict))):
5219 # The registry starts out empty:
5220 self.assertEqual(typing._overload_registry, {})
5221
5222 # This should just not fail:
5223 overload(sum)
5224 overload(print)
5225
5226 # No overloads are recorded (but, it still has a side-effect):
5227 self.assertEqual(typing.get_overloads(sum), [])
5228 self.assertEqual(typing.get_overloads(print), [])
5229
5230 def set_up_overloads(self):
5231 def blah():
5232 pass
5233
5234 overload1 = blah
5235 overload(blah)
5236
5237 def blah():
5238 pass
5239
5240 overload2 = blah
5241 overload(blah)
5242
5243 def blah():
5244 pass
5245
5246 return blah, [overload1, overload2]
5247
5248 # Make sure we don't clear the global overload registry
5249 @patch("typing._overload_registry",
5250 defaultdict(lambda: defaultdict(dict)))
5251 def test_overload_registry(self):
5252 # The registry starts out empty
5253 self.assertEqual(typing._overload_registry, {})
5254
5255 impl, overloads = self.set_up_overloads()
5256 self.assertNotEqual(typing._overload_registry, {})
5257 self.assertEqual(list(get_overloads(impl)), overloads)
5258
5259 def some_other_func(): pass
5260 overload(some_other_func)
5261 other_overload = some_other_func
5262 def some_other_func(): pass
5263 self.assertEqual(list(get_overloads(some_other_func)), [other_overload])
5264 # Unrelated function still has no overloads:
5265 def not_overloaded(): pass
5266 self.assertEqual(list(get_overloads(not_overloaded)), [])
5267
5268 # Make sure that after we clear all overloads, the registry is
5269 # completely empty.
5270 clear_overloads()
5271 self.assertEqual(typing._overload_registry, {})
5272 self.assertEqual(get_overloads(impl), [])
5273
5274 # Querying a function with no overloads shouldn't change the registry.
5275 def the_only_one(): pass
5276 self.assertEqual(get_overloads(the_only_one), [])
5277 self.assertEqual(typing._overload_registry, {})
5278
5279 def test_overload_registry_repeated(self):
5280 for _ in range(2):
5281 impl, overloads = self.set_up_overloads()
5282
5283 self.assertEqual(list(get_overloads(impl)), overloads)
5284
5285
5286 # Definitions needed for features introduced in Python 3.6
5287
5288 from test.typinganndata import (
5289 ann_module, ann_module2, ann_module3, ann_module5, ann_module6,
5290 )
5291
5292 T_a = TypeVar('T_a')
5293
5294 class AwaitableWrapper(typing.Awaitable[T_a]):
5295
5296 def __init__(self, value):
5297 self.value = value
5298
5299 def __await__(self) -> typing.Iterator[T_a]:
5300 yield
5301 return self.value
5302
5303 class AsyncIteratorWrapper(typing.AsyncIterator[T_a]):
5304
5305 def __init__(self, value: typing.Iterable[T_a]):
5306 self.value = value
5307
5308 def __aiter__(self) -> typing.AsyncIterator[T_a]:
5309 return self
5310
5311 async def __anext__(self) -> T_a:
5312 data = await self.value
5313 if data:
5314 return data
5315 else:
5316 raise StopAsyncIteration
5317
5318 class ACM:
5319 async def __aenter__(self) -> int:
5320 return 42
5321 async def __aexit__(self, etype, eval, tb):
5322 return None
5323
5324 class A:
5325 y: float
5326 class B(A):
5327 x: ClassVar[Optional['B']] = None
5328 y: int
5329 b: int
5330 class CSub(B):
5331 z: ClassVar['CSub'] = B()
5332 class G(Generic[T]):
5333 lst: ClassVar[List[T]] = []
5334
5335 class Loop:
5336 attr: Final['Loop']
5337
5338 class NoneAndForward:
5339 parent: 'NoneAndForward'
5340 meaning: None
5341
5342 class CoolEmployee(NamedTuple):
5343 name: str
5344 cool: int
5345
5346 class CoolEmployeeWithDefault(NamedTuple):
5347 name: str
5348 cool: int = 0
5349
5350 class XMeth(NamedTuple):
5351 x: int
5352 def double(self):
5353 return 2 * self.x
5354
5355 class XRepr(NamedTuple):
5356 x: int
5357 y: int = 1
5358 def __str__(self):
5359 return f'{self.x} -> {self.y}'
5360 def __add__(self, other):
5361 return 0
5362
5363 Label = TypedDict('Label', [('label', str)])
5364
5365 class Point2D(TypedDict):
5366 x: int
5367 y: int
5368
5369 class Point2DGeneric(Generic[T], TypedDict):
5370 a: T
5371 b: T
5372
5373 class Bar(_typed_dict_helper.Foo, total=False):
5374 b: int
5375
5376 class BarGeneric(_typed_dict_helper.FooGeneric[T], total=False):
5377 b: int
5378
5379 class LabelPoint2D(Point2D, Label): ...
5380
5381 class Options(TypedDict, total=False):
5382 log_level: int
5383 log_path: str
5384
5385 class TotalMovie(TypedDict):
5386 title: str
5387 year: NotRequired[int]
5388
5389 class NontotalMovie(TypedDict, total=False):
5390 title: Required[str]
5391 year: int
5392
5393 class ParentNontotalMovie(TypedDict, total=False):
5394 title: Required[str]
5395
5396 class ChildTotalMovie(ParentNontotalMovie):
5397 year: NotRequired[int]
5398
5399 class ParentDeeplyAnnotatedMovie(TypedDict):
5400 title: Annotated[Annotated[Required[str], "foobar"], "another level"]
5401
5402 class ChildDeeplyAnnotatedMovie(ParentDeeplyAnnotatedMovie):
5403 year: NotRequired[Annotated[int, 2000]]
5404
5405 class AnnotatedMovie(TypedDict):
5406 title: Annotated[Required[str], "foobar"]
5407 year: NotRequired[Annotated[int, 2000]]
5408
5409 class DeeplyAnnotatedMovie(TypedDict):
5410 title: Annotated[Annotated[Required[str], "foobar"], "another level"]
5411 year: NotRequired[Annotated[int, 2000]]
5412
5413 class WeirdlyQuotedMovie(TypedDict):
5414 title: Annotated['Annotated[Required[str], "foobar"]', "another level"]
5415 year: NotRequired['Annotated[int, 2000]']
5416
5417 class HasForeignBaseClass(mod_generics_cache.A):
5418 some_xrepr: 'XRepr'
5419 other_a: 'mod_generics_cache.A'
5420
5421 async def g_with(am: typing.AsyncContextManager[int]):
5422 x: int
5423 async with am as x:
5424 return x
5425
5426 try:
5427 g_with(ACM()).send(None)
5428 except StopIteration as e:
5429 assert e.args[0] == 42
5430
5431 gth = get_type_hints
5432
5433 class ForRefExample:
5434 @ann_module.dec
5435 def func(self: 'ForRefExample'):
5436 pass
5437
5438 @ann_module.dec
5439 @ann_module.dec
5440 def nested(self: 'ForRefExample'):
5441 pass
5442
5443
5444 class GetTypeHintTests(BaseTestCase):
5445 def test_get_type_hints_from_various_objects(self):
5446 # For invalid objects should fail with TypeError (not AttributeError etc).
5447 with self.assertRaises(TypeError):
5448 gth(123)
5449 with self.assertRaises(TypeError):
5450 gth('abc')
5451 with self.assertRaises(TypeError):
5452 gth(None)
5453
5454 def test_get_type_hints_modules(self):
5455 ann_module_type_hints = {1: 2, 'f': Tuple[int, int], 'x': int, 'y': str, 'u': int | float}
5456 self.assertEqual(gth(ann_module), ann_module_type_hints)
5457 self.assertEqual(gth(ann_module2), {})
5458 self.assertEqual(gth(ann_module3), {})
5459
5460 @skip("known bug")
5461 def test_get_type_hints_modules_forwardref(self):
5462 # FIXME: This currently exposes a bug in typing. Cached forward references
5463 # don't account for the case where there are multiple types of the same
5464 # name coming from different modules in the same program.
5465 mgc_hints = {'default_a': Optional[mod_generics_cache.A],
5466 'default_b': Optional[mod_generics_cache.B]}
5467 self.assertEqual(gth(mod_generics_cache), mgc_hints)
5468
5469 def test_get_type_hints_classes(self):
5470 self.assertEqual(gth(ann_module.C), # gth will find the right globalns
5471 {'y': Optional[ann_module.C]})
5472 self.assertIsInstance(gth(ann_module.j_class), dict)
5473 self.assertEqual(gth(ann_module.M), {'123': 123, 'o': type})
5474 self.assertEqual(gth(ann_module.D),
5475 {'j': str, 'k': str, 'y': Optional[ann_module.C]})
5476 self.assertEqual(gth(ann_module.Y), {'z': int})
5477 self.assertEqual(gth(ann_module.h_class),
5478 {'y': Optional[ann_module.C]})
5479 self.assertEqual(gth(ann_module.S), {'x': str, 'y': str})
5480 self.assertEqual(gth(ann_module.foo), {'x': int})
5481 self.assertEqual(gth(NoneAndForward),
5482 {'parent': NoneAndForward, 'meaning': type(None)})
5483 self.assertEqual(gth(HasForeignBaseClass),
5484 {'some_xrepr': XRepr, 'other_a': mod_generics_cache.A,
5485 'some_b': mod_generics_cache.B})
5486 self.assertEqual(gth(XRepr.__new__),
5487 {'x': int, 'y': int})
5488 self.assertEqual(gth(mod_generics_cache.B),
5489 {'my_inner_a1': mod_generics_cache.B.A,
5490 'my_inner_a2': mod_generics_cache.B.A,
5491 'my_outer_a': mod_generics_cache.A})
5492
5493 def test_get_type_hints_classes_no_implicit_optional(self):
5494 class WithNoneDefault:
5495 field: int = None # most type-checkers won't be happy with it
5496
5497 self.assertEqual(gth(WithNoneDefault), {'field': int})
5498
5499 def test_respect_no_type_check(self):
5500 @no_type_check
5501 class NoTpCheck:
5502 class Inn:
5503 def __init__(self, x: 'not a type'): ...
5504 self.assertTrue(NoTpCheck.__no_type_check__)
5505 self.assertTrue(NoTpCheck.Inn.__init__.__no_type_check__)
5506 self.assertEqual(gth(ann_module2.NTC.meth), {})
5507 class ABase(Generic[T]):
5508 def meth(x: int): ...
5509 @no_type_check
5510 class Der(ABase): ...
5511 self.assertEqual(gth(ABase.meth), {'x': int})
5512
5513 def test_get_type_hints_for_builtins(self):
5514 # Should not fail for built-in classes and functions.
5515 self.assertEqual(gth(int), {})
5516 self.assertEqual(gth(type), {})
5517 self.assertEqual(gth(dir), {})
5518 self.assertEqual(gth(len), {})
5519 self.assertEqual(gth(object.__str__), {})
5520 self.assertEqual(gth(object().__str__), {})
5521 self.assertEqual(gth(str.join), {})
5522
5523 def test_previous_behavior(self):
5524 def testf(x, y): ...
5525 testf.__annotations__['x'] = 'int'
5526 self.assertEqual(gth(testf), {'x': int})
5527 def testg(x: None): ...
5528 self.assertEqual(gth(testg), {'x': type(None)})
5529
5530 def test_get_type_hints_for_object_with_annotations(self):
5531 class A: ...
5532 class B: ...
5533 b = B()
5534 b.__annotations__ = {'x': 'A'}
5535 self.assertEqual(gth(b, locals()), {'x': A})
5536
5537 def test_get_type_hints_ClassVar(self):
5538 self.assertEqual(gth(ann_module2.CV, ann_module2.__dict__),
5539 {'var': typing.ClassVar[ann_module2.CV]})
5540 self.assertEqual(gth(B, globals()),
5541 {'y': int, 'x': ClassVar[Optional[B]], 'b': int})
5542 self.assertEqual(gth(CSub, globals()),
5543 {'z': ClassVar[CSub], 'y': int, 'b': int,
5544 'x': ClassVar[Optional[B]]})
5545 self.assertEqual(gth(G), {'lst': ClassVar[List[T]]})
5546
5547 def test_get_type_hints_wrapped_decoratored_func(self):
5548 expects = {'self': ForRefExample}
5549 self.assertEqual(gth(ForRefExample.func), expects)
5550 self.assertEqual(gth(ForRefExample.nested), expects)
5551
5552 def test_get_type_hints_annotated(self):
5553 def foobar(x: List['X']): ...
5554 X = Annotated[int, (1, 10)]
5555 self.assertEqual(
5556 get_type_hints(foobar, globals(), locals()),
5557 {'x': List[int]}
5558 )
5559 self.assertEqual(
5560 get_type_hints(foobar, globals(), locals(), include_extras=True),
5561 {'x': List[Annotated[int, (1, 10)]]}
5562 )
5563
5564 def foobar(x: list[ForwardRef('X')]): ...
5565 X = Annotated[int, (1, 10)]
5566 self.assertEqual(
5567 get_type_hints(foobar, globals(), locals()),
5568 {'x': list[int]}
5569 )
5570 self.assertEqual(
5571 get_type_hints(foobar, globals(), locals(), include_extras=True),
5572 {'x': list[Annotated[int, (1, 10)]]}
5573 )
5574
5575 BA = Tuple[Annotated[T, (1, 0)], ...]
5576 def barfoo(x: BA): ...
5577 self.assertEqual(get_type_hints(barfoo, globals(), locals())['x'], Tuple[T, ...])
5578 self.assertEqual(
5579 get_type_hints(barfoo, globals(), locals(), include_extras=True)['x'],
5580 BA
5581 )
5582
5583 BA = tuple[Annotated[T, (1, 0)], ...]
5584 def barfoo(x: BA): ...
5585 self.assertEqual(get_type_hints(barfoo, globals(), locals())['x'], tuple[T, ...])
5586 self.assertEqual(
5587 get_type_hints(barfoo, globals(), locals(), include_extras=True)['x'],
5588 BA
5589 )
5590
5591 def barfoo2(x: typing.Callable[..., Annotated[List[T], "const"]],
5592 y: typing.Union[int, Annotated[T, "mutable"]]): ...
5593 self.assertEqual(
5594 get_type_hints(barfoo2, globals(), locals()),
5595 {'x': typing.Callable[..., List[T]], 'y': typing.Union[int, T]}
5596 )
5597
5598 BA2 = typing.Callable[..., List[T]]
5599 def barfoo3(x: BA2): ...
5600 self.assertIs(
5601 get_type_hints(barfoo3, globals(), locals(), include_extras=True)["x"],
5602 BA2
5603 )
5604 BA3 = typing.Annotated[int | float, "const"]
5605 def barfoo4(x: BA3): ...
5606 self.assertEqual(
5607 get_type_hints(barfoo4, globals(), locals()),
5608 {"x": int | float}
5609 )
5610 self.assertEqual(
5611 get_type_hints(barfoo4, globals(), locals(), include_extras=True),
5612 {"x": typing.Annotated[int | float, "const"]}
5613 )
5614
5615 def test_get_type_hints_annotated_in_union(self): # bpo-46603
5616 def with_union(x: int | list[Annotated[str, 'meta']]): ...
5617
5618 self.assertEqual(get_type_hints(with_union), {'x': int | list[str]})
5619 self.assertEqual(
5620 get_type_hints(with_union, include_extras=True),
5621 {'x': int | list[Annotated[str, 'meta']]},
5622 )
5623
5624 def test_get_type_hints_annotated_refs(self):
5625
5626 Const = Annotated[T, "Const"]
5627
5628 class MySet(Generic[T]):
5629
5630 def __ior__(self, other: "Const[MySet[T]]") -> "MySet[T]":
5631 ...
5632
5633 def __iand__(self, other: Const["MySet[T]"]) -> "MySet[T]":
5634 ...
5635
5636 self.assertEqual(
5637 get_type_hints(MySet.__iand__, globals(), locals()),
5638 {'other': MySet[T], 'return': MySet[T]}
5639 )
5640
5641 self.assertEqual(
5642 get_type_hints(MySet.__iand__, globals(), locals(), include_extras=True),
5643 {'other': Const[MySet[T]], 'return': MySet[T]}
5644 )
5645
5646 self.assertEqual(
5647 get_type_hints(MySet.__ior__, globals(), locals()),
5648 {'other': MySet[T], 'return': MySet[T]}
5649 )
5650
5651 def test_get_type_hints_annotated_with_none_default(self):
5652 # See: https://bugs.python.org/issue46195
5653 def annotated_with_none_default(x: Annotated[int, 'data'] = None): ...
5654 self.assertEqual(
5655 get_type_hints(annotated_with_none_default),
5656 {'x': int},
5657 )
5658 self.assertEqual(
5659 get_type_hints(annotated_with_none_default, include_extras=True),
5660 {'x': Annotated[int, 'data']},
5661 )
5662
5663 def test_get_type_hints_classes_str_annotations(self):
5664 class Foo:
5665 y = str
5666 x: 'y'
5667 # This previously raised an error under PEP 563.
5668 self.assertEqual(get_type_hints(Foo), {'x': str})
5669
5670 def test_get_type_hints_bad_module(self):
5671 # bpo-41515
5672 class BadModule:
5673 pass
5674 BadModule.__module__ = 'bad' # Something not in sys.modules
5675 self.assertNotIn('bad', sys.modules)
5676 self.assertEqual(get_type_hints(BadModule), {})
5677
5678 def test_get_type_hints_annotated_bad_module(self):
5679 # See https://bugs.python.org/issue44468
5680 class BadBase:
5681 foo: tuple
5682 class BadType(BadBase):
5683 bar: list
5684 BadType.__module__ = BadBase.__module__ = 'bad'
5685 self.assertNotIn('bad', sys.modules)
5686 self.assertEqual(get_type_hints(BadType), {'foo': tuple, 'bar': list})
5687
5688 def test_forward_ref_and_final(self):
5689 # https://bugs.python.org/issue45166
5690 hints = get_type_hints(ann_module5)
5691 self.assertEqual(hints, {'name': Final[str]})
5692
5693 hints = get_type_hints(ann_module5.MyClass)
5694 self.assertEqual(hints, {'value': Final})
5695
5696 def test_top_level_class_var(self):
5697 # https://bugs.python.org/issue45166
5698 with self.assertRaisesRegex(
5699 TypeError,
5700 r'typing.ClassVar\[int\] is not valid as type argument',
5701 ):
5702 get_type_hints(ann_module6)
5703
5704 def test_get_type_hints_typeddict(self):
5705 self.assertEqual(get_type_hints(TotalMovie), {'title': str, 'year': int})
5706 self.assertEqual(get_type_hints(TotalMovie, include_extras=True), {
5707 'title': str,
5708 'year': NotRequired[int],
5709 })
5710
5711 self.assertEqual(get_type_hints(AnnotatedMovie), {'title': str, 'year': int})
5712 self.assertEqual(get_type_hints(AnnotatedMovie, include_extras=True), {
5713 'title': Annotated[Required[str], "foobar"],
5714 'year': NotRequired[Annotated[int, 2000]],
5715 })
5716
5717 self.assertEqual(get_type_hints(DeeplyAnnotatedMovie), {'title': str, 'year': int})
5718 self.assertEqual(get_type_hints(DeeplyAnnotatedMovie, include_extras=True), {
5719 'title': Annotated[Required[str], "foobar", "another level"],
5720 'year': NotRequired[Annotated[int, 2000]],
5721 })
5722
5723 self.assertEqual(get_type_hints(WeirdlyQuotedMovie), {'title': str, 'year': int})
5724 self.assertEqual(get_type_hints(WeirdlyQuotedMovie, include_extras=True), {
5725 'title': Annotated[Required[str], "foobar", "another level"],
5726 'year': NotRequired[Annotated[int, 2000]],
5727 })
5728
5729 self.assertEqual(get_type_hints(_typed_dict_helper.VeryAnnotated), {'a': int})
5730 self.assertEqual(get_type_hints(_typed_dict_helper.VeryAnnotated, include_extras=True), {
5731 'a': Annotated[Required[int], "a", "b", "c"]
5732 })
5733
5734 self.assertEqual(get_type_hints(ChildTotalMovie), {"title": str, "year": int})
5735 self.assertEqual(get_type_hints(ChildTotalMovie, include_extras=True), {
5736 "title": Required[str], "year": NotRequired[int]
5737 })
5738
5739 self.assertEqual(get_type_hints(ChildDeeplyAnnotatedMovie), {"title": str, "year": int})
5740 self.assertEqual(get_type_hints(ChildDeeplyAnnotatedMovie, include_extras=True), {
5741 "title": Annotated[Required[str], "foobar", "another level"],
5742 "year": NotRequired[Annotated[int, 2000]]
5743 })
5744
5745 def test_get_type_hints_collections_abc_callable(self):
5746 # https://github.com/python/cpython/issues/91621
5747 P = ParamSpec('P')
5748 def f(x: collections.abc.Callable[[int], int]): ...
5749 def g(x: collections.abc.Callable[..., int]): ...
5750 def h(x: collections.abc.Callable[P, int]): ...
5751
5752 self.assertEqual(get_type_hints(f), {'x': collections.abc.Callable[[int], int]})
5753 self.assertEqual(get_type_hints(g), {'x': collections.abc.Callable[..., int]})
5754 self.assertEqual(get_type_hints(h), {'x': collections.abc.Callable[P, int]})
5755
5756
5757 class GetUtilitiesTestCase(TestCase):
5758 def test_get_origin(self):
5759 T = TypeVar('T')
5760 Ts = TypeVarTuple('Ts')
5761 P = ParamSpec('P')
5762 class C(Generic[T]): pass
5763 self.assertIs(get_origin(C[int]), C)
5764 self.assertIs(get_origin(C[T]), C)
5765 self.assertIs(get_origin(int), None)
5766 self.assertIs(get_origin(ClassVar[int]), ClassVar)
5767 self.assertIs(get_origin(Union[int, str]), Union)
5768 self.assertIs(get_origin(Literal[42, 43]), Literal)
5769 self.assertIs(get_origin(Final[List[int]]), Final)
5770 self.assertIs(get_origin(Generic), Generic)
5771 self.assertIs(get_origin(Generic[T]), Generic)
5772 self.assertIs(get_origin(List[Tuple[T, T]][int]), list)
5773 self.assertIs(get_origin(Annotated[T, 'thing']), Annotated)
5774 self.assertIs(get_origin(List), list)
5775 self.assertIs(get_origin(Tuple), tuple)
5776 self.assertIs(get_origin(Callable), collections.abc.Callable)
5777 self.assertIs(get_origin(list[int]), list)
5778 self.assertIs(get_origin(list), None)
5779 self.assertIs(get_origin(list | str), types.UnionType)
5780 self.assertIs(get_origin(P.args), P)
5781 self.assertIs(get_origin(P.kwargs), P)
5782 self.assertIs(get_origin(Required[int]), Required)
5783 self.assertIs(get_origin(NotRequired[int]), NotRequired)
5784 self.assertIs(get_origin((*Ts,)[0]), Unpack)
5785 self.assertIs(get_origin(Unpack[Ts]), Unpack)
5786 self.assertIs(get_origin((*tuple[*Ts],)[0]), tuple)
5787 self.assertIs(get_origin(Unpack[Tuple[Unpack[Ts]]]), Unpack)
5788
5789 def test_get_args(self):
5790 T = TypeVar('T')
5791 class C(Generic[T]): pass
5792 self.assertEqual(get_args(C[int]), (int,))
5793 self.assertEqual(get_args(C[T]), (T,))
5794 self.assertEqual(get_args(int), ())
5795 self.assertEqual(get_args(ClassVar[int]), (int,))
5796 self.assertEqual(get_args(Union[int, str]), (int, str))
5797 self.assertEqual(get_args(Literal[42, 43]), (42, 43))
5798 self.assertEqual(get_args(Final[List[int]]), (List[int],))
5799 self.assertEqual(get_args(Union[int, Tuple[T, int]][str]),
5800 (int, Tuple[str, int]))
5801 self.assertEqual(get_args(typing.Dict[int, Tuple[T, T]][Optional[int]]),
5802 (int, Tuple[Optional[int], Optional[int]]))
5803 self.assertEqual(get_args(Callable[[], T][int]), ([], int))
5804 self.assertEqual(get_args(Callable[..., int]), (..., int))
5805 self.assertEqual(get_args(Union[int, Callable[[Tuple[T, ...]], str]]),
5806 (int, Callable[[Tuple[T, ...]], str]))
5807 self.assertEqual(get_args(Tuple[int, ...]), (int, ...))
5808 self.assertEqual(get_args(Tuple[()]), ())
5809 self.assertEqual(get_args(Annotated[T, 'one', 2, ['three']]), (T, 'one', 2, ['three']))
5810 self.assertEqual(get_args(List), ())
5811 self.assertEqual(get_args(Tuple), ())
5812 self.assertEqual(get_args(Callable), ())
5813 self.assertEqual(get_args(list[int]), (int,))
5814 self.assertEqual(get_args(list), ())
5815 self.assertEqual(get_args(collections.abc.Callable[[int], str]), ([int], str))
5816 self.assertEqual(get_args(collections.abc.Callable[..., str]), (..., str))
5817 self.assertEqual(get_args(collections.abc.Callable[[], str]), ([], str))
5818 self.assertEqual(get_args(collections.abc.Callable[[int], str]),
5819 get_args(Callable[[int], str]))
5820 P = ParamSpec('P')
5821 self.assertEqual(get_args(Callable[P, int]), (P, int))
5822 self.assertEqual(get_args(Callable[Concatenate[int, P], int]),
5823 (Concatenate[int, P], int))
5824 self.assertEqual(get_args(list | str), (list, str))
5825 self.assertEqual(get_args(Required[int]), (int,))
5826 self.assertEqual(get_args(NotRequired[int]), (int,))
5827 self.assertEqual(get_args(TypeAlias), ())
5828 self.assertEqual(get_args(TypeGuard[int]), (int,))
5829 Ts = TypeVarTuple('Ts')
5830 self.assertEqual(get_args(Ts), ())
5831 self.assertEqual(get_args((*Ts,)[0]), (Ts,))
5832 self.assertEqual(get_args(Unpack[Ts]), (Ts,))
5833 self.assertEqual(get_args(tuple[*Ts]), (*Ts,))
5834 self.assertEqual(get_args(tuple[Unpack[Ts]]), (Unpack[Ts],))
5835 self.assertEqual(get_args((*tuple[*Ts],)[0]), (*Ts,))
5836 self.assertEqual(get_args(Unpack[tuple[Unpack[Ts]]]), (tuple[Unpack[Ts]],))
5837
5838
5839 class CollectionsAbcTests(BaseTestCase):
5840
5841 def test_hashable(self):
5842 self.assertIsInstance(42, typing.Hashable)
5843 self.assertNotIsInstance([], typing.Hashable)
5844
5845 def test_iterable(self):
5846 self.assertIsInstance([], typing.Iterable)
5847 # Due to ABC caching, the second time takes a separate code
5848 # path and could fail. So call this a few times.
5849 self.assertIsInstance([], typing.Iterable)
5850 self.assertIsInstance([], typing.Iterable)
5851 self.assertNotIsInstance(42, typing.Iterable)
5852 # Just in case, also test issubclass() a few times.
5853 self.assertIsSubclass(list, typing.Iterable)
5854 self.assertIsSubclass(list, typing.Iterable)
5855
5856 def test_iterator(self):
5857 it = iter([])
5858 self.assertIsInstance(it, typing.Iterator)
5859 self.assertNotIsInstance(42, typing.Iterator)
5860
5861 def test_awaitable(self):
5862 ns = {}
5863 exec(
5864 "async def foo() -> typing.Awaitable[int]:\n"
5865 " return await AwaitableWrapper(42)\n",
5866 globals(), ns)
5867 foo = ns['foo']
5868 g = foo()
5869 self.assertIsInstance(g, typing.Awaitable)
5870 self.assertNotIsInstance(foo, typing.Awaitable)
5871 g.send(None) # Run foo() till completion, to avoid warning.
5872
5873 def test_coroutine(self):
5874 ns = {}
5875 exec(
5876 "async def foo():\n"
5877 " return\n",
5878 globals(), ns)
5879 foo = ns['foo']
5880 g = foo()
5881 self.assertIsInstance(g, typing.Coroutine)
5882 with self.assertRaises(TypeError):
5883 isinstance(g, typing.Coroutine[int])
5884 self.assertNotIsInstance(foo, typing.Coroutine)
5885 try:
5886 g.send(None)
5887 except StopIteration:
5888 pass
5889
5890 def test_async_iterable(self):
5891 base_it = range(10) # type: Iterator[int]
5892 it = AsyncIteratorWrapper(base_it)
5893 self.assertIsInstance(it, typing.AsyncIterable)
5894 self.assertIsInstance(it, typing.AsyncIterable)
5895 self.assertNotIsInstance(42, typing.AsyncIterable)
5896
5897 def test_async_iterator(self):
5898 base_it = range(10) # type: Iterator[int]
5899 it = AsyncIteratorWrapper(base_it)
5900 self.assertIsInstance(it, typing.AsyncIterator)
5901 self.assertNotIsInstance(42, typing.AsyncIterator)
5902
5903 def test_sized(self):
5904 self.assertIsInstance([], typing.Sized)
5905 self.assertNotIsInstance(42, typing.Sized)
5906
5907 def test_container(self):
5908 self.assertIsInstance([], typing.Container)
5909 self.assertNotIsInstance(42, typing.Container)
5910
5911 def test_collection(self):
5912 self.assertIsInstance(tuple(), typing.Collection)
5913 self.assertIsInstance(frozenset(), typing.Collection)
5914 self.assertIsSubclass(dict, typing.Collection)
5915 self.assertNotIsInstance(42, typing.Collection)
5916
5917 def test_abstractset(self):
5918 self.assertIsInstance(set(), typing.AbstractSet)
5919 self.assertNotIsInstance(42, typing.AbstractSet)
5920
5921 def test_mutableset(self):
5922 self.assertIsInstance(set(), typing.MutableSet)
5923 self.assertNotIsInstance(frozenset(), typing.MutableSet)
5924
5925 def test_mapping(self):
5926 self.assertIsInstance({}, typing.Mapping)
5927 self.assertNotIsInstance(42, typing.Mapping)
5928
5929 def test_mutablemapping(self):
5930 self.assertIsInstance({}, typing.MutableMapping)
5931 self.assertNotIsInstance(42, typing.MutableMapping)
5932
5933 def test_sequence(self):
5934 self.assertIsInstance([], typing.Sequence)
5935 self.assertNotIsInstance(42, typing.Sequence)
5936
5937 def test_mutablesequence(self):
5938 self.assertIsInstance([], typing.MutableSequence)
5939 self.assertNotIsInstance((), typing.MutableSequence)
5940
5941 def test_bytestring(self):
5942 self.assertIsInstance(b'', typing.ByteString)
5943 self.assertIsInstance(bytearray(b''), typing.ByteString)
5944
5945 def test_list(self):
5946 self.assertIsSubclass(list, typing.List)
5947
5948 def test_deque(self):
5949 self.assertIsSubclass(collections.deque, typing.Deque)
5950 class MyDeque(typing.Deque[int]): ...
5951 self.assertIsInstance(MyDeque(), collections.deque)
5952
5953 def test_counter(self):
5954 self.assertIsSubclass(collections.Counter, typing.Counter)
5955
5956 def test_set(self):
5957 self.assertIsSubclass(set, typing.Set)
5958 self.assertNotIsSubclass(frozenset, typing.Set)
5959
5960 def test_frozenset(self):
5961 self.assertIsSubclass(frozenset, typing.FrozenSet)
5962 self.assertNotIsSubclass(set, typing.FrozenSet)
5963
5964 def test_dict(self):
5965 self.assertIsSubclass(dict, typing.Dict)
5966
5967 def test_dict_subscribe(self):
5968 K = TypeVar('K')
5969 V = TypeVar('V')
5970 self.assertEqual(Dict[K, V][str, int], Dict[str, int])
5971 self.assertEqual(Dict[K, int][str], Dict[str, int])
5972 self.assertEqual(Dict[str, V][int], Dict[str, int])
5973 self.assertEqual(Dict[K, List[V]][str, int], Dict[str, List[int]])
5974 self.assertEqual(Dict[K, List[int]][str], Dict[str, List[int]])
5975 self.assertEqual(Dict[K, list[V]][str, int], Dict[str, list[int]])
5976 self.assertEqual(Dict[K, list[int]][str], Dict[str, list[int]])
5977
5978 def test_no_list_instantiation(self):
5979 with self.assertRaises(TypeError):
5980 typing.List()
5981 with self.assertRaises(TypeError):
5982 typing.List[T]()
5983 with self.assertRaises(TypeError):
5984 typing.List[int]()
5985
5986 def test_list_subclass(self):
5987
5988 class MyList(typing.List[int]):
5989 pass
5990
5991 a = MyList()
5992 self.assertIsInstance(a, MyList)
5993 self.assertIsInstance(a, typing.Sequence)
5994
5995 self.assertIsSubclass(MyList, list)
5996 self.assertNotIsSubclass(list, MyList)
5997
5998 def test_no_dict_instantiation(self):
5999 with self.assertRaises(TypeError):
6000 typing.Dict()
6001 with self.assertRaises(TypeError):
6002 typing.Dict[KT, VT]()
6003 with self.assertRaises(TypeError):
6004 typing.Dict[str, int]()
6005
6006 def test_dict_subclass(self):
6007
6008 class MyDict(typing.Dict[str, int]):
6009 pass
6010
6011 d = MyDict()
6012 self.assertIsInstance(d, MyDict)
6013 self.assertIsInstance(d, typing.MutableMapping)
6014
6015 self.assertIsSubclass(MyDict, dict)
6016 self.assertNotIsSubclass(dict, MyDict)
6017
6018 def test_defaultdict_instantiation(self):
6019 self.assertIs(type(typing.DefaultDict()), collections.defaultdict)
6020 self.assertIs(type(typing.DefaultDict[KT, VT]()), collections.defaultdict)
6021 self.assertIs(type(typing.DefaultDict[str, int]()), collections.defaultdict)
6022
6023 def test_defaultdict_subclass(self):
6024
6025 class MyDefDict(typing.DefaultDict[str, int]):
6026 pass
6027
6028 dd = MyDefDict()
6029 self.assertIsInstance(dd, MyDefDict)
6030
6031 self.assertIsSubclass(MyDefDict, collections.defaultdict)
6032 self.assertNotIsSubclass(collections.defaultdict, MyDefDict)
6033
6034 def test_ordereddict_instantiation(self):
6035 self.assertIs(type(typing.OrderedDict()), collections.OrderedDict)
6036 self.assertIs(type(typing.OrderedDict[KT, VT]()), collections.OrderedDict)
6037 self.assertIs(type(typing.OrderedDict[str, int]()), collections.OrderedDict)
6038
6039 def test_ordereddict_subclass(self):
6040
6041 class MyOrdDict(typing.OrderedDict[str, int]):
6042 pass
6043
6044 od = MyOrdDict()
6045 self.assertIsInstance(od, MyOrdDict)
6046
6047 self.assertIsSubclass(MyOrdDict, collections.OrderedDict)
6048 self.assertNotIsSubclass(collections.OrderedDict, MyOrdDict)
6049
6050 def test_chainmap_instantiation(self):
6051 self.assertIs(type(typing.ChainMap()), collections.ChainMap)
6052 self.assertIs(type(typing.ChainMap[KT, VT]()), collections.ChainMap)
6053 self.assertIs(type(typing.ChainMap[str, int]()), collections.ChainMap)
6054 class CM(typing.ChainMap[KT, VT]): ...
6055 self.assertIs(type(CM[int, str]()), CM)
6056
6057 def test_chainmap_subclass(self):
6058
6059 class MyChainMap(typing.ChainMap[str, int]):
6060 pass
6061
6062 cm = MyChainMap()
6063 self.assertIsInstance(cm, MyChainMap)
6064
6065 self.assertIsSubclass(MyChainMap, collections.ChainMap)
6066 self.assertNotIsSubclass(collections.ChainMap, MyChainMap)
6067
6068 def test_deque_instantiation(self):
6069 self.assertIs(type(typing.Deque()), collections.deque)
6070 self.assertIs(type(typing.Deque[T]()), collections.deque)
6071 self.assertIs(type(typing.Deque[int]()), collections.deque)
6072 class D(typing.Deque[T]): ...
6073 self.assertIs(type(D[int]()), D)
6074
6075 def test_counter_instantiation(self):
6076 self.assertIs(type(typing.Counter()), collections.Counter)
6077 self.assertIs(type(typing.Counter[T]()), collections.Counter)
6078 self.assertIs(type(typing.Counter[int]()), collections.Counter)
6079 class C(typing.Counter[T]): ...
6080 self.assertIs(type(C[int]()), C)
6081
6082 def test_counter_subclass_instantiation(self):
6083
6084 class MyCounter(typing.Counter[int]):
6085 pass
6086
6087 d = MyCounter()
6088 self.assertIsInstance(d, MyCounter)
6089 self.assertIsInstance(d, typing.Counter)
6090 self.assertIsInstance(d, collections.Counter)
6091
6092 def test_no_set_instantiation(self):
6093 with self.assertRaises(TypeError):
6094 typing.Set()
6095 with self.assertRaises(TypeError):
6096 typing.Set[T]()
6097 with self.assertRaises(TypeError):
6098 typing.Set[int]()
6099
6100 def test_set_subclass_instantiation(self):
6101
6102 class MySet(typing.Set[int]):
6103 pass
6104
6105 d = MySet()
6106 self.assertIsInstance(d, MySet)
6107
6108 def test_no_frozenset_instantiation(self):
6109 with self.assertRaises(TypeError):
6110 typing.FrozenSet()
6111 with self.assertRaises(TypeError):
6112 typing.FrozenSet[T]()
6113 with self.assertRaises(TypeError):
6114 typing.FrozenSet[int]()
6115
6116 def test_frozenset_subclass_instantiation(self):
6117
6118 class MyFrozenSet(typing.FrozenSet[int]):
6119 pass
6120
6121 d = MyFrozenSet()
6122 self.assertIsInstance(d, MyFrozenSet)
6123
6124 def test_no_tuple_instantiation(self):
6125 with self.assertRaises(TypeError):
6126 Tuple()
6127 with self.assertRaises(TypeError):
6128 Tuple[T]()
6129 with self.assertRaises(TypeError):
6130 Tuple[int]()
6131
6132 def test_generator(self):
6133 def foo():
6134 yield 42
6135 g = foo()
6136 self.assertIsSubclass(type(g), typing.Generator)
6137
6138 def test_no_generator_instantiation(self):
6139 with self.assertRaises(TypeError):
6140 typing.Generator()
6141 with self.assertRaises(TypeError):
6142 typing.Generator[T, T, T]()
6143 with self.assertRaises(TypeError):
6144 typing.Generator[int, int, int]()
6145
6146 def test_async_generator(self):
6147 ns = {}
6148 exec("async def f():\n"
6149 " yield 42\n", globals(), ns)
6150 g = ns['f']()
6151 self.assertIsSubclass(type(g), typing.AsyncGenerator)
6152
6153 def test_no_async_generator_instantiation(self):
6154 with self.assertRaises(TypeError):
6155 typing.AsyncGenerator()
6156 with self.assertRaises(TypeError):
6157 typing.AsyncGenerator[T, T]()
6158 with self.assertRaises(TypeError):
6159 typing.AsyncGenerator[int, int]()
6160
6161 def test_subclassing(self):
6162
6163 class MMA(typing.MutableMapping):
6164 pass
6165
6166 with self.assertRaises(TypeError): # It's abstract
6167 MMA()
6168
6169 class MMC(MMA):
6170 def __getitem__(self, k):
6171 return None
6172 def __setitem__(self, k, v):
6173 pass
6174 def __delitem__(self, k):
6175 pass
6176 def __iter__(self):
6177 return iter(())
6178 def __len__(self):
6179 return 0
6180
6181 self.assertEqual(len(MMC()), 0)
6182 self.assertTrue(callable(MMC.update))
6183 self.assertIsInstance(MMC(), typing.Mapping)
6184
6185 class MMB(typing.MutableMapping[KT, VT]):
6186 def __getitem__(self, k):
6187 return None
6188 def __setitem__(self, k, v):
6189 pass
6190 def __delitem__(self, k):
6191 pass
6192 def __iter__(self):
6193 return iter(())
6194 def __len__(self):
6195 return 0
6196
6197 self.assertEqual(len(MMB()), 0)
6198 self.assertEqual(len(MMB[str, str]()), 0)
6199 self.assertEqual(len(MMB[KT, VT]()), 0)
6200
6201 self.assertNotIsSubclass(dict, MMA)
6202 self.assertNotIsSubclass(dict, MMB)
6203
6204 self.assertIsSubclass(MMA, typing.Mapping)
6205 self.assertIsSubclass(MMB, typing.Mapping)
6206 self.assertIsSubclass(MMC, typing.Mapping)
6207
6208 self.assertIsInstance(MMB[KT, VT](), typing.Mapping)
6209 self.assertIsInstance(MMB[KT, VT](), collections.abc.Mapping)
6210
6211 self.assertIsSubclass(MMA, collections.abc.Mapping)
6212 self.assertIsSubclass(MMB, collections.abc.Mapping)
6213 self.assertIsSubclass(MMC, collections.abc.Mapping)
6214
6215 with self.assertRaises(TypeError):
6216 issubclass(MMB[str, str], typing.Mapping)
6217 self.assertIsSubclass(MMC, MMA)
6218
6219 class I(typing.Iterable): ...
6220 self.assertNotIsSubclass(list, I)
6221
6222 class G(typing.Generator[int, int, int]): ...
6223 def g(): yield 0
6224 self.assertIsSubclass(G, typing.Generator)
6225 self.assertIsSubclass(G, typing.Iterable)
6226 self.assertIsSubclass(G, collections.abc.Generator)
6227 self.assertIsSubclass(G, collections.abc.Iterable)
6228 self.assertNotIsSubclass(type(g), G)
6229
6230 def test_subclassing_async_generator(self):
6231 class G(typing.AsyncGenerator[int, int]):
6232 def asend(self, value):
6233 pass
6234 def athrow(self, typ, val=None, tb=None):
6235 pass
6236
6237 ns = {}
6238 exec('async def g(): yield 0', globals(), ns)
6239 g = ns['g']
6240 self.assertIsSubclass(G, typing.AsyncGenerator)
6241 self.assertIsSubclass(G, typing.AsyncIterable)
6242 self.assertIsSubclass(G, collections.abc.AsyncGenerator)
6243 self.assertIsSubclass(G, collections.abc.AsyncIterable)
6244 self.assertNotIsSubclass(type(g), G)
6245
6246 instance = G()
6247 self.assertIsInstance(instance, typing.AsyncGenerator)
6248 self.assertIsInstance(instance, typing.AsyncIterable)
6249 self.assertIsInstance(instance, collections.abc.AsyncGenerator)
6250 self.assertIsInstance(instance, collections.abc.AsyncIterable)
6251 self.assertNotIsInstance(type(g), G)
6252 self.assertNotIsInstance(g, G)
6253
6254 def test_subclassing_subclasshook(self):
6255
6256 class Base(typing.Iterable):
6257 @classmethod
6258 def __subclasshook__(cls, other):
6259 if other.__name__ == 'Foo':
6260 return True
6261 else:
6262 return False
6263
6264 class C(Base): ...
6265 class Foo: ...
6266 class Bar: ...
6267 self.assertIsSubclass(Foo, Base)
6268 self.assertIsSubclass(Foo, C)
6269 self.assertNotIsSubclass(Bar, C)
6270
6271 def test_subclassing_register(self):
6272
6273 class A(typing.Container): ...
6274 class B(A): ...
6275
6276 class C: ...
6277 A.register(C)
6278 self.assertIsSubclass(C, A)
6279 self.assertNotIsSubclass(C, B)
6280
6281 class D: ...
6282 B.register(D)
6283 self.assertIsSubclass(D, A)
6284 self.assertIsSubclass(D, B)
6285
6286 class M(): ...
6287 collections.abc.MutableMapping.register(M)
6288 self.assertIsSubclass(M, typing.Mapping)
6289
6290 def test_collections_as_base(self):
6291
6292 class M(collections.abc.Mapping): ...
6293 self.assertIsSubclass(M, typing.Mapping)
6294 self.assertIsSubclass(M, typing.Iterable)
6295
6296 class S(collections.abc.MutableSequence): ...
6297 self.assertIsSubclass(S, typing.MutableSequence)
6298 self.assertIsSubclass(S, typing.Iterable)
6299
6300 class I(collections.abc.Iterable): ...
6301 self.assertIsSubclass(I, typing.Iterable)
6302
6303 class A(collections.abc.Mapping, metaclass=abc.ABCMeta): ...
6304 class B: ...
6305 A.register(B)
6306 self.assertIsSubclass(B, typing.Mapping)
6307
6308 def test_or_and_ror(self):
6309 self.assertEqual(typing.Sized | typing.Awaitable, Union[typing.Sized, typing.Awaitable])
6310 self.assertEqual(typing.Coroutine | typing.Hashable, Union[typing.Coroutine, typing.Hashable])
6311
6312
6313 class OtherABCTests(BaseTestCase):
6314
6315 def test_contextmanager(self):
6316 @contextlib.contextmanager
6317 def manager():
6318 yield 42
6319
6320 cm = manager()
6321 self.assertIsInstance(cm, typing.ContextManager)
6322 self.assertNotIsInstance(42, typing.ContextManager)
6323
6324 def test_async_contextmanager(self):
6325 class NotACM:
6326 pass
6327 self.assertIsInstance(ACM(), typing.AsyncContextManager)
6328 self.assertNotIsInstance(NotACM(), typing.AsyncContextManager)
6329 @contextlib.contextmanager
6330 def manager():
6331 yield 42
6332
6333 cm = manager()
6334 self.assertNotIsInstance(cm, typing.AsyncContextManager)
6335 self.assertEqual(typing.AsyncContextManager[int].__args__, (int,))
6336 with self.assertRaises(TypeError):
6337 isinstance(42, typing.AsyncContextManager[int])
6338 with self.assertRaises(TypeError):
6339 typing.AsyncContextManager[int, str]
6340
6341
6342 class TypeTests(BaseTestCase):
6343
6344 def test_type_basic(self):
6345
6346 class User: pass
6347 class BasicUser(User): pass
6348 class ProUser(User): pass
6349
6350 def new_user(user_class: Type[User]) -> User:
6351 return user_class()
6352
6353 new_user(BasicUser)
6354
6355 def test_type_typevar(self):
6356
6357 class User: pass
6358 class BasicUser(User): pass
6359 class ProUser(User): pass
6360
6361 U = TypeVar('U', bound=User)
6362
6363 def new_user(user_class: Type[U]) -> U:
6364 return user_class()
6365
6366 new_user(BasicUser)
6367
6368 def test_type_optional(self):
6369 A = Optional[Type[BaseException]]
6370
6371 def foo(a: A) -> Optional[BaseException]:
6372 if a is None:
6373 return None
6374 else:
6375 return a()
6376
6377 self.assertIsInstance(foo(KeyboardInterrupt), KeyboardInterrupt)
6378 self.assertIsNone(foo(None))
6379
6380
6381 class TestModules(TestCase):
6382 func_names = ['_idfunc']
6383
6384 def test_py_functions(self):
6385 for fname in self.func_names:
6386 self.assertEqual(getattr(py_typing, fname).__module__, 'typing')
6387
6388 @skipUnless(c_typing, 'requires _typing')
6389 def test_c_functions(self):
6390 for fname in self.func_names:
6391 self.assertEqual(getattr(c_typing, fname).__module__, '_typing')
6392
6393
6394 class NewTypeTests:
6395 def cleanup(self):
6396 for f in self.module._cleanups:
6397 f()
6398
6399 @classmethod
6400 def setUpClass(cls):
6401 sys.modules['typing'] = cls.module
6402 global UserId
6403 UserId = cls.module.NewType('UserId', int)
6404 cls.UserName = cls.module.NewType(cls.__qualname__ + '.UserName', str)
6405
6406 @classmethod
6407 def tearDownClass(cls):
6408 global UserId
6409 del UserId
6410 del cls.UserName
6411 sys.modules['typing'] = typing
6412
6413 def tearDown(self):
6414 self.cleanup()
6415
6416 def test_basic(self):
6417 self.assertIsInstance(UserId(5), int)
6418 self.assertIsInstance(self.UserName('Joe'), str)
6419 self.assertEqual(UserId(5) + 1, 6)
6420
6421 def test_errors(self):
6422 with self.assertRaises(TypeError):
6423 issubclass(UserId, int)
6424 with self.assertRaises(TypeError):
6425 class D(UserId):
6426 pass
6427
6428 def test_or(self):
6429 for cls in (int, self.UserName):
6430 with self.subTest(cls=cls):
6431 self.assertEqual(UserId | cls, self.module.Union[UserId, cls])
6432 self.assertEqual(cls | UserId, self.module.Union[cls, UserId])
6433
6434 self.assertEqual(self.module.get_args(UserId | cls), (UserId, cls))
6435 self.assertEqual(self.module.get_args(cls | UserId), (cls, UserId))
6436
6437 def test_special_attrs(self):
6438 self.assertEqual(UserId.__name__, 'UserId')
6439 self.assertEqual(UserId.__qualname__, 'UserId')
6440 self.assertEqual(UserId.__module__, __name__)
6441 self.assertEqual(UserId.__supertype__, int)
6442
6443 UserName = self.UserName
6444 self.assertEqual(UserName.__name__, 'UserName')
6445 self.assertEqual(UserName.__qualname__,
6446 self.__class__.__qualname__ + '.UserName')
6447 self.assertEqual(UserName.__module__, __name__)
6448 self.assertEqual(UserName.__supertype__, str)
6449
6450 def test_repr(self):
6451 self.assertEqual(repr(UserId), f'{__name__}.UserId')
6452 self.assertEqual(repr(self.UserName),
6453 f'{__name__}.{self.__class__.__qualname__}.UserName')
6454
6455 def test_pickle(self):
6456 UserAge = self.module.NewType('UserAge', float)
6457 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
6458 with self.subTest(proto=proto):
6459 pickled = pickle.dumps(UserId, proto)
6460 loaded = pickle.loads(pickled)
6461 self.assertIs(loaded, UserId)
6462
6463 pickled = pickle.dumps(self.UserName, proto)
6464 loaded = pickle.loads(pickled)
6465 self.assertIs(loaded, self.UserName)
6466
6467 with self.assertRaises(pickle.PicklingError):
6468 pickle.dumps(UserAge, proto)
6469
6470 def test_missing__name__(self):
6471 code = ("import typing\n"
6472 "NT = typing.NewType('NT', int)\n"
6473 )
6474 exec(code, {})
6475
6476 def test_error_message_when_subclassing(self):
6477 with self.assertRaisesRegex(
6478 TypeError,
6479 re.escape(
6480 "Cannot subclass an instance of NewType. Perhaps you were looking for: "
6481 "`ProUserId = NewType('ProUserId', UserId)`"
6482 )
6483 ):
6484 class ProUserId(UserId):
6485 ...
6486
6487
6488 class NewTypePythonTests(NewTypeTests, BaseTestCase):
6489 module = py_typing
6490
6491
6492 @skipUnless(c_typing, 'requires _typing')
6493 class NewTypeCTests(NewTypeTests, BaseTestCase):
6494 module = c_typing
6495
6496
6497 class NamedTupleTests(BaseTestCase):
6498 class NestedEmployee(NamedTuple):
6499 name: str
6500 cool: int
6501
6502 def test_basics(self):
6503 Emp = NamedTuple('Emp', [('name', str), ('id', int)])
6504 self.assertIsSubclass(Emp, tuple)
6505 joe = Emp('Joe', 42)
6506 jim = Emp(name='Jim', id=1)
6507 self.assertIsInstance(joe, Emp)
6508 self.assertIsInstance(joe, tuple)
6509 self.assertEqual(joe.name, 'Joe')
6510 self.assertEqual(joe.id, 42)
6511 self.assertEqual(jim.name, 'Jim')
6512 self.assertEqual(jim.id, 1)
6513 self.assertEqual(Emp.__name__, 'Emp')
6514 self.assertEqual(Emp._fields, ('name', 'id'))
6515 self.assertEqual(Emp.__annotations__,
6516 collections.OrderedDict([('name', str), ('id', int)]))
6517
6518 def test_annotation_usage(self):
6519 tim = CoolEmployee('Tim', 9000)
6520 self.assertIsInstance(tim, CoolEmployee)
6521 self.assertIsInstance(tim, tuple)
6522 self.assertEqual(tim.name, 'Tim')
6523 self.assertEqual(tim.cool, 9000)
6524 self.assertEqual(CoolEmployee.__name__, 'CoolEmployee')
6525 self.assertEqual(CoolEmployee._fields, ('name', 'cool'))
6526 self.assertEqual(CoolEmployee.__annotations__,
6527 collections.OrderedDict(name=str, cool=int))
6528
6529 def test_annotation_usage_with_default(self):
6530 jelle = CoolEmployeeWithDefault('Jelle')
6531 self.assertIsInstance(jelle, CoolEmployeeWithDefault)
6532 self.assertIsInstance(jelle, tuple)
6533 self.assertEqual(jelle.name, 'Jelle')
6534 self.assertEqual(jelle.cool, 0)
6535 cooler_employee = CoolEmployeeWithDefault('Sjoerd', 1)
6536 self.assertEqual(cooler_employee.cool, 1)
6537
6538 self.assertEqual(CoolEmployeeWithDefault.__name__, 'CoolEmployeeWithDefault')
6539 self.assertEqual(CoolEmployeeWithDefault._fields, ('name', 'cool'))
6540 self.assertEqual(CoolEmployeeWithDefault.__annotations__,
6541 dict(name=str, cool=int))
6542 self.assertEqual(CoolEmployeeWithDefault._field_defaults, dict(cool=0))
6543
6544 with self.assertRaises(TypeError):
6545 class NonDefaultAfterDefault(NamedTuple):
6546 x: int = 3
6547 y: int
6548
6549 def test_annotation_usage_with_methods(self):
6550 self.assertEqual(XMeth(1).double(), 2)
6551 self.assertEqual(XMeth(42).x, XMeth(42)[0])
6552 self.assertEqual(str(XRepr(42)), '42 -> 1')
6553 self.assertEqual(XRepr(1, 2) + XRepr(3), 0)
6554
6555 with self.assertRaises(AttributeError):
6556 class XMethBad(NamedTuple):
6557 x: int
6558 def _fields(self):
6559 return 'no chance for this'
6560
6561 with self.assertRaises(AttributeError):
6562 class XMethBad2(NamedTuple):
6563 x: int
6564 def _source(self):
6565 return 'no chance for this as well'
6566
6567 def test_multiple_inheritance(self):
6568 class A:
6569 pass
6570 with self.assertRaises(TypeError):
6571 class X(NamedTuple, A):
6572 x: int
6573 with self.assertRaises(TypeError):
6574 class Y(NamedTuple, tuple):
6575 x: int
6576 with self.assertRaises(TypeError):
6577 class Z(NamedTuple, NamedTuple):
6578 x: int
6579 class B(NamedTuple):
6580 x: int
6581 with self.assertRaises(TypeError):
6582 class C(NamedTuple, B):
6583 y: str
6584
6585 def test_generic(self):
6586 class X(NamedTuple, Generic[T]):
6587 x: T
6588 self.assertEqual(X.__bases__, (tuple, Generic))
6589 self.assertEqual(X.__orig_bases__, (NamedTuple, Generic[T]))
6590 self.assertEqual(X.__mro__, (X, tuple, Generic, object))
6591
6592 class Y(Generic[T], NamedTuple):
6593 x: T
6594 self.assertEqual(Y.__bases__, (Generic, tuple))
6595 self.assertEqual(Y.__orig_bases__, (Generic[T], NamedTuple))
6596 self.assertEqual(Y.__mro__, (Y, Generic, tuple, object))
6597
6598 for G in X, Y:
6599 with self.subTest(type=G):
6600 self.assertEqual(G.__parameters__, (T,))
6601 A = G[int]
6602 self.assertIs(A.__origin__, G)
6603 self.assertEqual(A.__args__, (int,))
6604 self.assertEqual(A.__parameters__, ())
6605
6606 a = A(3)
6607 self.assertIs(type(a), G)
6608 self.assertEqual(a.x, 3)
6609
6610 with self.assertRaises(TypeError):
6611 G[int, str]
6612
6613 def test_non_generic_subscript(self):
6614 # For backward compatibility, subscription works
6615 # on arbitrary NamedTuple types.
6616 class Group(NamedTuple):
6617 key: T
6618 group: list[T]
6619 A = Group[int]
6620 self.assertEqual(A.__origin__, Group)
6621 self.assertEqual(A.__parameters__, ())
6622 self.assertEqual(A.__args__, (int,))
6623 a = A(1, [2])
6624 self.assertIs(type(a), Group)
6625 self.assertEqual(a, (1, [2]))
6626
6627 def test_namedtuple_keyword_usage(self):
6628 LocalEmployee = NamedTuple("LocalEmployee", name=str, age=int)
6629 nick = LocalEmployee('Nick', 25)
6630 self.assertIsInstance(nick, tuple)
6631 self.assertEqual(nick.name, 'Nick')
6632 self.assertEqual(LocalEmployee.__name__, 'LocalEmployee')
6633 self.assertEqual(LocalEmployee._fields, ('name', 'age'))
6634 self.assertEqual(LocalEmployee.__annotations__, dict(name=str, age=int))
6635 with self.assertRaises(TypeError):
6636 NamedTuple('Name', [('x', int)], y=str)
6637
6638 def test_namedtuple_special_keyword_names(self):
6639 NT = NamedTuple("NT", cls=type, self=object, typename=str, fields=list)
6640 self.assertEqual(NT.__name__, 'NT')
6641 self.assertEqual(NT._fields, ('cls', 'self', 'typename', 'fields'))
6642 a = NT(cls=str, self=42, typename='foo', fields=[('bar', tuple)])
6643 self.assertEqual(a.cls, str)
6644 self.assertEqual(a.self, 42)
6645 self.assertEqual(a.typename, 'foo')
6646 self.assertEqual(a.fields, [('bar', tuple)])
6647
6648 def test_empty_namedtuple(self):
6649 NT = NamedTuple('NT')
6650
6651 class CNT(NamedTuple):
6652 pass # empty body
6653
6654 for struct in [NT, CNT]:
6655 with self.subTest(struct=struct):
6656 self.assertEqual(struct._fields, ())
6657 self.assertEqual(struct._field_defaults, {})
6658 self.assertEqual(struct.__annotations__, {})
6659 self.assertIsInstance(struct(), struct)
6660
6661 def test_namedtuple_errors(self):
6662 with self.assertRaises(TypeError):
6663 NamedTuple.__new__()
6664 with self.assertRaises(TypeError):
6665 NamedTuple()
6666 with self.assertRaises(TypeError):
6667 NamedTuple('Emp', [('name', str)], None)
6668 with self.assertRaises(ValueError):
6669 NamedTuple('Emp', [('_name', str)])
6670 with self.assertRaises(TypeError):
6671 NamedTuple(typename='Emp', name=str, id=int)
6672
6673 def test_copy_and_pickle(self):
6674 global Emp # pickle wants to reference the class by name
6675 Emp = NamedTuple('Emp', [('name', str), ('cool', int)])
6676 for cls in Emp, CoolEmployee, self.NestedEmployee:
6677 with self.subTest(cls=cls):
6678 jane = cls('jane', 37)
6679 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
6680 z = pickle.dumps(jane, proto)
6681 jane2 = pickle.loads(z)
6682 self.assertEqual(jane2, jane)
6683 self.assertIsInstance(jane2, cls)
6684
6685 jane2 = copy(jane)
6686 self.assertEqual(jane2, jane)
6687 self.assertIsInstance(jane2, cls)
6688
6689 jane2 = deepcopy(jane)
6690 self.assertEqual(jane2, jane)
6691 self.assertIsInstance(jane2, cls)
6692
6693
6694 class TypedDictTests(BaseTestCase):
6695 def test_basics_functional_syntax(self):
6696 Emp = TypedDict('Emp', {'name': str, 'id': int})
6697 self.assertIsSubclass(Emp, dict)
6698 self.assertIsSubclass(Emp, typing.MutableMapping)
6699 self.assertNotIsSubclass(Emp, collections.abc.Sequence)
6700 jim = Emp(name='Jim', id=1)
6701 self.assertIs(type(jim), dict)
6702 self.assertEqual(jim['name'], 'Jim')
6703 self.assertEqual(jim['id'], 1)
6704 self.assertEqual(Emp.__name__, 'Emp')
6705 self.assertEqual(Emp.__module__, __name__)
6706 self.assertEqual(Emp.__bases__, (dict,))
6707 self.assertEqual(Emp.__annotations__, {'name': str, 'id': int})
6708 self.assertEqual(Emp.__total__, True)
6709 self.assertEqual(Emp.__required_keys__, {'name', 'id'})
6710 self.assertIsInstance(Emp.__required_keys__, frozenset)
6711 self.assertEqual(Emp.__optional_keys__, set())
6712 self.assertIsInstance(Emp.__optional_keys__, frozenset)
6713
6714 def test_basics_keywords_syntax(self):
6715 with self.assertWarns(DeprecationWarning):
6716 Emp = TypedDict('Emp', name=str, id=int)
6717 self.assertIsSubclass(Emp, dict)
6718 self.assertIsSubclass(Emp, typing.MutableMapping)
6719 self.assertNotIsSubclass(Emp, collections.abc.Sequence)
6720 jim = Emp(name='Jim', id=1)
6721 self.assertIs(type(jim), dict)
6722 self.assertEqual(jim['name'], 'Jim')
6723 self.assertEqual(jim['id'], 1)
6724 self.assertEqual(Emp.__name__, 'Emp')
6725 self.assertEqual(Emp.__module__, __name__)
6726 self.assertEqual(Emp.__bases__, (dict,))
6727 self.assertEqual(Emp.__annotations__, {'name': str, 'id': int})
6728 self.assertEqual(Emp.__total__, True)
6729
6730 def test_typeddict_special_keyword_names(self):
6731 with self.assertWarns(DeprecationWarning):
6732 TD = TypedDict("TD", cls=type, self=object, typename=str, _typename=int, fields=list, _fields=dict)
6733 self.assertEqual(TD.__name__, 'TD')
6734 self.assertEqual(TD.__annotations__, {'cls': type, 'self': object, 'typename': str, '_typename': int, 'fields': list, '_fields': dict})
6735 a = TD(cls=str, self=42, typename='foo', _typename=53, fields=[('bar', tuple)], _fields={'baz', set})
6736 self.assertEqual(a['cls'], str)
6737 self.assertEqual(a['self'], 42)
6738 self.assertEqual(a['typename'], 'foo')
6739 self.assertEqual(a['_typename'], 53)
6740 self.assertEqual(a['fields'], [('bar', tuple)])
6741 self.assertEqual(a['_fields'], {'baz', set})
6742
6743 def test_typeddict_create_errors(self):
6744 with self.assertRaises(TypeError):
6745 TypedDict.__new__()
6746 with self.assertRaises(TypeError):
6747 TypedDict()
6748 with self.assertRaises(TypeError):
6749 TypedDict('Emp', [('name', str)], None)
6750 with self.assertRaises(TypeError):
6751 TypedDict(_typename='Emp', name=str, id=int)
6752
6753 def test_typeddict_errors(self):
6754 Emp = TypedDict('Emp', {'name': str, 'id': int})
6755 self.assertEqual(TypedDict.__module__, 'typing')
6756 jim = Emp(name='Jim', id=1)
6757 with self.assertRaises(TypeError):
6758 isinstance({}, Emp)
6759 with self.assertRaises(TypeError):
6760 isinstance(jim, Emp)
6761 with self.assertRaises(TypeError):
6762 issubclass(dict, Emp)
6763 with self.assertRaises(TypeError):
6764 TypedDict('Hi', [('x', int)], y=int)
6765
6766 def test_py36_class_syntax_usage(self):
6767 self.assertEqual(LabelPoint2D.__name__, 'LabelPoint2D')
6768 self.assertEqual(LabelPoint2D.__module__, __name__)
6769 self.assertEqual(LabelPoint2D.__annotations__, {'x': int, 'y': int, 'label': str})
6770 self.assertEqual(LabelPoint2D.__bases__, (dict,))
6771 self.assertEqual(LabelPoint2D.__total__, True)
6772 self.assertNotIsSubclass(LabelPoint2D, typing.Sequence)
6773 not_origin = Point2D(x=0, y=1)
6774 self.assertEqual(not_origin['x'], 0)
6775 self.assertEqual(not_origin['y'], 1)
6776 other = LabelPoint2D(x=0, y=1, label='hi')
6777 self.assertEqual(other['label'], 'hi')
6778
6779 def test_pickle(self):
6780 global EmpD # pickle wants to reference the class by name
6781 EmpD = TypedDict('EmpD', {'name': str, 'id': int})
6782 jane = EmpD({'name': 'jane', 'id': 37})
6783 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
6784 z = pickle.dumps(jane, proto)
6785 jane2 = pickle.loads(z)
6786 self.assertEqual(jane2, jane)
6787 self.assertEqual(jane2, {'name': 'jane', 'id': 37})
6788 ZZ = pickle.dumps(EmpD, proto)
6789 EmpDnew = pickle.loads(ZZ)
6790 self.assertEqual(EmpDnew({'name': 'jane', 'id': 37}), jane)
6791
6792 def test_pickle_generic(self):
6793 point = Point2DGeneric(a=5.0, b=3.0)
6794 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
6795 z = pickle.dumps(point, proto)
6796 point2 = pickle.loads(z)
6797 self.assertEqual(point2, point)
6798 self.assertEqual(point2, {'a': 5.0, 'b': 3.0})
6799 ZZ = pickle.dumps(Point2DGeneric, proto)
6800 Point2DGenericNew = pickle.loads(ZZ)
6801 self.assertEqual(Point2DGenericNew({'a': 5.0, 'b': 3.0}), point)
6802
6803 def test_optional(self):
6804 EmpD = TypedDict('EmpD', {'name': str, 'id': int})
6805
6806 self.assertEqual(typing.Optional[EmpD], typing.Union[None, EmpD])
6807 self.assertNotEqual(typing.List[EmpD], typing.Tuple[EmpD])
6808
6809 def test_total(self):
6810 D = TypedDict('D', {'x': int}, total=False)
6811 self.assertEqual(D(), {})
6812 self.assertEqual(D(x=1), {'x': 1})
6813 self.assertEqual(D.__total__, False)
6814 self.assertEqual(D.__required_keys__, frozenset())
6815 self.assertIsInstance(D.__required_keys__, frozenset)
6816 self.assertEqual(D.__optional_keys__, {'x'})
6817 self.assertIsInstance(D.__optional_keys__, frozenset)
6818
6819 self.assertEqual(Options(), {})
6820 self.assertEqual(Options(log_level=2), {'log_level': 2})
6821 self.assertEqual(Options.__total__, False)
6822 self.assertEqual(Options.__required_keys__, frozenset())
6823 self.assertEqual(Options.__optional_keys__, {'log_level', 'log_path'})
6824
6825 def test_optional_keys(self):
6826 class Point2Dor3D(Point2D, total=False):
6827 z: int
6828
6829 self.assertEqual(Point2Dor3D.__required_keys__, frozenset(['x', 'y']))
6830 self.assertIsInstance(Point2Dor3D.__required_keys__, frozenset)
6831 self.assertEqual(Point2Dor3D.__optional_keys__, frozenset(['z']))
6832 self.assertIsInstance(Point2Dor3D.__optional_keys__, frozenset)
6833
6834 def test_keys_inheritance(self):
6835 class BaseAnimal(TypedDict):
6836 name: str
6837
6838 class Animal(BaseAnimal, total=False):
6839 voice: str
6840 tail: bool
6841
6842 class Cat(Animal):
6843 fur_color: str
6844
6845 self.assertEqual(BaseAnimal.__required_keys__, frozenset(['name']))
6846 self.assertEqual(BaseAnimal.__optional_keys__, frozenset([]))
6847 self.assertEqual(BaseAnimal.__annotations__, {'name': str})
6848
6849 self.assertEqual(Animal.__required_keys__, frozenset(['name']))
6850 self.assertEqual(Animal.__optional_keys__, frozenset(['tail', 'voice']))
6851 self.assertEqual(Animal.__annotations__, {
6852 'name': str,
6853 'tail': bool,
6854 'voice': str,
6855 })
6856
6857 self.assertEqual(Cat.__required_keys__, frozenset(['name', 'fur_color']))
6858 self.assertEqual(Cat.__optional_keys__, frozenset(['tail', 'voice']))
6859 self.assertEqual(Cat.__annotations__, {
6860 'fur_color': str,
6861 'name': str,
6862 'tail': bool,
6863 'voice': str,
6864 })
6865
6866 def test_keys_inheritance_with_same_name(self):
6867 class NotTotal(TypedDict, total=False):
6868 a: int
6869
6870 class Total(NotTotal):
6871 a: int
6872
6873 self.assertEqual(NotTotal.__required_keys__, frozenset())
6874 self.assertEqual(NotTotal.__optional_keys__, frozenset(['a']))
6875 self.assertEqual(Total.__required_keys__, frozenset(['a']))
6876 self.assertEqual(Total.__optional_keys__, frozenset())
6877
6878 class Base(TypedDict):
6879 a: NotRequired[int]
6880 b: Required[int]
6881
6882 class Child(Base):
6883 a: Required[int]
6884 b: NotRequired[int]
6885
6886 self.assertEqual(Base.__required_keys__, frozenset(['b']))
6887 self.assertEqual(Base.__optional_keys__, frozenset(['a']))
6888 self.assertEqual(Child.__required_keys__, frozenset(['a']))
6889 self.assertEqual(Child.__optional_keys__, frozenset(['b']))
6890
6891 def test_multiple_inheritance_with_same_key(self):
6892 class Base1(TypedDict):
6893 a: NotRequired[int]
6894
6895 class Base2(TypedDict):
6896 a: Required[str]
6897
6898 class Child(Base1, Base2):
6899 pass
6900
6901 # Last base wins
6902 self.assertEqual(Child.__annotations__, {'a': Required[str]})
6903 self.assertEqual(Child.__required_keys__, frozenset(['a']))
6904 self.assertEqual(Child.__optional_keys__, frozenset())
6905
6906 def test_required_notrequired_keys(self):
6907 self.assertEqual(NontotalMovie.__required_keys__,
6908 frozenset({"title"}))
6909 self.assertEqual(NontotalMovie.__optional_keys__,
6910 frozenset({"year"}))
6911
6912 self.assertEqual(TotalMovie.__required_keys__,
6913 frozenset({"title"}))
6914 self.assertEqual(TotalMovie.__optional_keys__,
6915 frozenset({"year"}))
6916
6917 self.assertEqual(_typed_dict_helper.VeryAnnotated.__required_keys__,
6918 frozenset())
6919 self.assertEqual(_typed_dict_helper.VeryAnnotated.__optional_keys__,
6920 frozenset({"a"}))
6921
6922 self.assertEqual(AnnotatedMovie.__required_keys__,
6923 frozenset({"title"}))
6924 self.assertEqual(AnnotatedMovie.__optional_keys__,
6925 frozenset({"year"}))
6926
6927 self.assertEqual(WeirdlyQuotedMovie.__required_keys__,
6928 frozenset({"title"}))
6929 self.assertEqual(WeirdlyQuotedMovie.__optional_keys__,
6930 frozenset({"year"}))
6931
6932 self.assertEqual(ChildTotalMovie.__required_keys__,
6933 frozenset({"title"}))
6934 self.assertEqual(ChildTotalMovie.__optional_keys__,
6935 frozenset({"year"}))
6936
6937 self.assertEqual(ChildDeeplyAnnotatedMovie.__required_keys__,
6938 frozenset({"title"}))
6939 self.assertEqual(ChildDeeplyAnnotatedMovie.__optional_keys__,
6940 frozenset({"year"}))
6941
6942 def test_multiple_inheritance(self):
6943 class One(TypedDict):
6944 one: int
6945 class Two(TypedDict):
6946 two: str
6947 class Untotal(TypedDict, total=False):
6948 untotal: str
6949 Inline = TypedDict('Inline', {'inline': bool})
6950 class Regular:
6951 pass
6952
6953 class Child(One, Two):
6954 child: bool
6955 self.assertEqual(
6956 Child.__required_keys__,
6957 frozenset(['one', 'two', 'child']),
6958 )
6959 self.assertEqual(
6960 Child.__optional_keys__,
6961 frozenset([]),
6962 )
6963 self.assertEqual(
6964 Child.__annotations__,
6965 {'one': int, 'two': str, 'child': bool},
6966 )
6967
6968 class ChildWithOptional(One, Untotal):
6969 child: bool
6970 self.assertEqual(
6971 ChildWithOptional.__required_keys__,
6972 frozenset(['one', 'child']),
6973 )
6974 self.assertEqual(
6975 ChildWithOptional.__optional_keys__,
6976 frozenset(['untotal']),
6977 )
6978 self.assertEqual(
6979 ChildWithOptional.__annotations__,
6980 {'one': int, 'untotal': str, 'child': bool},
6981 )
6982
6983 class ChildWithTotalFalse(One, Untotal, total=False):
6984 child: bool
6985 self.assertEqual(
6986 ChildWithTotalFalse.__required_keys__,
6987 frozenset(['one']),
6988 )
6989 self.assertEqual(
6990 ChildWithTotalFalse.__optional_keys__,
6991 frozenset(['untotal', 'child']),
6992 )
6993 self.assertEqual(
6994 ChildWithTotalFalse.__annotations__,
6995 {'one': int, 'untotal': str, 'child': bool},
6996 )
6997
6998 class ChildWithInlineAndOptional(Untotal, Inline):
6999 child: bool
7000 self.assertEqual(
7001 ChildWithInlineAndOptional.__required_keys__,
7002 frozenset(['inline', 'child']),
7003 )
7004 self.assertEqual(
7005 ChildWithInlineAndOptional.__optional_keys__,
7006 frozenset(['untotal']),
7007 )
7008 self.assertEqual(
7009 ChildWithInlineAndOptional.__annotations__,
7010 {'inline': bool, 'untotal': str, 'child': bool},
7011 )
7012
7013 wrong_bases = [
7014 (One, Regular),
7015 (Regular, One),
7016 (One, Two, Regular),
7017 (Inline, Regular),
7018 (Untotal, Regular),
7019 ]
7020 for bases in wrong_bases:
7021 with self.subTest(bases=bases):
7022 with self.assertRaisesRegex(
7023 TypeError,
7024 'cannot inherit from both a TypedDict type and a non-TypedDict',
7025 ):
7026 class Wrong(*bases):
7027 pass
7028
7029 def test_is_typeddict(self):
7030 self.assertIs(is_typeddict(Point2D), True)
7031 self.assertIs(is_typeddict(Union[str, int]), False)
7032 # classes, not instances
7033 self.assertIs(is_typeddict(Point2D()), False)
7034 call_based = TypedDict('call_based', {'a': int})
7035 self.assertIs(is_typeddict(call_based), True)
7036 self.assertIs(is_typeddict(call_based()), False)
7037
7038 T = TypeVar("T")
7039 class BarGeneric(TypedDict, Generic[T]):
7040 a: T
7041 self.assertIs(is_typeddict(BarGeneric), True)
7042 self.assertIs(is_typeddict(BarGeneric[int]), False)
7043 self.assertIs(is_typeddict(BarGeneric()), False)
7044
7045 # The TypedDict constructor is not itself a TypedDict
7046 self.assertIs(is_typeddict(TypedDict), False)
7047
7048 def test_get_type_hints(self):
7049 self.assertEqual(
7050 get_type_hints(Bar),
7051 {'a': typing.Optional[int], 'b': int}
7052 )
7053
7054 def test_get_type_hints_generic(self):
7055 self.assertEqual(
7056 get_type_hints(BarGeneric),
7057 {'a': typing.Optional[T], 'b': int}
7058 )
7059
7060 class FooBarGeneric(BarGeneric[int]):
7061 c: str
7062
7063 self.assertEqual(
7064 get_type_hints(FooBarGeneric),
7065 {'a': typing.Optional[T], 'b': int, 'c': str}
7066 )
7067
7068 def test_generic_inheritance(self):
7069 class A(TypedDict, Generic[T]):
7070 a: T
7071
7072 self.assertEqual(A.__bases__, (Generic, dict))
7073 self.assertEqual(A.__orig_bases__, (TypedDict, Generic[T]))
7074 self.assertEqual(A.__mro__, (A, Generic, dict, object))
7075 self.assertEqual(A.__parameters__, (T,))
7076 self.assertEqual(A[str].__parameters__, ())
7077 self.assertEqual(A[str].__args__, (str,))
7078
7079 class A2(Generic[T], TypedDict):
7080 a: T
7081
7082 self.assertEqual(A2.__bases__, (Generic, dict))
7083 self.assertEqual(A2.__orig_bases__, (Generic[T], TypedDict))
7084 self.assertEqual(A2.__mro__, (A2, Generic, dict, object))
7085 self.assertEqual(A2.__parameters__, (T,))
7086 self.assertEqual(A2[str].__parameters__, ())
7087 self.assertEqual(A2[str].__args__, (str,))
7088
7089 class B(A[KT], total=False):
7090 b: KT
7091
7092 self.assertEqual(B.__bases__, (Generic, dict))
7093 self.assertEqual(B.__orig_bases__, (A[KT],))
7094 self.assertEqual(B.__mro__, (B, Generic, dict, object))
7095 self.assertEqual(B.__parameters__, (KT,))
7096 self.assertEqual(B.__total__, False)
7097 self.assertEqual(B.__optional_keys__, frozenset(['b']))
7098 self.assertEqual(B.__required_keys__, frozenset(['a']))
7099
7100 self.assertEqual(B[str].__parameters__, ())
7101 self.assertEqual(B[str].__args__, (str,))
7102 self.assertEqual(B[str].__origin__, B)
7103
7104 class C(B[int]):
7105 c: int
7106
7107 self.assertEqual(C.__bases__, (Generic, dict))
7108 self.assertEqual(C.__orig_bases__, (B[int],))
7109 self.assertEqual(C.__mro__, (C, Generic, dict, object))
7110 self.assertEqual(C.__parameters__, ())
7111 self.assertEqual(C.__total__, True)
7112 self.assertEqual(C.__optional_keys__, frozenset(['b']))
7113 self.assertEqual(C.__required_keys__, frozenset(['a', 'c']))
7114 self.assertEqual(C.__annotations__, {
7115 'a': T,
7116 'b': KT,
7117 'c': int,
7118 })
7119 with self.assertRaises(TypeError):
7120 C[str]
7121
7122
7123 class Point3D(Point2DGeneric[T], Generic[T, KT]):
7124 c: KT
7125
7126 self.assertEqual(Point3D.__bases__, (Generic, dict))
7127 self.assertEqual(Point3D.__orig_bases__, (Point2DGeneric[T], Generic[T, KT]))
7128 self.assertEqual(Point3D.__mro__, (Point3D, Generic, dict, object))
7129 self.assertEqual(Point3D.__parameters__, (T, KT))
7130 self.assertEqual(Point3D.__total__, True)
7131 self.assertEqual(Point3D.__optional_keys__, frozenset())
7132 self.assertEqual(Point3D.__required_keys__, frozenset(['a', 'b', 'c']))
7133 self.assertEqual(Point3D.__annotations__, {
7134 'a': T,
7135 'b': T,
7136 'c': KT,
7137 })
7138 self.assertEqual(Point3D[int, str].__origin__, Point3D)
7139
7140 with self.assertRaises(TypeError):
7141 Point3D[int]
7142
7143 with self.assertRaises(TypeError):
7144 class Point3D(Point2DGeneric[T], Generic[KT]):
7145 c: KT
7146
7147 def test_implicit_any_inheritance(self):
7148 class A(TypedDict, Generic[T]):
7149 a: T
7150
7151 class B(A[KT], total=False):
7152 b: KT
7153
7154 class WithImplicitAny(B):
7155 c: int
7156
7157 self.assertEqual(WithImplicitAny.__bases__, (Generic, dict,))
7158 self.assertEqual(WithImplicitAny.__mro__, (WithImplicitAny, Generic, dict, object))
7159 # Consistent with GenericTests.test_implicit_any
7160 self.assertEqual(WithImplicitAny.__parameters__, ())
7161 self.assertEqual(WithImplicitAny.__total__, True)
7162 self.assertEqual(WithImplicitAny.__optional_keys__, frozenset(['b']))
7163 self.assertEqual(WithImplicitAny.__required_keys__, frozenset(['a', 'c']))
7164 self.assertEqual(WithImplicitAny.__annotations__, {
7165 'a': T,
7166 'b': KT,
7167 'c': int,
7168 })
7169 with self.assertRaises(TypeError):
7170 WithImplicitAny[str]
7171
7172 def test_non_generic_subscript(self):
7173 # For backward compatibility, subscription works
7174 # on arbitrary TypedDict types.
7175 class TD(TypedDict):
7176 a: T
7177 A = TD[int]
7178 self.assertEqual(A.__origin__, TD)
7179 self.assertEqual(A.__parameters__, ())
7180 self.assertEqual(A.__args__, (int,))
7181 a = A(a = 1)
7182 self.assertIs(type(a), dict)
7183 self.assertEqual(a, {'a': 1})
7184
7185
7186 class RequiredTests(BaseTestCase):
7187
7188 def test_basics(self):
7189 with self.assertRaises(TypeError):
7190 Required[NotRequired]
7191 with self.assertRaises(TypeError):
7192 Required[int, str]
7193 with self.assertRaises(TypeError):
7194 Required[int][str]
7195
7196 def test_repr(self):
7197 self.assertEqual(repr(Required), 'typing.Required')
7198 cv = Required[int]
7199 self.assertEqual(repr(cv), 'typing.Required[int]')
7200 cv = Required[Employee]
7201 self.assertEqual(repr(cv), f'typing.Required[{__name__}.Employee]')
7202
7203 def test_cannot_subclass(self):
7204 with self.assertRaises(TypeError):
7205 class C(type(Required)):
7206 pass
7207 with self.assertRaises(TypeError):
7208 class D(type(Required[int])):
7209 pass
7210 with self.assertRaises(TypeError):
7211 class E(Required):
7212 pass
7213 with self.assertRaises(TypeError):
7214 class F(Required[int]):
7215 pass
7216
7217 def test_cannot_init(self):
7218 with self.assertRaises(TypeError):
7219 Required()
7220 with self.assertRaises(TypeError):
7221 type(Required)()
7222 with self.assertRaises(TypeError):
7223 type(Required[Optional[int]])()
7224
7225 def test_no_isinstance(self):
7226 with self.assertRaises(TypeError):
7227 isinstance(1, Required[int])
7228 with self.assertRaises(TypeError):
7229 issubclass(int, Required)
7230
7231
7232 class NotRequiredTests(BaseTestCase):
7233
7234 def test_basics(self):
7235 with self.assertRaises(TypeError):
7236 NotRequired[Required]
7237 with self.assertRaises(TypeError):
7238 NotRequired[int, str]
7239 with self.assertRaises(TypeError):
7240 NotRequired[int][str]
7241
7242 def test_repr(self):
7243 self.assertEqual(repr(NotRequired), 'typing.NotRequired')
7244 cv = NotRequired[int]
7245 self.assertEqual(repr(cv), 'typing.NotRequired[int]')
7246 cv = NotRequired[Employee]
7247 self.assertEqual(repr(cv), f'typing.NotRequired[{__name__}.Employee]')
7248
7249 def test_cannot_subclass(self):
7250 with self.assertRaises(TypeError):
7251 class C(type(NotRequired)):
7252 pass
7253 with self.assertRaises(TypeError):
7254 class D(type(NotRequired[int])):
7255 pass
7256 with self.assertRaises(TypeError):
7257 class E(NotRequired):
7258 pass
7259 with self.assertRaises(TypeError):
7260 class F(NotRequired[int]):
7261 pass
7262
7263 def test_cannot_init(self):
7264 with self.assertRaises(TypeError):
7265 NotRequired()
7266 with self.assertRaises(TypeError):
7267 type(NotRequired)()
7268 with self.assertRaises(TypeError):
7269 type(NotRequired[Optional[int]])()
7270
7271 def test_no_isinstance(self):
7272 with self.assertRaises(TypeError):
7273 isinstance(1, NotRequired[int])
7274 with self.assertRaises(TypeError):
7275 issubclass(int, NotRequired)
7276
7277
7278 class IOTests(BaseTestCase):
7279
7280 def test_io(self):
7281
7282 def stuff(a: IO) -> AnyStr:
7283 return a.readline()
7284
7285 a = stuff.__annotations__['a']
7286 self.assertEqual(a.__parameters__, (AnyStr,))
7287
7288 def test_textio(self):
7289
7290 def stuff(a: TextIO) -> str:
7291 return a.readline()
7292
7293 a = stuff.__annotations__['a']
7294 self.assertEqual(a.__parameters__, ())
7295
7296 def test_binaryio(self):
7297
7298 def stuff(a: BinaryIO) -> bytes:
7299 return a.readline()
7300
7301 a = stuff.__annotations__['a']
7302 self.assertEqual(a.__parameters__, ())
7303
7304 def test_io_submodule(self):
7305 with warnings.catch_warnings(record=True) as w:
7306 warnings.filterwarnings("default", category=DeprecationWarning)
7307 from typing.io import IO, TextIO, BinaryIO, __all__, __name__
7308 self.assertIs(IO, typing.IO)
7309 self.assertIs(TextIO, typing.TextIO)
7310 self.assertIs(BinaryIO, typing.BinaryIO)
7311 self.assertEqual(set(__all__), set(['IO', 'TextIO', 'BinaryIO']))
7312 self.assertEqual(__name__, 'typing.io')
7313 self.assertEqual(len(w), 1)
7314
7315
7316 class RETests(BaseTestCase):
7317 # Much of this is really testing _TypeAlias.
7318
7319 def test_basics(self):
7320 pat = re.compile('[a-z]+', re.I)
7321 self.assertIsSubclass(pat.__class__, Pattern)
7322 self.assertIsSubclass(type(pat), Pattern)
7323 self.assertIsInstance(pat, Pattern)
7324
7325 mat = pat.search('12345abcde.....')
7326 self.assertIsSubclass(mat.__class__, Match)
7327 self.assertIsSubclass(type(mat), Match)
7328 self.assertIsInstance(mat, Match)
7329
7330 # these should just work
7331 Pattern[Union[str, bytes]]
7332 Match[Union[bytes, str]]
7333
7334 def test_alias_equality(self):
7335 self.assertEqual(Pattern[str], Pattern[str])
7336 self.assertNotEqual(Pattern[str], Pattern[bytes])
7337 self.assertNotEqual(Pattern[str], Match[str])
7338 self.assertNotEqual(Pattern[str], str)
7339
7340 def test_errors(self):
7341 m = Match[Union[str, bytes]]
7342 with self.assertRaises(TypeError):
7343 m[str]
7344 with self.assertRaises(TypeError):
7345 # We don't support isinstance().
7346 isinstance(42, Pattern[str])
7347 with self.assertRaises(TypeError):
7348 # We don't support issubclass().
7349 issubclass(Pattern[bytes], Pattern[str])
7350
7351 def test_repr(self):
7352 self.assertEqual(repr(Pattern), 'typing.Pattern')
7353 self.assertEqual(repr(Pattern[str]), 'typing.Pattern[str]')
7354 self.assertEqual(repr(Pattern[bytes]), 'typing.Pattern[bytes]')
7355 self.assertEqual(repr(Match), 'typing.Match')
7356 self.assertEqual(repr(Match[str]), 'typing.Match[str]')
7357 self.assertEqual(repr(Match[bytes]), 'typing.Match[bytes]')
7358
7359 def test_re_submodule(self):
7360 with warnings.catch_warnings(record=True) as w:
7361 warnings.filterwarnings("default", category=DeprecationWarning)
7362 from typing.re import Match, Pattern, __all__, __name__
7363 self.assertIs(Match, typing.Match)
7364 self.assertIs(Pattern, typing.Pattern)
7365 self.assertEqual(set(__all__), set(['Match', 'Pattern']))
7366 self.assertEqual(__name__, 'typing.re')
7367 self.assertEqual(len(w), 1)
7368
7369 def test_re_submodule_access_basics(self):
7370 with warnings.catch_warnings():
7371 warnings.filterwarnings("error", category=DeprecationWarning)
7372 from typing import re
7373 self.assertIsInstance(re.__doc__, str)
7374 self.assertEqual(re.__name__, "typing.re")
7375 self.assertIsInstance(re.__dict__, types.MappingProxyType)
7376
7377 with self.assertWarns(DeprecationWarning):
7378 re.Match
7379
7380 def test_cannot_subclass(self):
7381 with self.assertRaises(TypeError) as ex:
7382
7383 class A(typing.Match):
7384 pass
7385
7386 self.assertEqual(str(ex.exception),
7387 "type 're.Match' is not an acceptable base type")
7388
7389
7390 class AnnotatedTests(BaseTestCase):
7391
7392 def test_new(self):
7393 with self.assertRaisesRegex(
7394 TypeError,
7395 'Type Annotated cannot be instantiated',
7396 ):
7397 Annotated()
7398
7399 def test_repr(self):
7400 self.assertEqual(
7401 repr(Annotated[int, 4, 5]),
7402 "typing.Annotated[int, 4, 5]"
7403 )
7404 self.assertEqual(
7405 repr(Annotated[List[int], 4, 5]),
7406 "typing.Annotated[typing.List[int], 4, 5]"
7407 )
7408
7409 def test_dir(self):
7410 dir_items = set(dir(Annotated[int, 4]))
7411 for required_item in [
7412 '__args__', '__parameters__', '__origin__',
7413 '__metadata__',
7414 ]:
7415 with self.subTest(required_item=required_item):
7416 self.assertIn(required_item, dir_items)
7417
7418 def test_flatten(self):
7419 A = Annotated[Annotated[int, 4], 5]
7420 self.assertEqual(A, Annotated[int, 4, 5])
7421 self.assertEqual(A.__metadata__, (4, 5))
7422 self.assertEqual(A.__origin__, int)
7423
7424 def test_deduplicate_from_union(self):
7425 # Regular:
7426 self.assertEqual(get_args(Annotated[int, 1] | int),
7427 (Annotated[int, 1], int))
7428 self.assertEqual(get_args(Union[Annotated[int, 1], int]),
7429 (Annotated[int, 1], int))
7430 self.assertEqual(get_args(Annotated[int, 1] | Annotated[int, 2] | int),
7431 (Annotated[int, 1], Annotated[int, 2], int))
7432 self.assertEqual(get_args(Union[Annotated[int, 1], Annotated[int, 2], int]),
7433 (Annotated[int, 1], Annotated[int, 2], int))
7434 self.assertEqual(get_args(Annotated[int, 1] | Annotated[str, 1] | int),
7435 (Annotated[int, 1], Annotated[str, 1], int))
7436 self.assertEqual(get_args(Union[Annotated[int, 1], Annotated[str, 1], int]),
7437 (Annotated[int, 1], Annotated[str, 1], int))
7438
7439 # Duplicates:
7440 self.assertEqual(Annotated[int, 1] | Annotated[int, 1] | int,
7441 Annotated[int, 1] | int)
7442 self.assertEqual(Union[Annotated[int, 1], Annotated[int, 1], int],
7443 Union[Annotated[int, 1], int])
7444
7445 # Unhashable metadata:
7446 self.assertEqual(get_args(str | Annotated[int, {}] | Annotated[int, set()] | int),
7447 (str, Annotated[int, {}], Annotated[int, set()], int))
7448 self.assertEqual(get_args(Union[str, Annotated[int, {}], Annotated[int, set()], int]),
7449 (str, Annotated[int, {}], Annotated[int, set()], int))
7450 self.assertEqual(get_args(str | Annotated[int, {}] | Annotated[str, {}] | int),
7451 (str, Annotated[int, {}], Annotated[str, {}], int))
7452 self.assertEqual(get_args(Union[str, Annotated[int, {}], Annotated[str, {}], int]),
7453 (str, Annotated[int, {}], Annotated[str, {}], int))
7454
7455 self.assertEqual(get_args(Annotated[int, 1] | str | Annotated[str, {}] | int),
7456 (Annotated[int, 1], str, Annotated[str, {}], int))
7457 self.assertEqual(get_args(Union[Annotated[int, 1], str, Annotated[str, {}], int]),
7458 (Annotated[int, 1], str, Annotated[str, {}], int))
7459
7460 import dataclasses
7461 @dataclasses.dataclass
7462 class ValueRange:
7463 lo: int
7464 hi: int
7465 v = ValueRange(1, 2)
7466 self.assertEqual(get_args(Annotated[int, v] | None),
7467 (Annotated[int, v], types.NoneType))
7468 self.assertEqual(get_args(Union[Annotated[int, v], None]),
7469 (Annotated[int, v], types.NoneType))
7470 self.assertEqual(get_args(Optional[Annotated[int, v]]),
7471 (Annotated[int, v], types.NoneType))
7472
7473 # Unhashable metadata duplicated:
7474 self.assertEqual(Annotated[int, {}] | Annotated[int, {}] | int,
7475 Annotated[int, {}] | int)
7476 self.assertEqual(Annotated[int, {}] | Annotated[int, {}] | int,
7477 int | Annotated[int, {}])
7478 self.assertEqual(Union[Annotated[int, {}], Annotated[int, {}], int],
7479 Union[Annotated[int, {}], int])
7480 self.assertEqual(Union[Annotated[int, {}], Annotated[int, {}], int],
7481 Union[int, Annotated[int, {}]])
7482
7483 def test_order_in_union(self):
7484 expr1 = Annotated[int, 1] | str | Annotated[str, {}] | int
7485 for args in itertools.permutations(get_args(expr1)):
7486 with self.subTest(args=args):
7487 self.assertEqual(expr1, reduce(operator.or_, args))
7488
7489 expr2 = Union[Annotated[int, 1], str, Annotated[str, {}], int]
7490 for args in itertools.permutations(get_args(expr2)):
7491 with self.subTest(args=args):
7492 self.assertEqual(expr2, Union[args])
7493
7494 def test_specialize(self):
7495 L = Annotated[List[T], "my decoration"]
7496 LI = Annotated[List[int], "my decoration"]
7497 self.assertEqual(L[int], Annotated[List[int], "my decoration"])
7498 self.assertEqual(L[int].__metadata__, ("my decoration",))
7499 self.assertEqual(L[int].__origin__, List[int])
7500 with self.assertRaises(TypeError):
7501 LI[int]
7502 with self.assertRaises(TypeError):
7503 L[int, float]
7504
7505 def test_hash_eq(self):
7506 self.assertEqual(len({Annotated[int, 4, 5], Annotated[int, 4, 5]}), 1)
7507 self.assertNotEqual(Annotated[int, 4, 5], Annotated[int, 5, 4])
7508 self.assertNotEqual(Annotated[int, 4, 5], Annotated[str, 4, 5])
7509 self.assertNotEqual(Annotated[int, 4], Annotated[int, 4, 4])
7510 self.assertEqual(
7511 {Annotated[int, 4, 5], Annotated[int, 4, 5], Annotated[T, 4, 5]},
7512 {Annotated[int, 4, 5], Annotated[T, 4, 5]}
7513 )
7514 # Unhashable `metadata` raises `TypeError`:
7515 a1 = Annotated[int, []]
7516 with self.assertRaises(TypeError):
7517 hash(a1)
7518
7519 class A:
7520 __hash__ = None
7521 a2 = Annotated[int, A()]
7522 with self.assertRaises(TypeError):
7523 hash(a2)
7524
7525 def test_instantiate(self):
7526 class C:
7527 classvar = 4
7528
7529 def __init__(self, x):
7530 self.x = x
7531
7532 def __eq__(self, other):
7533 if not isinstance(other, C):
7534 return NotImplemented
7535 return other.x == self.x
7536
7537 A = Annotated[C, "a decoration"]
7538 a = A(5)
7539 c = C(5)
7540 self.assertEqual(a, c)
7541 self.assertEqual(a.x, c.x)
7542 self.assertEqual(a.classvar, c.classvar)
7543
7544 def test_instantiate_generic(self):
7545 MyCount = Annotated[typing.Counter[T], "my decoration"]
7546 self.assertEqual(MyCount([4, 4, 5]), {4: 2, 5: 1})
7547 self.assertEqual(MyCount[int]([4, 4, 5]), {4: 2, 5: 1})
7548
7549 def test_instantiate_immutable(self):
7550 class C:
7551 def __setattr__(self, key, value):
7552 raise Exception("should be ignored")
7553
7554 A = Annotated[C, "a decoration"]
7555 # gh-115165: This used to cause RuntimeError to be raised
7556 # when we tried to set `__orig_class__` on the `C` instance
7557 # returned by the `A()` call
7558 self.assertIsInstance(A(), C)
7559
7560 def test_cannot_instantiate_forward(self):
7561 A = Annotated["int", (5, 6)]
7562 with self.assertRaises(TypeError):
7563 A(5)
7564
7565 def test_cannot_instantiate_type_var(self):
7566 A = Annotated[T, (5, 6)]
7567 with self.assertRaises(TypeError):
7568 A(5)
7569
7570 def test_cannot_getattr_typevar(self):
7571 with self.assertRaises(AttributeError):
7572 Annotated[T, (5, 7)].x
7573
7574 def test_attr_passthrough(self):
7575 class C:
7576 classvar = 4
7577
7578 A = Annotated[C, "a decoration"]
7579 self.assertEqual(A.classvar, 4)
7580 A.x = 5
7581 self.assertEqual(C.x, 5)
7582
7583 def test_special_form_containment(self):
7584 class C:
7585 classvar: Annotated[ClassVar[int], "a decoration"] = 4
7586 const: Annotated[Final[int], "Const"] = 4
7587
7588 self.assertEqual(get_type_hints(C, globals())['classvar'], ClassVar[int])
7589 self.assertEqual(get_type_hints(C, globals())['const'], Final[int])
7590
7591 def test_cannot_subclass(self):
7592 with self.assertRaisesRegex(TypeError, "Cannot subclass .*Annotated"):
7593 class C(Annotated):
7594 pass
7595
7596 def test_cannot_check_instance(self):
7597 with self.assertRaises(TypeError):
7598 isinstance(5, Annotated[int, "positive"])
7599
7600 def test_cannot_check_subclass(self):
7601 with self.assertRaises(TypeError):
7602 issubclass(int, Annotated[int, "positive"])
7603
7604 def test_too_few_type_args(self):
7605 with self.assertRaisesRegex(TypeError, 'at least two arguments'):
7606 Annotated[int]
7607
7608 def test_pickle(self):
7609 samples = [typing.Any, typing.Union[int, str],
7610 typing.Optional[str], Tuple[int, ...],
7611 typing.Callable[[str], bytes]]
7612
7613 for t in samples:
7614 x = Annotated[t, "a"]
7615
7616 for prot in range(pickle.HIGHEST_PROTOCOL + 1):
7617 with self.subTest(protocol=prot, type=t):
7618 pickled = pickle.dumps(x, prot)
7619 restored = pickle.loads(pickled)
7620 self.assertEqual(x, restored)
7621
7622 global _Annotated_test_G
7623
7624 class _Annotated_test_G(Generic[T]):
7625 x = 1
7626
7627 G = Annotated[_Annotated_test_G[int], "A decoration"]
7628 G.foo = 42
7629 G.bar = 'abc'
7630
7631 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
7632 z = pickle.dumps(G, proto)
7633 x = pickle.loads(z)
7634 self.assertEqual(x.foo, 42)
7635 self.assertEqual(x.bar, 'abc')
7636 self.assertEqual(x.x, 1)
7637
7638 def test_subst(self):
7639 dec = "a decoration"
7640 dec2 = "another decoration"
7641
7642 S = Annotated[T, dec2]
7643 self.assertEqual(S[int], Annotated[int, dec2])
7644
7645 self.assertEqual(S[Annotated[int, dec]], Annotated[int, dec, dec2])
7646 L = Annotated[List[T], dec]
7647
7648 self.assertEqual(L[int], Annotated[List[int], dec])
7649 with self.assertRaises(TypeError):
7650 L[int, int]
7651
7652 self.assertEqual(S[L[int]], Annotated[List[int], dec, dec2])
7653
7654 D = Annotated[typing.Dict[KT, VT], dec]
7655 self.assertEqual(D[str, int], Annotated[typing.Dict[str, int], dec])
7656 with self.assertRaises(TypeError):
7657 D[int]
7658
7659 It = Annotated[int, dec]
7660 with self.assertRaises(TypeError):
7661 It[None]
7662
7663 LI = L[int]
7664 with self.assertRaises(TypeError):
7665 LI[None]
7666
7667 def test_typevar_subst(self):
7668 dec = "a decoration"
7669 Ts = TypeVarTuple('Ts')
7670 T = TypeVar('T')
7671 T1 = TypeVar('T1')
7672 T2 = TypeVar('T2')
7673
7674 A = Annotated[tuple[*Ts], dec]
7675 self.assertEqual(A[int], Annotated[tuple[int], dec])
7676 self.assertEqual(A[str, int], Annotated[tuple[str, int], dec])
7677 with self.assertRaises(TypeError):
7678 Annotated[*Ts, dec]
7679
7680 B = Annotated[Tuple[Unpack[Ts]], dec]
7681 self.assertEqual(B[int], Annotated[Tuple[int], dec])
7682 self.assertEqual(B[str, int], Annotated[Tuple[str, int], dec])
7683 with self.assertRaises(TypeError):
7684 Annotated[Unpack[Ts], dec]
7685
7686 C = Annotated[tuple[T, *Ts], dec]
7687 self.assertEqual(C[int], Annotated[tuple[int], dec])
7688 self.assertEqual(C[int, str], Annotated[tuple[int, str], dec])
7689 self.assertEqual(
7690 C[int, str, float],
7691 Annotated[tuple[int, str, float], dec]
7692 )
7693 with self.assertRaises(TypeError):
7694 C[()]
7695
7696 D = Annotated[Tuple[T, Unpack[Ts]], dec]
7697 self.assertEqual(D[int], Annotated[Tuple[int], dec])
7698 self.assertEqual(D[int, str], Annotated[Tuple[int, str], dec])
7699 self.assertEqual(
7700 D[int, str, float],
7701 Annotated[Tuple[int, str, float], dec]
7702 )
7703 with self.assertRaises(TypeError):
7704 D[()]
7705
7706 E = Annotated[tuple[*Ts, T], dec]
7707 self.assertEqual(E[int], Annotated[tuple[int], dec])
7708 self.assertEqual(E[int, str], Annotated[tuple[int, str], dec])
7709 self.assertEqual(
7710 E[int, str, float],
7711 Annotated[tuple[int, str, float], dec]
7712 )
7713 with self.assertRaises(TypeError):
7714 E[()]
7715
7716 F = Annotated[Tuple[Unpack[Ts], T], dec]
7717 self.assertEqual(F[int], Annotated[Tuple[int], dec])
7718 self.assertEqual(F[int, str], Annotated[Tuple[int, str], dec])
7719 self.assertEqual(
7720 F[int, str, float],
7721 Annotated[Tuple[int, str, float], dec]
7722 )
7723 with self.assertRaises(TypeError):
7724 F[()]
7725
7726 G = Annotated[tuple[T1, *Ts, T2], dec]
7727 self.assertEqual(G[int, str], Annotated[tuple[int, str], dec])
7728 self.assertEqual(
7729 G[int, str, float],
7730 Annotated[tuple[int, str, float], dec]
7731 )
7732 self.assertEqual(
7733 G[int, str, bool, float],
7734 Annotated[tuple[int, str, bool, float], dec]
7735 )
7736 with self.assertRaises(TypeError):
7737 G[int]
7738
7739 H = Annotated[Tuple[T1, Unpack[Ts], T2], dec]
7740 self.assertEqual(H[int, str], Annotated[Tuple[int, str], dec])
7741 self.assertEqual(
7742 H[int, str, float],
7743 Annotated[Tuple[int, str, float], dec]
7744 )
7745 self.assertEqual(
7746 H[int, str, bool, float],
7747 Annotated[Tuple[int, str, bool, float], dec]
7748 )
7749 with self.assertRaises(TypeError):
7750 H[int]
7751
7752 # Now let's try creating an alias from an alias.
7753
7754 Ts2 = TypeVarTuple('Ts2')
7755 T3 = TypeVar('T3')
7756 T4 = TypeVar('T4')
7757
7758 # G is Annotated[tuple[T1, *Ts, T2], dec].
7759 I = G[T3, *Ts2, T4]
7760 J = G[T3, Unpack[Ts2], T4]
7761
7762 for x, y in [
7763 (I, Annotated[tuple[T3, *Ts2, T4], dec]),
7764 (J, Annotated[tuple[T3, Unpack[Ts2], T4], dec]),
7765 (I[int, str], Annotated[tuple[int, str], dec]),
7766 (J[int, str], Annotated[tuple[int, str], dec]),
7767 (I[int, str, float], Annotated[tuple[int, str, float], dec]),
7768 (J[int, str, float], Annotated[tuple[int, str, float], dec]),
7769 (I[int, str, bool, float],
7770 Annotated[tuple[int, str, bool, float], dec]),
7771 (J[int, str, bool, float],
7772 Annotated[tuple[int, str, bool, float], dec]),
7773 ]:
7774 self.assertEqual(x, y)
7775
7776 with self.assertRaises(TypeError):
7777 I[int]
7778 with self.assertRaises(TypeError):
7779 J[int]
7780
7781 def test_annotated_in_other_types(self):
7782 X = List[Annotated[T, 5]]
7783 self.assertEqual(X[int], List[Annotated[int, 5]])
7784
7785 def test_annotated_mro(self):
7786 class X(Annotated[int, (1, 10)]): ...
7787 self.assertEqual(X.__mro__, (X, int, object),
7788 "Annotated should be transparent.")
7789
7790 def test_annotated_cached_with_types(self):
7791 class A(str): ...
7792 class B(str): ...
7793
7794 field_a1 = Annotated[str, A("X")]
7795 field_a2 = Annotated[str, B("X")]
7796 a1_metadata = field_a1.__metadata__[0]
7797 a2_metadata = field_a2.__metadata__[0]
7798
7799 self.assertIs(type(a1_metadata), A)
7800 self.assertEqual(a1_metadata, A("X"))
7801 self.assertIs(type(a2_metadata), B)
7802 self.assertEqual(a2_metadata, B("X"))
7803 self.assertIsNot(type(a1_metadata), type(a2_metadata))
7804
7805 field_b1 = Annotated[str, A("Y")]
7806 field_b2 = Annotated[str, B("Y")]
7807 b1_metadata = field_b1.__metadata__[0]
7808 b2_metadata = field_b2.__metadata__[0]
7809
7810 self.assertIs(type(b1_metadata), A)
7811 self.assertEqual(b1_metadata, A("Y"))
7812 self.assertIs(type(b2_metadata), B)
7813 self.assertEqual(b2_metadata, B("Y"))
7814 self.assertIsNot(type(b1_metadata), type(b2_metadata))
7815
7816 field_c1 = Annotated[int, 1]
7817 field_c2 = Annotated[int, 1.0]
7818 field_c3 = Annotated[int, True]
7819
7820 self.assertIs(type(field_c1.__metadata__[0]), int)
7821 self.assertIs(type(field_c2.__metadata__[0]), float)
7822 self.assertIs(type(field_c3.__metadata__[0]), bool)
7823
7824
7825 class TypeAliasTests(BaseTestCase):
7826 def test_canonical_usage_with_variable_annotation(self):
7827 Alias: TypeAlias = Employee
7828
7829 def test_canonical_usage_with_type_comment(self):
7830 Alias = Employee # type: TypeAlias
7831
7832 def test_cannot_instantiate(self):
7833 with self.assertRaises(TypeError):
7834 TypeAlias()
7835
7836 def test_no_isinstance(self):
7837 with self.assertRaises(TypeError):
7838 isinstance(42, TypeAlias)
7839
7840 def test_stringized_usage(self):
7841 class A:
7842 a: "TypeAlias"
7843 self.assertEqual(get_type_hints(A), {'a': TypeAlias})
7844
7845 def test_no_issubclass(self):
7846 with self.assertRaises(TypeError):
7847 issubclass(Employee, TypeAlias)
7848
7849 with self.assertRaises(TypeError):
7850 issubclass(TypeAlias, Employee)
7851
7852 def test_cannot_subclass(self):
7853 with self.assertRaises(TypeError):
7854 class C(TypeAlias):
7855 pass
7856
7857 with self.assertRaises(TypeError):
7858 class D(type(TypeAlias)):
7859 pass
7860
7861 def test_repr(self):
7862 self.assertEqual(repr(TypeAlias), 'typing.TypeAlias')
7863
7864 def test_cannot_subscript(self):
7865 with self.assertRaises(TypeError):
7866 TypeAlias[int]
7867
7868
7869 class ParamSpecTests(BaseTestCase):
7870
7871 def test_basic_plain(self):
7872 P = ParamSpec('P')
7873 self.assertEqual(P, P)
7874 self.assertIsInstance(P, ParamSpec)
7875 self.assertEqual(P.__name__, 'P')
7876
7877 def test_valid_uses(self):
7878 P = ParamSpec('P')
7879 T = TypeVar('T')
7880 C1 = Callable[P, int]
7881 self.assertEqual(C1.__args__, (P, int))
7882 self.assertEqual(C1.__parameters__, (P,))
7883 C2 = Callable[P, T]
7884 self.assertEqual(C2.__args__, (P, T))
7885 self.assertEqual(C2.__parameters__, (P, T))
7886 # Test collections.abc.Callable too.
7887 C3 = collections.abc.Callable[P, int]
7888 self.assertEqual(C3.__args__, (P, int))
7889 self.assertEqual(C3.__parameters__, (P,))
7890 C4 = collections.abc.Callable[P, T]
7891 self.assertEqual(C4.__args__, (P, T))
7892 self.assertEqual(C4.__parameters__, (P, T))
7893
7894 def test_args_kwargs(self):
7895 P = ParamSpec('P')
7896 P_2 = ParamSpec('P_2')
7897 self.assertIn('args', dir(P))
7898 self.assertIn('kwargs', dir(P))
7899 self.assertIsInstance(P.args, ParamSpecArgs)
7900 self.assertIsInstance(P.kwargs, ParamSpecKwargs)
7901 self.assertIs(P.args.__origin__, P)
7902 self.assertIs(P.kwargs.__origin__, P)
7903 self.assertEqual(P.args, P.args)
7904 self.assertEqual(P.kwargs, P.kwargs)
7905 self.assertNotEqual(P.args, P_2.args)
7906 self.assertNotEqual(P.kwargs, P_2.kwargs)
7907 self.assertNotEqual(P.args, P.kwargs)
7908 self.assertNotEqual(P.kwargs, P.args)
7909 self.assertNotEqual(P.args, P_2.kwargs)
7910 self.assertEqual(repr(P.args), "P.args")
7911 self.assertEqual(repr(P.kwargs), "P.kwargs")
7912
7913 def test_stringized(self):
7914 P = ParamSpec('P')
7915 class C(Generic[P]):
7916 func: Callable["P", int]
7917 def foo(self, *args: "P.args", **kwargs: "P.kwargs"):
7918 pass
7919
7920 self.assertEqual(gth(C, globals(), locals()), {"func": Callable[P, int]})
7921 self.assertEqual(
7922 gth(C.foo, globals(), locals()), {"args": P.args, "kwargs": P.kwargs}
7923 )
7924
7925 def test_user_generics(self):
7926 T = TypeVar("T")
7927 P = ParamSpec("P")
7928 P_2 = ParamSpec("P_2")
7929
7930 class X(Generic[T, P]):
7931 f: Callable[P, int]
7932 x: T
7933 G1 = X[int, P_2]
7934 self.assertEqual(G1.__args__, (int, P_2))
7935 self.assertEqual(G1.__parameters__, (P_2,))
7936 with self.assertRaisesRegex(TypeError, "few arguments for"):
7937 X[int]
7938 with self.assertRaisesRegex(TypeError, "many arguments for"):
7939 X[int, P_2, str]
7940
7941 G2 = X[int, Concatenate[int, P_2]]
7942 self.assertEqual(G2.__args__, (int, Concatenate[int, P_2]))
7943 self.assertEqual(G2.__parameters__, (P_2,))
7944
7945 G3 = X[int, [int, bool]]
7946 self.assertEqual(G3.__args__, (int, (int, bool)))
7947 self.assertEqual(G3.__parameters__, ())
7948
7949 G4 = X[int, ...]
7950 self.assertEqual(G4.__args__, (int, Ellipsis))
7951 self.assertEqual(G4.__parameters__, ())
7952
7953 class Z(Generic[P]):
7954 f: Callable[P, int]
7955
7956 G5 = Z[[int, str, bool]]
7957 self.assertEqual(G5.__args__, ((int, str, bool),))
7958 self.assertEqual(G5.__parameters__, ())
7959
7960 G6 = Z[int, str, bool]
7961 self.assertEqual(G6.__args__, ((int, str, bool),))
7962 self.assertEqual(G6.__parameters__, ())
7963
7964 # G5 and G6 should be equivalent according to the PEP
7965 self.assertEqual(G5.__args__, G6.__args__)
7966 self.assertEqual(G5.__origin__, G6.__origin__)
7967 self.assertEqual(G5.__parameters__, G6.__parameters__)
7968 self.assertEqual(G5, G6)
7969
7970 G7 = Z[int]
7971 self.assertEqual(G7.__args__, ((int,),))
7972 self.assertEqual(G7.__parameters__, ())
7973
7974 with self.assertRaisesRegex(TypeError, "many arguments for"):
7975 Z[[int, str], bool]
7976 with self.assertRaisesRegex(TypeError, "many arguments for"):
7977 Z[P_2, bool]
7978
7979 def test_multiple_paramspecs_in_user_generics(self):
7980 P = ParamSpec("P")
7981 P2 = ParamSpec("P2")
7982
7983 class X(Generic[P, P2]):
7984 f: Callable[P, int]
7985 g: Callable[P2, str]
7986
7987 G1 = X[[int, str], [bytes]]
7988 G2 = X[[int], [str, bytes]]
7989 self.assertNotEqual(G1, G2)
7990 self.assertEqual(G1.__args__, ((int, str), (bytes,)))
7991 self.assertEqual(G2.__args__, ((int,), (str, bytes)))
7992
7993 def test_typevartuple_and_paramspecs_in_user_generics(self):
7994 Ts = TypeVarTuple("Ts")
7995 P = ParamSpec("P")
7996
7997 class X(Generic[*Ts, P]):
7998 f: Callable[P, int]
7999 g: Tuple[*Ts]
8000
8001 G1 = X[int, [bytes]]
8002 self.assertEqual(G1.__args__, (int, (bytes,)))
8003 G2 = X[int, str, [bytes]]
8004 self.assertEqual(G2.__args__, (int, str, (bytes,)))
8005 G3 = X[[bytes]]
8006 self.assertEqual(G3.__args__, ((bytes,),))
8007 G4 = X[[]]
8008 self.assertEqual(G4.__args__, ((),))
8009 with self.assertRaises(TypeError):
8010 X[()]
8011
8012 class Y(Generic[P, *Ts]):
8013 f: Callable[P, int]
8014 g: Tuple[*Ts]
8015
8016 G1 = Y[[bytes], int]
8017 self.assertEqual(G1.__args__, ((bytes,), int))
8018 G2 = Y[[bytes], int, str]
8019 self.assertEqual(G2.__args__, ((bytes,), int, str))
8020 G3 = Y[[bytes]]
8021 self.assertEqual(G3.__args__, ((bytes,),))
8022 G4 = Y[[]]
8023 self.assertEqual(G4.__args__, ((),))
8024 with self.assertRaises(TypeError):
8025 Y[()]
8026
8027 def test_typevartuple_and_paramspecs_in_generic_aliases(self):
8028 P = ParamSpec('P')
8029 T = TypeVar('T')
8030 Ts = TypeVarTuple('Ts')
8031
8032 for C in Callable, collections.abc.Callable:
8033 with self.subTest(generic=C):
8034 A = C[P, Tuple[*Ts]]
8035 B = A[[int, str], bytes, float]
8036 self.assertEqual(B.__args__, (int, str, Tuple[bytes, float]))
8037
8038 class X(Generic[T, P]):
8039 pass
8040
8041 A = X[Tuple[*Ts], P]
8042 B = A[bytes, float, [int, str]]
8043 self.assertEqual(B.__args__, (Tuple[bytes, float], (int, str,)))
8044
8045 class Y(Generic[P, T]):
8046 pass
8047
8048 A = Y[P, Tuple[*Ts]]
8049 B = A[[int, str], bytes, float]
8050 self.assertEqual(B.__args__, ((int, str,), Tuple[bytes, float]))
8051
8052 def test_var_substitution(self):
8053 P = ParamSpec("P")
8054 subst = P.__typing_subst__
8055 self.assertEqual(subst((int, str)), (int, str))
8056 self.assertEqual(subst([int, str]), (int, str))
8057 self.assertEqual(subst([None]), (type(None),))
8058 self.assertIs(subst(...), ...)
8059 self.assertIs(subst(P), P)
8060 self.assertEqual(subst(Concatenate[int, P]), Concatenate[int, P])
8061
8062 def test_bad_var_substitution(self):
8063 T = TypeVar('T')
8064 P = ParamSpec('P')
8065 bad_args = (42, int, None, T, int|str, Union[int, str])
8066 for arg in bad_args:
8067 with self.subTest(arg=arg):
8068 with self.assertRaises(TypeError):
8069 P.__typing_subst__(arg)
8070 with self.assertRaises(TypeError):
8071 typing.Callable[P, T][arg, str]
8072 with self.assertRaises(TypeError):
8073 collections.abc.Callable[P, T][arg, str]
8074
8075 def test_type_var_subst_for_other_type_vars(self):
8076 T = TypeVar('T')
8077 T2 = TypeVar('T2')
8078 P = ParamSpec('P')
8079 P2 = ParamSpec('P2')
8080 Ts = TypeVarTuple('Ts')
8081
8082 class Base(Generic[P]):
8083 pass
8084
8085 A1 = Base[T]
8086 self.assertEqual(A1.__parameters__, (T,))
8087 self.assertEqual(A1.__args__, ((T,),))
8088 self.assertEqual(A1[int], Base[int])
8089
8090 A2 = Base[[T]]
8091 self.assertEqual(A2.__parameters__, (T,))
8092 self.assertEqual(A2.__args__, ((T,),))
8093 self.assertEqual(A2[int], Base[int])
8094
8095 A3 = Base[[int, T]]
8096 self.assertEqual(A3.__parameters__, (T,))
8097 self.assertEqual(A3.__args__, ((int, T),))
8098 self.assertEqual(A3[str], Base[[int, str]])
8099
8100 A4 = Base[[T, int, T2]]
8101 self.assertEqual(A4.__parameters__, (T, T2))
8102 self.assertEqual(A4.__args__, ((T, int, T2),))
8103 self.assertEqual(A4[str, bool], Base[[str, int, bool]])
8104
8105 A5 = Base[[*Ts, int]]
8106 self.assertEqual(A5.__parameters__, (Ts,))
8107 self.assertEqual(A5.__args__, ((*Ts, int),))
8108 self.assertEqual(A5[str, bool], Base[[str, bool, int]])
8109
8110 A5_2 = Base[[int, *Ts]]
8111 self.assertEqual(A5_2.__parameters__, (Ts,))
8112 self.assertEqual(A5_2.__args__, ((int, *Ts),))
8113 self.assertEqual(A5_2[str, bool], Base[[int, str, bool]])
8114
8115 A6 = Base[[T, *Ts]]
8116 self.assertEqual(A6.__parameters__, (T, Ts))
8117 self.assertEqual(A6.__args__, ((T, *Ts),))
8118 self.assertEqual(A6[int, str, bool], Base[[int, str, bool]])
8119
8120 A7 = Base[[T, T]]
8121 self.assertEqual(A7.__parameters__, (T,))
8122 self.assertEqual(A7.__args__, ((T, T),))
8123 self.assertEqual(A7[int], Base[[int, int]])
8124
8125 A8 = Base[[T, list[T]]]
8126 self.assertEqual(A8.__parameters__, (T,))
8127 self.assertEqual(A8.__args__, ((T, list[T]),))
8128 self.assertEqual(A8[int], Base[[int, list[int]]])
8129
8130 A9 = Base[[Tuple[*Ts], *Ts]]
8131 self.assertEqual(A9.__parameters__, (Ts,))
8132 self.assertEqual(A9.__args__, ((Tuple[*Ts], *Ts),))
8133 self.assertEqual(A9[int, str], Base[Tuple[int, str], int, str])
8134
8135 A10 = Base[P2]
8136 self.assertEqual(A10.__parameters__, (P2,))
8137 self.assertEqual(A10.__args__, (P2,))
8138 self.assertEqual(A10[[int, str]], Base[[int, str]])
8139
8140 class DoubleP(Generic[P, P2]):
8141 pass
8142
8143 B1 = DoubleP[P, P2]
8144 self.assertEqual(B1.__parameters__, (P, P2))
8145 self.assertEqual(B1.__args__, (P, P2))
8146 self.assertEqual(B1[[int, str], [bool]], DoubleP[[int, str], [bool]])
8147 self.assertEqual(B1[[], []], DoubleP[[], []])
8148
8149 B2 = DoubleP[[int, str], P2]
8150 self.assertEqual(B2.__parameters__, (P2,))
8151 self.assertEqual(B2.__args__, ((int, str), P2))
8152 self.assertEqual(B2[[bool, bool]], DoubleP[[int, str], [bool, bool]])
8153 self.assertEqual(B2[[]], DoubleP[[int, str], []])
8154
8155 B3 = DoubleP[P, [bool, bool]]
8156 self.assertEqual(B3.__parameters__, (P,))
8157 self.assertEqual(B3.__args__, (P, (bool, bool)))
8158 self.assertEqual(B3[[int, str]], DoubleP[[int, str], [bool, bool]])
8159 self.assertEqual(B3[[]], DoubleP[[], [bool, bool]])
8160
8161 B4 = DoubleP[[T, int], [bool, T2]]
8162 self.assertEqual(B4.__parameters__, (T, T2))
8163 self.assertEqual(B4.__args__, ((T, int), (bool, T2)))
8164 self.assertEqual(B4[str, float], DoubleP[[str, int], [bool, float]])
8165
8166 B5 = DoubleP[[*Ts, int], [bool, T2]]
8167 self.assertEqual(B5.__parameters__, (Ts, T2))
8168 self.assertEqual(B5.__args__, ((*Ts, int), (bool, T2)))
8169 self.assertEqual(B5[str, bytes, float],
8170 DoubleP[[str, bytes, int], [bool, float]])
8171
8172 B6 = DoubleP[[T, int], [bool, *Ts]]
8173 self.assertEqual(B6.__parameters__, (T, Ts))
8174 self.assertEqual(B6.__args__, ((T, int), (bool, *Ts)))
8175 self.assertEqual(B6[str, bytes, float],
8176 DoubleP[[str, int], [bool, bytes, float]])
8177
8178 class PandT(Generic[P, T]):
8179 pass
8180
8181 C1 = PandT[P, T]
8182 self.assertEqual(C1.__parameters__, (P, T))
8183 self.assertEqual(C1.__args__, (P, T))
8184 self.assertEqual(C1[[int, str], bool], PandT[[int, str], bool])
8185
8186 C2 = PandT[[int, T], T]
8187 self.assertEqual(C2.__parameters__, (T,))
8188 self.assertEqual(C2.__args__, ((int, T), T))
8189 self.assertEqual(C2[str], PandT[[int, str], str])
8190
8191 C3 = PandT[[int, *Ts], T]
8192 self.assertEqual(C3.__parameters__, (Ts, T))
8193 self.assertEqual(C3.__args__, ((int, *Ts), T))
8194 self.assertEqual(C3[str, bool, bytes], PandT[[int, str, bool], bytes])
8195
8196 def test_paramspec_in_nested_generics(self):
8197 # Although ParamSpec should not be found in __parameters__ of most
8198 # generics, they probably should be found when nested in
8199 # a valid location.
8200 T = TypeVar("T")
8201 P = ParamSpec("P")
8202 C1 = Callable[P, T]
8203 G1 = List[C1]
8204 G2 = list[C1]
8205 G3 = list[C1] | int
8206 self.assertEqual(G1.__parameters__, (P, T))
8207 self.assertEqual(G2.__parameters__, (P, T))
8208 self.assertEqual(G3.__parameters__, (P, T))
8209 C = Callable[[int, str], float]
8210 self.assertEqual(G1[[int, str], float], List[C])
8211 self.assertEqual(G2[[int, str], float], list[C])
8212 self.assertEqual(G3[[int, str], float], list[C] | int)
8213
8214 def test_paramspec_gets_copied(self):
8215 # bpo-46581
8216 P = ParamSpec('P')
8217 P2 = ParamSpec('P2')
8218 C1 = Callable[P, int]
8219 self.assertEqual(C1.__parameters__, (P,))
8220 self.assertEqual(C1[P2].__parameters__, (P2,))
8221 self.assertEqual(C1[str].__parameters__, ())
8222 self.assertEqual(C1[str, T].__parameters__, (T,))
8223 self.assertEqual(C1[Concatenate[str, P2]].__parameters__, (P2,))
8224 self.assertEqual(C1[Concatenate[T, P2]].__parameters__, (T, P2))
8225 self.assertEqual(C1[...].__parameters__, ())
8226
8227 C2 = Callable[Concatenate[str, P], int]
8228 self.assertEqual(C2.__parameters__, (P,))
8229 self.assertEqual(C2[P2].__parameters__, (P2,))
8230 self.assertEqual(C2[str].__parameters__, ())
8231 self.assertEqual(C2[str, T].__parameters__, (T,))
8232 self.assertEqual(C2[Concatenate[str, P2]].__parameters__, (P2,))
8233 self.assertEqual(C2[Concatenate[T, P2]].__parameters__, (T, P2))
8234
8235
8236 class ConcatenateTests(BaseTestCase):
8237 def test_basics(self):
8238 P = ParamSpec('P')
8239 class MyClass: ...
8240 c = Concatenate[MyClass, P]
8241 self.assertNotEqual(c, Concatenate)
8242
8243 def test_dir(self):
8244 P = ParamSpec('P')
8245 dir_items = set(dir(Concatenate[int, P]))
8246 for required_item in [
8247 '__args__', '__parameters__', '__origin__',
8248 ]:
8249 with self.subTest(required_item=required_item):
8250 self.assertIn(required_item, dir_items)
8251
8252 def test_valid_uses(self):
8253 P = ParamSpec('P')
8254 T = TypeVar('T')
8255 C1 = Callable[Concatenate[int, P], int]
8256 self.assertEqual(C1.__args__, (Concatenate[int, P], int))
8257 self.assertEqual(C1.__parameters__, (P,))
8258 C2 = Callable[Concatenate[int, T, P], T]
8259 self.assertEqual(C2.__args__, (Concatenate[int, T, P], T))
8260 self.assertEqual(C2.__parameters__, (T, P))
8261
8262 # Test collections.abc.Callable too.
8263 C3 = collections.abc.Callable[Concatenate[int, P], int]
8264 self.assertEqual(C3.__args__, (Concatenate[int, P], int))
8265 self.assertEqual(C3.__parameters__, (P,))
8266 C4 = collections.abc.Callable[Concatenate[int, T, P], T]
8267 self.assertEqual(C4.__args__, (Concatenate[int, T, P], T))
8268 self.assertEqual(C4.__parameters__, (T, P))
8269
8270 def test_var_substitution(self):
8271 T = TypeVar('T')
8272 P = ParamSpec('P')
8273 P2 = ParamSpec('P2')
8274 C = Concatenate[T, P]
8275 self.assertEqual(C[int, P2], Concatenate[int, P2])
8276 self.assertEqual(C[int, [str, float]], (int, str, float))
8277 self.assertEqual(C[int, []], (int,))
8278 self.assertEqual(C[int, Concatenate[str, P2]],
8279 Concatenate[int, str, P2])
8280 self.assertEqual(C[int, ...], Concatenate[int, ...])
8281
8282 C = Concatenate[int, P]
8283 self.assertEqual(C[P2], Concatenate[int, P2])
8284 self.assertEqual(C[[str, float]], (int, str, float))
8285 self.assertEqual(C[str, float], (int, str, float))
8286 self.assertEqual(C[[]], (int,))
8287 self.assertEqual(C[Concatenate[str, P2]], Concatenate[int, str, P2])
8288 self.assertEqual(C[...], Concatenate[int, ...])
8289
8290 class TypeGuardTests(BaseTestCase):
8291 def test_basics(self):
8292 TypeGuard[int] # OK
8293
8294 def foo(arg) -> TypeGuard[int]: ...
8295 self.assertEqual(gth(foo), {'return': TypeGuard[int]})
8296
8297 with self.assertRaises(TypeError):
8298 TypeGuard[int, str]
8299
8300 def test_repr(self):
8301 self.assertEqual(repr(TypeGuard), 'typing.TypeGuard')
8302 cv = TypeGuard[int]
8303 self.assertEqual(repr(cv), 'typing.TypeGuard[int]')
8304 cv = TypeGuard[Employee]
8305 self.assertEqual(repr(cv), 'typing.TypeGuard[%s.Employee]' % __name__)
8306 cv = TypeGuard[tuple[int]]
8307 self.assertEqual(repr(cv), 'typing.TypeGuard[tuple[int]]')
8308
8309 def test_cannot_subclass(self):
8310 with self.assertRaises(TypeError):
8311 class C(type(TypeGuard)):
8312 pass
8313 with self.assertRaises(TypeError):
8314 class D(type(TypeGuard[int])):
8315 pass
8316
8317 def test_cannot_init(self):
8318 with self.assertRaises(TypeError):
8319 TypeGuard()
8320 with self.assertRaises(TypeError):
8321 type(TypeGuard)()
8322 with self.assertRaises(TypeError):
8323 type(TypeGuard[Optional[int]])()
8324
8325 def test_no_isinstance(self):
8326 with self.assertRaises(TypeError):
8327 isinstance(1, TypeGuard[int])
8328 with self.assertRaises(TypeError):
8329 issubclass(int, TypeGuard)
8330
8331
8332 SpecialAttrsP = typing.ParamSpec('SpecialAttrsP')
8333 SpecialAttrsT = typing.TypeVar('SpecialAttrsT', int, float, complex)
8334
8335
8336 class SpecialAttrsTests(BaseTestCase):
8337
8338 def test_special_attrs(self):
8339 cls_to_check = {
8340 # ABC classes
8341 typing.AbstractSet: 'AbstractSet',
8342 typing.AsyncContextManager: 'AsyncContextManager',
8343 typing.AsyncGenerator: 'AsyncGenerator',
8344 typing.AsyncIterable: 'AsyncIterable',
8345 typing.AsyncIterator: 'AsyncIterator',
8346 typing.Awaitable: 'Awaitable',
8347 typing.ByteString: 'ByteString',
8348 typing.Callable: 'Callable',
8349 typing.ChainMap: 'ChainMap',
8350 typing.Collection: 'Collection',
8351 typing.Container: 'Container',
8352 typing.ContextManager: 'ContextManager',
8353 typing.Coroutine: 'Coroutine',
8354 typing.Counter: 'Counter',
8355 typing.DefaultDict: 'DefaultDict',
8356 typing.Deque: 'Deque',
8357 typing.Dict: 'Dict',
8358 typing.FrozenSet: 'FrozenSet',
8359 typing.Generator: 'Generator',
8360 typing.Hashable: 'Hashable',
8361 typing.ItemsView: 'ItemsView',
8362 typing.Iterable: 'Iterable',
8363 typing.Iterator: 'Iterator',
8364 typing.KeysView: 'KeysView',
8365 typing.List: 'List',
8366 typing.Mapping: 'Mapping',
8367 typing.MappingView: 'MappingView',
8368 typing.MutableMapping: 'MutableMapping',
8369 typing.MutableSequence: 'MutableSequence',
8370 typing.MutableSet: 'MutableSet',
8371 typing.OrderedDict: 'OrderedDict',
8372 typing.Reversible: 'Reversible',
8373 typing.Sequence: 'Sequence',
8374 typing.Set: 'Set',
8375 typing.Sized: 'Sized',
8376 typing.Tuple: 'Tuple',
8377 typing.Type: 'Type',
8378 typing.ValuesView: 'ValuesView',
8379 # Subscribed ABC classes
8380 typing.AbstractSet[Any]: 'AbstractSet',
8381 typing.AsyncContextManager[Any]: 'AsyncContextManager',
8382 typing.AsyncGenerator[Any, Any]: 'AsyncGenerator',
8383 typing.AsyncIterable[Any]: 'AsyncIterable',
8384 typing.AsyncIterator[Any]: 'AsyncIterator',
8385 typing.Awaitable[Any]: 'Awaitable',
8386 typing.Callable[[], Any]: 'Callable',
8387 typing.Callable[..., Any]: 'Callable',
8388 typing.ChainMap[Any, Any]: 'ChainMap',
8389 typing.Collection[Any]: 'Collection',
8390 typing.Container[Any]: 'Container',
8391 typing.ContextManager[Any]: 'ContextManager',
8392 typing.Coroutine[Any, Any, Any]: 'Coroutine',
8393 typing.Counter[Any]: 'Counter',
8394 typing.DefaultDict[Any, Any]: 'DefaultDict',
8395 typing.Deque[Any]: 'Deque',
8396 typing.Dict[Any, Any]: 'Dict',
8397 typing.FrozenSet[Any]: 'FrozenSet',
8398 typing.Generator[Any, Any, Any]: 'Generator',
8399 typing.ItemsView[Any, Any]: 'ItemsView',
8400 typing.Iterable[Any]: 'Iterable',
8401 typing.Iterator[Any]: 'Iterator',
8402 typing.KeysView[Any]: 'KeysView',
8403 typing.List[Any]: 'List',
8404 typing.Mapping[Any, Any]: 'Mapping',
8405 typing.MappingView[Any]: 'MappingView',
8406 typing.MutableMapping[Any, Any]: 'MutableMapping',
8407 typing.MutableSequence[Any]: 'MutableSequence',
8408 typing.MutableSet[Any]: 'MutableSet',
8409 typing.OrderedDict[Any, Any]: 'OrderedDict',
8410 typing.Reversible[Any]: 'Reversible',
8411 typing.Sequence[Any]: 'Sequence',
8412 typing.Set[Any]: 'Set',
8413 typing.Tuple[Any]: 'Tuple',
8414 typing.Tuple[Any, ...]: 'Tuple',
8415 typing.Type[Any]: 'Type',
8416 typing.ValuesView[Any]: 'ValuesView',
8417 # Special Forms
8418 typing.Annotated: 'Annotated',
8419 typing.Any: 'Any',
8420 typing.ClassVar: 'ClassVar',
8421 typing.Concatenate: 'Concatenate',
8422 typing.Final: 'Final',
8423 typing.ForwardRef: 'ForwardRef',
8424 typing.Literal: 'Literal',
8425 typing.NewType: 'NewType',
8426 typing.NoReturn: 'NoReturn',
8427 typing.Never: 'Never',
8428 typing.Optional: 'Optional',
8429 typing.TypeAlias: 'TypeAlias',
8430 typing.TypeGuard: 'TypeGuard',
8431 typing.TypeVar: 'TypeVar',
8432 typing.Union: 'Union',
8433 typing.Self: 'Self',
8434 # Subscribed special forms
8435 typing.Annotated[Any, "Annotation"]: 'Annotated',
8436 typing.ClassVar[Any]: 'ClassVar',
8437 typing.Concatenate[Any, SpecialAttrsP]: 'Concatenate',
8438 typing.Final[Any]: 'Final',
8439 typing.Literal[Any]: 'Literal',
8440 typing.Literal[1, 2]: 'Literal',
8441 typing.Literal[True, 2]: 'Literal',
8442 typing.Optional[Any]: 'Optional',
8443 typing.TypeGuard[Any]: 'TypeGuard',
8444 typing.Union[Any]: 'Any',
8445 typing.Union[int, float]: 'Union',
8446 # Incompatible special forms (tested in test_special_attrs2)
8447 # - typing.ForwardRef('set[Any]')
8448 # - typing.NewType('TypeName', Any)
8449 # - typing.ParamSpec('SpecialAttrsP')
8450 # - typing.TypeVar('T')
8451 }
8452
8453 for cls, name in cls_to_check.items():
8454 with self.subTest(cls=cls):
8455 self.assertEqual(cls.__name__, name, str(cls))
8456 self.assertEqual(cls.__qualname__, name, str(cls))
8457 self.assertEqual(cls.__module__, 'typing', str(cls))
8458 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
8459 s = pickle.dumps(cls, proto)
8460 loaded = pickle.loads(s)
8461 self.assertIs(cls, loaded)
8462
8463 TypeName = typing.NewType('SpecialAttrsTests.TypeName', Any)
8464
8465 def test_special_attrs2(self):
8466 # Forward refs provide a different introspection API. __name__ and
8467 # __qualname__ make little sense for forward refs as they can store
8468 # complex typing expressions.
8469 fr = typing.ForwardRef('set[Any]')
8470 self.assertFalse(hasattr(fr, '__name__'))
8471 self.assertFalse(hasattr(fr, '__qualname__'))
8472 self.assertEqual(fr.__module__, 'typing')
8473 # Forward refs are currently unpicklable.
8474 # PyPy change: we can pickle ForwardRefs just fine on higher protocols
8475 for proto in range(2):
8476 with self.assertRaises(TypeError):
8477 pickle.dumps(fr, proto)
8478
8479 self.assertEqual(SpecialAttrsTests.TypeName.__name__, 'TypeName')
8480 self.assertEqual(
8481 SpecialAttrsTests.TypeName.__qualname__,
8482 'SpecialAttrsTests.TypeName',
8483 )
8484 self.assertEqual(
8485 SpecialAttrsTests.TypeName.__module__,
8486 __name__,
8487 )
8488 # NewTypes are picklable assuming correct qualname information.
8489 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
8490 s = pickle.dumps(SpecialAttrsTests.TypeName, proto)
8491 loaded = pickle.loads(s)
8492 self.assertIs(SpecialAttrsTests.TypeName, loaded)
8493
8494 # Type variables don't support non-global instantiation per PEP 484
8495 # restriction that "The argument to TypeVar() must be a string equal
8496 # to the variable name to which it is assigned". Thus, providing
8497 # __qualname__ is unnecessary.
8498 self.assertEqual(SpecialAttrsT.__name__, 'SpecialAttrsT')
8499 self.assertFalse(hasattr(SpecialAttrsT, '__qualname__'))
8500 self.assertEqual(SpecialAttrsT.__module__, __name__)
8501 # Module-level type variables are picklable.
8502 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
8503 s = pickle.dumps(SpecialAttrsT, proto)
8504 loaded = pickle.loads(s)
8505 self.assertIs(SpecialAttrsT, loaded)
8506
8507 self.assertEqual(SpecialAttrsP.__name__, 'SpecialAttrsP')
8508 self.assertFalse(hasattr(SpecialAttrsP, '__qualname__'))
8509 self.assertEqual(SpecialAttrsP.__module__, __name__)
8510 # Module-level ParamSpecs are picklable.
8511 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
8512 s = pickle.dumps(SpecialAttrsP, proto)
8513 loaded = pickle.loads(s)
8514 self.assertIs(SpecialAttrsP, loaded)
8515
8516 def test_genericalias_dir(self):
8517 class Foo(Generic[T]):
8518 def bar(self):
8519 pass
8520 baz = 3
8521 __magic__ = 4
8522
8523 # The class attributes of the original class should be visible even
8524 # in dir() of the GenericAlias. See bpo-45755.
8525 dir_items = set(dir(Foo[int]))
8526 for required_item in [
8527 'bar', 'baz',
8528 '__args__', '__parameters__', '__origin__',
8529 ]:
8530 with self.subTest(required_item=required_item):
8531 self.assertIn(required_item, dir_items)
8532 self.assertNotIn('__magic__', dir_items)
8533
8534
8535 class RevealTypeTests(BaseTestCase):
8536 def test_reveal_type(self):
8537 obj = object()
8538 with captured_stderr() as stderr:
8539 self.assertIs(obj, reveal_type(obj))
8540 self.assertEqual(stderr.getvalue(), "Runtime type is 'object'\n")
8541
8542
8543 class DataclassTransformTests(BaseTestCase):
8544 def test_decorator(self):
8545 def create_model(*, frozen: bool = False, kw_only: bool = True):
8546 return lambda cls: cls
8547
8548 decorated = dataclass_transform(kw_only_default=True, order_default=False)(create_model)
8549
8550 class CustomerModel:
8551 id: int
8552
8553 self.assertIs(decorated, create_model)
8554 self.assertEqual(
8555 decorated.__dataclass_transform__,
8556 {
8557 "eq_default": True,
8558 "order_default": False,
8559 "kw_only_default": True,
8560 "field_specifiers": (),
8561 "kwargs": {},
8562 }
8563 )
8564 self.assertIs(
8565 decorated(frozen=True, kw_only=False)(CustomerModel),
8566 CustomerModel
8567 )
8568
8569 def test_base_class(self):
8570 class ModelBase:
8571 def __init_subclass__(cls, *, frozen: bool = False): ...
8572
8573 Decorated = dataclass_transform(
8574 eq_default=True,
8575 order_default=True,
8576 # Arbitrary unrecognized kwargs are accepted at runtime.
8577 make_everything_awesome=True,
8578 )(ModelBase)
8579
8580 class CustomerModel(Decorated, frozen=True):
8581 id: int
8582
8583 self.assertIs(Decorated, ModelBase)
8584 self.assertEqual(
8585 Decorated.__dataclass_transform__,
8586 {
8587 "eq_default": True,
8588 "order_default": True,
8589 "kw_only_default": False,
8590 "field_specifiers": (),
8591 "kwargs": {"make_everything_awesome": True},
8592 }
8593 )
8594 self.assertIsSubclass(CustomerModel, Decorated)
8595
8596 def test_metaclass(self):
8597 class Field: ...
8598
8599 class ModelMeta(type):
8600 def __new__(
8601 cls, name, bases, namespace, *, init: bool = True,
8602 ):
8603 return super().__new__(cls, name, bases, namespace)
8604
8605 Decorated = dataclass_transform(
8606 order_default=True, field_specifiers=(Field,)
8607 )(ModelMeta)
8608
8609 class ModelBase(metaclass=Decorated): ...
8610
8611 class CustomerModel(ModelBase, init=False):
8612 id: int
8613
8614 self.assertIs(Decorated, ModelMeta)
8615 self.assertEqual(
8616 Decorated.__dataclass_transform__,
8617 {
8618 "eq_default": True,
8619 "order_default": True,
8620 "kw_only_default": False,
8621 "field_specifiers": (Field,),
8622 "kwargs": {},
8623 }
8624 )
8625 self.assertIsInstance(CustomerModel, Decorated)
8626
8627
8628 class AllTests(BaseTestCase):
8629 """Tests for __all__."""
8630
8631 def test_all(self):
8632 from typing import __all__ as a
8633 # Just spot-check the first and last of every category.
8634 self.assertIn('AbstractSet', a)
8635 self.assertIn('ValuesView', a)
8636 self.assertIn('cast', a)
8637 self.assertIn('overload', a)
8638 # Context managers.
8639 self.assertIn('ContextManager', a)
8640 self.assertIn('AsyncContextManager', a)
8641 # Check that io and re are not exported.
8642 self.assertNotIn('io', a)
8643 self.assertNotIn('re', a)
8644 # Spot-check that stdlib modules aren't exported.
8645 self.assertNotIn('os', a)
8646 self.assertNotIn('sys', a)
8647 # Check that Text is defined.
8648 self.assertIn('Text', a)
8649 # Check previously missing classes.
8650 self.assertIn('SupportsBytes', a)
8651 self.assertIn('SupportsComplex', a)
8652
8653 def test_all_exported_names(self):
8654 actual_all = set(typing.__all__)
8655 computed_all = {
8656 k for k, v in vars(typing).items()
8657 # explicitly exported, not a thing with __module__
8658 if k in actual_all or (
8659 # avoid private names
8660 not k.startswith('_') and
8661 k not in {'io', 're'} and
8662 # there's a few types and metaclasses that aren't exported
8663 not k.endswith(('Meta', '_contra', '_co')) and
8664 not k.upper() == k and
8665 # but export all things that have __module__ == 'typing'
8666 getattr(v, '__module__', None) == typing.__name__
8667 )
8668 }
8669 self.assertSetEqual(computed_all, actual_all)
8670
8671
8672 class TypeIterationTests(BaseTestCase):
8673 _UNITERABLE_TYPES = (
8674 Any,
8675 Union,
8676 Union[str, int],
8677 Union[str, T],
8678 List,
8679 Tuple,
8680 Callable,
8681 Callable[..., T],
8682 Callable[[T], str],
8683 Annotated,
8684 Annotated[T, ''],
8685 )
8686
8687 def test_cannot_iterate(self):
8688 expected_error_regex = "object is not iterable"
8689 for test_type in self._UNITERABLE_TYPES:
8690 with self.subTest(type=test_type):
8691 with self.assertRaisesRegex(TypeError, expected_error_regex):
8692 iter(test_type)
8693 with self.assertRaisesRegex(TypeError, expected_error_regex):
8694 list(test_type)
8695 with self.assertRaisesRegex(TypeError, expected_error_regex):
8696 for _ in test_type:
8697 pass
8698
8699 def test_is_not_instance_of_iterable(self):
8700 for type_to_test in self._UNITERABLE_TYPES:
8701 self.assertNotIsInstance(type_to_test, collections.abc.Iterable)
8702
8703
8704 def load_tests(loader, tests, pattern):
8705 import doctest
8706 tests.addTests(doctest.DocTestSuite(typing))
8707 return tests
8708
8709
8710 if __name__ == '__main__':
8711 main()