Debian Codegraph @

src/test_typing_extensions.py

raw ◀ ▶
1 Debian patch touch this file
1 import abc
2 import asyncio
3 import collections
4 import collections.abc
5 import contextlib
6 import copy
7 import functools
8 import gc
9 import importlib
10 import inspect
11 import io
12 import itertools
13 import os
14 import pickle
15 import re
16 import subprocess
17 import sys
18 import tempfile
19 import textwrap
20 import types
21 import typing
22 import warnings
23 from collections import defaultdict
24 from functools import lru_cache
25 from pathlib import Path
26 from unittest import TestCase, main, skipIf, skipUnless
27 from unittest.mock import patch
28
29 import typing_extensions
30 from _typed_dict_test_helper import Foo, FooGeneric, VeryAnnotated
31 from typing_extensions import (
32 _FORWARD_REF_HAS_CLASS,
33 Annotated,
34 Any,
35 AnyStr,
36 AsyncContextManager,
37 AsyncIterator,
38 Awaitable,
39 Buffer,
40 Callable,
41 ClassVar,
42 Concatenate,
43 Dict,
44 Doc,
45 Final,
46 Format,
47 Generic,
48 IntVar,
49 Iterable,
50 Iterator,
51 List,
52 Literal,
53 LiteralString,
54 NamedTuple,
55 Never,
56 NewType,
57 NoDefault,
58 NoExtraItems,
59 NoReturn,
60 NotRequired,
61 Optional,
62 ParamSpec,
63 ParamSpecArgs,
64 ParamSpecKwargs,
65 Protocol,
66 ReadOnly,
67 Required,
68 Self,
69 Sentinel,
70 Set,
71 Tuple,
72 Type,
73 TypeAlias,
74 TypeAliasType,
75 TypedDict,
76 TypeForm,
77 TypeGuard,
78 TypeIs,
79 TypeVar,
80 TypeVarTuple,
81 Union,
82 Unpack,
83 assert_never,
84 assert_type,
85 clear_overloads,
86 dataclass_transform,
87 deprecated,
88 disjoint_base,
89 evaluate_forward_ref,
90 final,
91 get_annotations,
92 get_args,
93 get_origin,
94 get_original_bases,
95 get_overloads,
96 get_protocol_members,
97 get_type_hints,
98 is_protocol,
99 is_typeddict,
100 no_type_check,
101 overload,
102 override,
103 reveal_type,
104 runtime,
105 runtime_checkable,
106 sentinel,
107 type_repr,
108 )
109
110 NoneType = type(None)
111 T = TypeVar("T")
112 KT = TypeVar("KT")
113 VT = TypeVar("VT")
114
115 # Flags used to mark tests that only apply after a specific
116 # version of the typing module.
117 TYPING_3_10_0 = sys.version_info[:3] >= (3, 10, 0)
118
119 # 3.11 makes runtime type checks (_type_check) more lenient.
120 TYPING_3_11_0 = sys.version_info[:3] >= (3, 11, 0)
121
122 # 3.12 changes the representation of Unpack[] (PEP 692)
123 # and adds PEP 695 to CPython's grammar
124 TYPING_3_12_0 = sys.version_info[:3] >= (3, 12, 0)
125
126 # @deprecated works differently in Python 3.12
127 TYPING_3_12_ONLY = (3, 12) <= sys.version_info < (3, 13)
128
129 # 3.13 drops support for the keyword argument syntax of TypedDict
130 TYPING_3_13_0 = sys.version_info[:3] >= (3, 13, 0)
131
132 # 3.13.0.rc1 fixes a problem with @deprecated
133 TYPING_3_13_0_RC = sys.version_info[:4] >= (3, 13, 0, "candidate")
134
135 TYPING_3_14_0 = sys.version_info[:3] >= (3, 14, 0)
136
137 TYPING_3_15_0 = sys.version_info[:3] >= (3, 15, 0)
138
139 TYPING_3_15_0_BETA_1 = sys.version_info[:5] == (3, 15, 0, 'beta', 1)
140
141 # We cannot control the repr of `TypeVarTuple` on versions of Python
142 # where `typing_extensions.TypeVarTuple()` does not return an instance
143 # of `typing_extensions.TypeVarTuple`. At time of writing, that's Python
144 # versions 3.11-3.14 inclusive (but not 3.10 or 3.15+). The exact version
145 # range has changed in the past and may do so again in the future.
146 #
147 # Note that we do not do an `isinstance()` check here because
148 # `typing_extensions.TypeVarTuple` does some trickery to pretend that
149 # instances of `typing.TypeVar` are also instances of
150 # `typing_extensions.TypeVarTuple` on Python 3.11-3.14.
151 # (Possibly we're being a little too clever for our own good there.)
152 GOOD_TYPEVARTUPLE_REPR_EXPECTED = (
153 type(typing_extensions.TypeVarTuple("Ts"))
154 is typing_extensions.TypeVarTuple
155 )
156
157 # https://github.com/python/cpython/pull/27017 was backported into some 3.9 and 3.10
158 # versions, but not all
159 HAS_FORWARD_MODULE = "module" in inspect.signature(typing._type_check).parameters
160
161 skip_if_py313_beta_1 = skipIf(
162 sys.version_info[:5] == (3, 13, 0, 'beta', 1),
163 "Bugfixes will be released in 3.13.0b2"
164 )
165
166 ANN_MODULE_SOURCE = '''\
167 import sys
168 from typing import List, Optional
169 from functools import wraps
170
171 try:
172 __annotations__[1] = 2
173 except NameError:
174 assert sys.version_info >= (3, 14)
175
176 class C:
177
178 x = 5; y: Optional['C'] = None
179
180 from typing import Tuple
181 x: int = 5; y: str = x; f: Tuple[int, int]
182
183 class M(type):
184 try:
185 __annotations__['123'] = 123
186 except NameError:
187 assert sys.version_info >= (3, 14)
188 o: type = object
189
190 (pars): bool = True
191
192 class D(C):
193 j: str = 'hi'; k: str= 'bye'
194
195 from types import new_class
196 h_class = new_class('H', (C,))
197 j_class = new_class('J')
198
199 class F():
200 z: int = 5
201 def __init__(self, x):
202 pass
203
204 class Y(F):
205 def __init__(self):
206 super(F, self).__init__(123)
207
208 class Meta(type):
209 def __new__(meta, name, bases, namespace):
210 return super().__new__(meta, name, bases, namespace)
211
212 class S(metaclass = Meta):
213 x: str = 'something'
214 y: str = 'something else'
215
216 def foo(x: int = 10):
217 def bar(y: List[str]):
218 x: str = 'yes'
219 bar()
220
221 def dec(func):
222 @wraps(func)
223 def wrapper(*args, **kwargs):
224 return func(*args, **kwargs)
225 return wrapper
226 '''
227
228 ANN_MODULE_2_SOURCE = '''\
229 from typing import no_type_check, ClassVar
230
231 i: int = 1
232 j: int
233 x: float = i/10
234
235 def f():
236 class C: ...
237 return C()
238
239 f().new_attr: object = object()
240
241 class C:
242 def __init__(self, x: int) -> None:
243 self.x = x
244
245 c = C(5)
246 c.new_attr: int = 10
247
248 __annotations__ = {}
249
250
251 @no_type_check
252 class NTC:
253 def meth(self, param: complex) -> None:
254 ...
255
256 class CV:
257 var: ClassVar['CV']
258
259 CV.var = CV()
260 '''
261
262 ANN_MODULE_3_SOURCE = '''\
263 def f_bad_ann():
264 __annotations__[1] = 2
265
266 class C_OK:
267 def __init__(self, x: int) -> None:
268 self.x: no_such_name = x # This one is OK as proposed by Guido
269
270 class D_bad_ann:
271 def __init__(self, x: int) -> None:
272 sfel.y: int = 0
273
274 def g_bad_ann():
275 no_such_name.attr: int = 0
276 '''
277
278
279 STOCK_ANNOTATIONS = """
280 a:int=3
281 b:str="foo"
282
283 class MyClass:
284 a:int=4
285 b:str="bar"
286 def __init__(self, a, b):
287 self.a = a
288 self.b = b
289 def __eq__(self, other):
290 return isinstance(other, MyClass) and self.a == other.a and self.b == other.b
291
292 def function(a:int, b:str) -> MyClass:
293 return MyClass(a, b)
294
295
296 def function2(a:int, b:"str", c:MyClass) -> MyClass:
297 pass
298
299
300 def function3(a:"int", b:"str", c:"MyClass"):
301 pass
302
303
304 class UnannotatedClass:
305 pass
306
307 def unannotated_function(a, b, c): pass
308 """
309
310 STRINGIZED_ANNOTATIONS = """
311 from __future__ import annotations
312
313 a:int=3
314 b:str="foo"
315
316 class MyClass:
317 a:int=4
318 b:str="bar"
319 def __init__(self, a, b):
320 self.a = a
321 self.b = b
322 def __eq__(self, other):
323 return isinstance(other, MyClass) and self.a == other.a and self.b == other.b
324
325 def function(a:int, b:str) -> MyClass:
326 return MyClass(a, b)
327
328
329 def function2(a:int, b:"str", c:MyClass) -> MyClass:
330 pass
331
332
333 def function3(a:"int", b:"str", c:"MyClass"):
334 pass
335
336
337 class UnannotatedClass:
338 pass
339
340 def unannotated_function(a, b, c): pass
341
342 class MyClassWithLocalAnnotations:
343 mytype = int
344 x: mytype
345 """
346
347 STRINGIZED_ANNOTATIONS_2 = """
348 from __future__ import annotations
349
350
351 def foo(a, b, c): pass
352 """
353
354 if TYPING_3_12_0:
355 STRINGIZED_ANNOTATIONS_PEP_695 = textwrap.dedent(
356 """
357 from __future__ import annotations
358 from typing import Callable, Unpack
359
360
361 class A[T, *Ts, **P]:
362 x: T
363 y: tuple[*Ts]
364 z: Callable[P, str]
365
366
367 class B[T, *Ts, **P]:
368 T = int
369 Ts = str
370 P = bytes
371 x: T
372 y: Ts
373 z: P
374
375
376 Eggs = int
377 Spam = str
378
379
380 class C[Eggs, **Spam]:
381 x: Eggs
382 y: Spam
383
384
385 def generic_function[T, *Ts, **P](
386 x: T, *y: Unpack[Ts], z: P.args, zz: P.kwargs
387 ) -> None: ...
388
389
390 def generic_function_2[Eggs, **Spam](x: Eggs, y: Spam): pass
391
392
393 class D:
394 Foo = int
395 Bar = str
396
397 def generic_method[Foo, **Bar](
398 self, x: Foo, y: Bar
399 ) -> None: ...
400
401 def generic_method_2[Eggs, **Spam](self, x: Eggs, y: Spam): pass
402
403
404 # Eggs is `int` in globals, a TypeVar in type_params, and `str` in locals:
405 class E[Eggs]:
406 Eggs = str
407 x: Eggs
408
409
410
411 def nested():
412 from types import SimpleNamespace
413 from typing_extensions import get_annotations
414
415 Eggs = bytes
416 Spam = memoryview
417
418
419 class F[Eggs, **Spam]:
420 x: Eggs
421 y: Spam
422
423 def generic_method[Eggs, **Spam](self, x: Eggs, y: Spam): pass
424
425
426 def generic_function[Eggs, **Spam](x: Eggs, y: Spam): pass
427
428
429 # Eggs is `int` in globals, `bytes` in the function scope,
430 # a TypeVar in the type_params, and `str` in locals:
431 class G[Eggs]:
432 Eggs = str
433 x: Eggs
434
435
436 return SimpleNamespace(
437 F=F,
438 F_annotations=get_annotations(F, eval_str=True),
439 F_meth_annotations=get_annotations(F.generic_method, eval_str=True),
440 G_annotations=get_annotations(G, eval_str=True),
441 generic_func=generic_function,
442 generic_func_annotations=get_annotations(generic_function, eval_str=True)
443 )
444 """
445 )
446 else:
447 STRINGIZED_ANNOTATIONS_PEP_695 = None
448
449
450 class BaseTestCase(TestCase):
451 def assertIsSubclass(self, cls, class_or_tuple, msg=None):
452 if not issubclass(cls, class_or_tuple):
453 message = f'{cls!r} is not a subclass of {class_or_tuple!r}'
454 if msg is not None:
455 message += f' : {msg}'
456 raise self.failureException(message)
457
458 def assertNotIsSubclass(self, cls, class_or_tuple, msg=None):
459 if issubclass(cls, class_or_tuple):
460 message = f'{cls!r} is a subclass of {class_or_tuple!r}'
461 if msg is not None:
462 message += f' : {msg}'
463 raise self.failureException(message)
464
465
466 class EqualToForwardRef:
467 """Helper to ease use of annotationlib.ForwardRef in tests.
468
469 This checks only attributes that can be set using the constructor.
470
471 """
472
473 def __init__(
474 self,
475 arg,
476 *,
477 module=None,
478 owner=None,
479 is_class=False,
480 ):
481 self.__forward_arg__ = arg
482 self.__forward_is_class__ = is_class
483 self.__forward_module__ = module
484 self.__owner__ = owner
485
486 def __eq__(self, other):
487 if not isinstance(other, (EqualToForwardRef, typing.ForwardRef)):
488 return NotImplemented
489 if sys.version_info >= (3, 14) and self.__owner__ != other.__owner__:
490 return False
491 return (
492 self.__forward_arg__ == other.__forward_arg__
493 and self.__forward_module__ == other.__forward_module__
494 and self.__forward_is_class__ == other.__forward_is_class__
495 )
496
497 def __repr__(self):
498 extra = []
499 if self.__forward_module__ is not None:
500 extra.append(f", module={self.__forward_module__!r}")
501 if self.__forward_is_class__:
502 extra.append(", is_class=True")
503 if sys.version_info >= (3, 14) and self.__owner__ is not None:
504 extra.append(f", owner={self.__owner__!r}")
505 return f"EqualToForwardRef({self.__forward_arg__!r}{''.join(extra)})"
506
507
508 class Employee:
509 pass
510
511
512 class BottomTypeTestsMixin:
513 bottom_type: ClassVar[Any]
514
515 def test_equality(self):
516 self.assertEqual(self.bottom_type, self.bottom_type)
517 self.assertIs(self.bottom_type, self.bottom_type)
518 self.assertNotEqual(self.bottom_type, None)
519
520 def test_get_origin(self):
521 self.assertIs(get_origin(self.bottom_type), None)
522
523 def test_instance_type_error(self):
524 with self.assertRaises(TypeError):
525 isinstance(42, self.bottom_type)
526
527 def test_subclass_type_error(self):
528 with self.assertRaises(TypeError):
529 issubclass(Employee, self.bottom_type)
530 with self.assertRaises(TypeError):
531 issubclass(NoReturn, self.bottom_type)
532
533 def test_not_generic(self):
534 with self.assertRaises(TypeError):
535 self.bottom_type[int]
536
537 def test_cannot_subclass(self):
538 with self.assertRaises(TypeError):
539 class A(self.bottom_type):
540 pass
541 with self.assertRaises(TypeError):
542 class B(type(self.bottom_type)):
543 pass
544
545 def test_cannot_instantiate(self):
546 with self.assertRaises(TypeError):
547 self.bottom_type()
548 with self.assertRaises(TypeError):
549 type(self.bottom_type)()
550
551 def test_pickle(self):
552 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
553 pickled = pickle.dumps(self.bottom_type, protocol=proto)
554 self.assertIs(self.bottom_type, pickle.loads(pickled))
555
556 @skipUnless(TYPING_3_10_0, "PEP 604 has yet to be")
557 def test_or(self):
558 self.assertEqual(self.bottom_type | int, Union[self.bottom_type, int])
559 self.assertEqual(int | self.bottom_type, Union[int, self.bottom_type])
560
561 self.assertEqual(get_args(self.bottom_type | int), (self.bottom_type, int))
562 self.assertEqual(get_args(int | self.bottom_type), (int, self.bottom_type))
563
564
565 class NoReturnTests(BottomTypeTestsMixin, BaseTestCase):
566 bottom_type = NoReturn
567
568 def test_repr(self):
569 if hasattr(typing, 'NoReturn'):
570 self.assertEqual(repr(NoReturn), 'typing.NoReturn')
571 else:
572 self.assertEqual(repr(NoReturn), 'typing_extensions.NoReturn')
573
574 def test_get_type_hints(self):
575 def some(arg: NoReturn) -> NoReturn: ...
576 def some_str(arg: 'NoReturn') -> 'typing.NoReturn': ...
577
578 expected = {'arg': NoReturn, 'return': NoReturn}
579 for target in some, some_str:
580 with self.subTest(target=target):
581 self.assertEqual(gth(target), expected)
582
583 def test_not_equality(self):
584 self.assertNotEqual(NoReturn, Never)
585 self.assertNotEqual(Never, NoReturn)
586
587
588 class NeverTests(BottomTypeTestsMixin, BaseTestCase):
589 bottom_type = Never
590
591 def test_repr(self):
592 if hasattr(typing, 'Never'):
593 self.assertEqual(repr(Never), 'typing.Never')
594 else:
595 self.assertEqual(repr(Never), 'typing_extensions.Never')
596
597 def test_get_type_hints(self):
598 def some(arg: Never) -> Never: ...
599 def some_str(arg: 'Never') -> 'typing_extensions.Never': ...
600
601 expected = {'arg': Never, 'return': Never}
602 for target in [some, some_str]:
603 with self.subTest(target=target):
604 self.assertEqual(gth(target), expected)
605
606
607 class AssertNeverTests(BaseTestCase):
608 def test_exception(self):
609 with self.assertRaises(AssertionError):
610 assert_never(None)
611
612 value = "some value"
613 with self.assertRaisesRegex(AssertionError, value):
614 assert_never(value)
615
616 # Make sure a huge value doesn't get printed in its entirety
617 huge_value = "a" * 10000
618 with self.assertRaises(AssertionError) as cm:
619 assert_never(huge_value)
620 self.assertLess(
621 len(cm.exception.args[0]),
622 typing_extensions._ASSERT_NEVER_REPR_MAX_LENGTH * 2,
623 )
624
625
626 class OverrideTests(BaseTestCase):
627 def test_override(self):
628 class Base:
629 def normal_method(self): ...
630 @staticmethod
631 def static_method_good_order(): ...
632 @staticmethod
633 def static_method_bad_order(): ...
634 @staticmethod
635 def decorator_with_slots(): ...
636
637 class Derived(Base):
638 @override
639 def normal_method(self):
640 return 42
641
642 @staticmethod
643 @override
644 def static_method_good_order():
645 return 42
646
647 @override
648 @staticmethod
649 def static_method_bad_order():
650 return 42
651
652 self.assertIsSubclass(Derived, Base)
653 instance = Derived()
654 self.assertEqual(instance.normal_method(), 42)
655 self.assertIs(True, instance.normal_method.__override__)
656 self.assertEqual(Derived.static_method_good_order(), 42)
657 self.assertIs(True, Derived.static_method_good_order.__override__)
658 self.assertEqual(Derived.static_method_bad_order(), 42)
659 self.assertIs(False, hasattr(Derived.static_method_bad_order, "__override__"))
660
661
662 class DeprecatedTests(BaseTestCase):
663 def test_dunder_deprecated(self):
664 @deprecated("A will go away soon")
665 class A:
666 pass
667
668 self.assertEqual(A.__deprecated__, "A will go away soon")
669 self.assertIsInstance(A, type)
670
671 @deprecated("b will go away soon")
672 def b():
673 pass
674
675 self.assertEqual(b.__deprecated__, "b will go away soon")
676 self.assertIsInstance(b, types.FunctionType)
677
678 @overload
679 @deprecated("no more ints")
680 def h(x: int) -> int: ...
681 @overload
682 def h(x: str) -> str: ...
683 def h(x):
684 return x # pragma: no cover
685
686 overloads = get_overloads(h)
687 self.assertEqual(len(overloads), 2)
688 self.assertEqual(overloads[0].__deprecated__, "no more ints")
689
690 def test_class(self):
691 @deprecated("A will go away soon")
692 class A:
693 pass
694
695 with self.assertWarnsRegex(DeprecationWarning, "A will go away soon"):
696 A()
697 with self.assertWarnsRegex(DeprecationWarning, "A will go away soon"):
698 with self.assertRaises(TypeError):
699 A(42)
700
701 def test_class_with_init(self):
702 @deprecated("HasInit will go away soon")
703 class HasInit:
704 def __init__(self, x):
705 self.x = x
706
707 with self.assertWarnsRegex(DeprecationWarning, "HasInit will go away soon"):
708 instance = HasInit(42)
709 self.assertEqual(instance.x, 42)
710
711 def test_class_with_new(self):
712 has_new_called = False
713
714 @deprecated("HasNew will go away soon")
715 class HasNew:
716 def __new__(cls, x):
717 nonlocal has_new_called
718 has_new_called = True
719 return super().__new__(cls)
720
721 def __init__(self, x) -> None:
722 self.x = x
723
724 with self.assertWarnsRegex(DeprecationWarning, "HasNew will go away soon"):
725 instance = HasNew(42)
726 self.assertEqual(instance.x, 42)
727 self.assertTrue(has_new_called)
728
729 def test_class_with_inherited_new(self):
730 new_base_called = False
731
732 class NewBase:
733 def __new__(cls, x):
734 nonlocal new_base_called
735 new_base_called = True
736 return super().__new__(cls)
737
738 def __init__(self, x) -> None:
739 self.x = x
740
741 @deprecated("HasInheritedNew will go away soon")
742 class HasInheritedNew(NewBase):
743 pass
744
745 with self.assertWarnsRegex(DeprecationWarning, "HasInheritedNew will go away soon"):
746 instance = HasInheritedNew(42)
747 self.assertEqual(instance.x, 42)
748 self.assertTrue(new_base_called)
749
750 def test_class_with_new_but_no_init(self):
751 new_called = False
752
753 @deprecated("HasNewNoInit will go away soon")
754 class HasNewNoInit:
755 def __new__(cls, x):
756 nonlocal new_called
757 new_called = True
758 obj = super().__new__(cls)
759 obj.x = x
760 return obj
761
762 with self.assertWarnsRegex(DeprecationWarning, "HasNewNoInit will go away soon"):
763 instance = HasNewNoInit(42)
764 self.assertEqual(instance.x, 42)
765 self.assertTrue(new_called)
766
767 def test_mixin_class(self):
768 @deprecated("Mixin will go away soon")
769 class Mixin:
770 pass
771
772 class Base:
773 def __init__(self, a) -> None:
774 self.a = a
775
776 with self.assertWarnsRegex(DeprecationWarning, "Mixin will go away soon"):
777 class Child(Base, Mixin):
778 pass
779
780 instance = Child(42)
781 self.assertEqual(instance.a, 42)
782
783 def test_do_not_shadow_user_arguments(self):
784 new_called = False
785 new_called_cls = None
786
787 @deprecated("MyMeta will go away soon")
788 class MyMeta(type):
789 def __new__(mcs, name, bases, attrs, cls=None):
790 nonlocal new_called, new_called_cls
791 new_called = True
792 new_called_cls = cls
793 return super().__new__(mcs, name, bases, attrs)
794
795 with self.assertWarnsRegex(DeprecationWarning, "MyMeta will go away soon"):
796 class Foo(metaclass=MyMeta, cls='haha'):
797 pass
798
799 self.assertTrue(new_called)
800 self.assertEqual(new_called_cls, 'haha')
801
802 def test_existing_init_subclass(self):
803 @deprecated("C will go away soon")
804 class C:
805 def __init_subclass__(cls) -> None:
806 cls.inited = True
807
808 with self.assertWarnsRegex(DeprecationWarning, "C will go away soon"):
809 C()
810
811 with self.assertWarnsRegex(DeprecationWarning, "C will go away soon"):
812 class D(C):
813 pass
814
815 self.assertTrue(D.inited)
816 self.assertIsInstance(D(), D) # no deprecation
817
818 def test_existing_init_subclass_in_base(self):
819 class Base:
820 def __init_subclass__(cls, x) -> None:
821 cls.inited = x
822
823 @deprecated("C will go away soon")
824 class C(Base, x=42):
825 pass
826
827 self.assertEqual(C.inited, 42)
828
829 with self.assertWarnsRegex(DeprecationWarning, "C will go away soon"):
830 C()
831
832 with self.assertWarnsRegex(DeprecationWarning, "C will go away soon"):
833 class D(C, x=3):
834 pass
835
836 self.assertEqual(D.inited, 3)
837
838 def test_existing_init_subclass_in_sibling_base(self):
839 @deprecated("A will go away soon")
840 class A:
841 pass
842 class B:
843 def __init_subclass__(cls, x):
844 super().__init_subclass__()
845 cls.inited = x
846
847 with self.assertWarnsRegex(DeprecationWarning, "A will go away soon"):
848 class C(A, B, x=42):
849 pass
850 self.assertEqual(C.inited, 42)
851
852 with self.assertWarnsRegex(DeprecationWarning, "A will go away soon"):
853 class D(B, A, x=42):
854 pass
855 self.assertEqual(D.inited, 42)
856
857 def test_init_subclass_has_correct_cls(self):
858 init_subclass_saw = None
859
860 @deprecated("Base will go away soon")
861 class Base:
862 def __init_subclass__(cls) -> None:
863 nonlocal init_subclass_saw
864 init_subclass_saw = cls
865
866 self.assertIsNone(init_subclass_saw)
867
868 with self.assertWarnsRegex(DeprecationWarning, "Base will go away soon"):
869 class C(Base):
870 pass
871
872 self.assertIs(init_subclass_saw, C)
873
874 def test_init_subclass_with_explicit_classmethod(self):
875 init_subclass_saw = None
876
877 @deprecated("Base will go away soon")
878 class Base:
879 @classmethod
880 def __init_subclass__(cls) -> None:
881 nonlocal init_subclass_saw
882 init_subclass_saw = cls
883
884 self.assertIsNone(init_subclass_saw)
885
886 with self.assertWarnsRegex(DeprecationWarning, "Base will go away soon"):
887 class C(Base):
888 pass
889
890 self.assertIs(init_subclass_saw, C)
891
892 def test_function(self):
893 @deprecated("b will go away soon")
894 def b():
895 pass
896
897 with self.assertWarnsRegex(DeprecationWarning, "b will go away soon"):
898 b()
899
900 def test_method(self):
901 class Capybara:
902 @deprecated("x will go away soon")
903 def x(self):
904 pass
905
906 instance = Capybara()
907 with self.assertWarnsRegex(DeprecationWarning, "x will go away soon"):
908 instance.x()
909
910 def test_property(self):
911 class Capybara:
912 @property
913 @deprecated("x will go away soon")
914 def x(self):
915 pass
916
917 @property
918 def no_more_setting(self):
919 return 42
920
921 @no_more_setting.setter
922 @deprecated("no more setting")
923 def no_more_setting(self, value):
924 pass
925
926 instance = Capybara()
927 with self.assertWarnsRegex(DeprecationWarning, "x will go away soon"):
928 instance.x
929
930 with warnings.catch_warnings():
931 warnings.simplefilter("error")
932 self.assertEqual(instance.no_more_setting, 42)
933
934 with self.assertWarnsRegex(DeprecationWarning, "no more setting"):
935 instance.no_more_setting = 42
936
937 def test_category(self):
938 @deprecated("c will go away soon", category=RuntimeWarning)
939 def c():
940 pass
941
942 with self.assertWarnsRegex(RuntimeWarning, "c will go away soon"):
943 c()
944
945 def test_turn_off_warnings(self):
946 @deprecated("d will go away soon", category=None)
947 def d():
948 pass
949
950 with warnings.catch_warnings():
951 warnings.simplefilter("error")
952 d()
953
954 def test_only_strings_allowed(self):
955 with self.assertRaisesRegex(
956 TypeError,
957 "Expected an object of type str for 'message', not 'type'"
958 ):
959 @deprecated
960 class Foo: ...
961
962 with self.assertRaisesRegex(
963 TypeError,
964 "Expected an object of type str for 'message', not 'function'"
965 ):
966 @deprecated
967 def foo(): ...
968
969 def test_no_retained_references_to_wrapper_instance(self):
970 @deprecated('depr')
971 def d(): pass
972
973 self.assertFalse(any(
974 isinstance(cell.cell_contents, deprecated) for cell in d.__closure__
975 ))
976
977 @deprecated("depr")
978 def func():
979 pass
980
981 @deprecated("depr")
982 async def coro():
983 pass
984
985 class Cls:
986 @deprecated("depr")
987 def func(self):
988 pass
989
990 @deprecated("depr")
991 async def coro(self):
992 pass
993
994 class DeprecatedCoroTests(BaseTestCase):
995 def test_asyncio_iscoroutinefunction(self):
996 with warnings.catch_warnings():
997 warnings.simplefilter("ignore", DeprecationWarning)
998 self.assertFalse(asyncio.coroutines.iscoroutinefunction(func))
999 self.assertFalse(asyncio.coroutines.iscoroutinefunction(Cls.func))
1000 self.assertTrue(asyncio.coroutines.iscoroutinefunction(coro))
1001 self.assertTrue(asyncio.coroutines.iscoroutinefunction(Cls.coro))
1002
1003 @skipUnless(TYPING_3_12_ONLY or TYPING_3_13_0_RC, "inspect.iscoroutinefunction works differently on Python < 3.12")
1004 def test_inspect_iscoroutinefunction(self):
1005 self.assertFalse(inspect.iscoroutinefunction(func))
1006 self.assertFalse(inspect.iscoroutinefunction(Cls.func))
1007 self.assertTrue(inspect.iscoroutinefunction(coro))
1008 self.assertTrue(inspect.iscoroutinefunction(Cls.coro))
1009
1010
1011 class AnyTests(BaseTestCase):
1012 def test_can_subclass(self):
1013 class Mock(Any): pass
1014 self.assertTrue(issubclass(Mock, Any))
1015 self.assertIsInstance(Mock(), Mock)
1016
1017 class Something: pass
1018 self.assertFalse(issubclass(Something, Any))
1019 self.assertNotIsInstance(Something(), Mock)
1020
1021 class MockSomething(Something, Mock): pass
1022 self.assertTrue(issubclass(MockSomething, Any))
1023 ms = MockSomething()
1024 self.assertIsInstance(ms, MockSomething)
1025 self.assertIsInstance(ms, Something)
1026 self.assertIsInstance(ms, Mock)
1027
1028 class SubclassesAny(Any):
1029 ...
1030
1031 def test_repr(self):
1032 if sys.version_info >= (3, 11):
1033 mod_name = 'typing'
1034 else:
1035 mod_name = 'typing_extensions'
1036 self.assertEqual(repr(Any), f"{mod_name}.Any")
1037
1038 @skipIf(sys.version_info[:3] == (3, 11, 0), "A bug was fixed in 3.11.1")
1039 def test_repr_on_Any_subclass(self):
1040 self.assertEqual(
1041 repr(self.SubclassesAny),
1042 f"<class '{self.SubclassesAny.__module__}.AnyTests.SubclassesAny'>"
1043 )
1044
1045 def test_instantiation(self):
1046 with self.assertRaises(TypeError):
1047 Any()
1048
1049 self.SubclassesAny()
1050
1051 def test_isinstance(self):
1052 with self.assertRaises(TypeError):
1053 isinstance(object(), Any)
1054
1055 isinstance(object(), self.SubclassesAny)
1056
1057
1058 class ClassVarTests(BaseTestCase):
1059
1060 def test_basics(self):
1061 if not TYPING_3_11_0:
1062 with self.assertRaises(TypeError):
1063 ClassVar[1]
1064 with self.assertRaises(TypeError):
1065 ClassVar[int, str]
1066 with self.assertRaises(TypeError):
1067 ClassVar[int][str]
1068
1069 def test_repr(self):
1070 if hasattr(typing, 'ClassVar'):
1071 mod_name = 'typing'
1072 else:
1073 mod_name = 'typing_extensions'
1074 self.assertEqual(repr(ClassVar), mod_name + '.ClassVar')
1075 cv = ClassVar[int]
1076 self.assertEqual(repr(cv), mod_name + '.ClassVar[int]')
1077 cv = ClassVar[Employee]
1078 self.assertEqual(repr(cv), mod_name + f'.ClassVar[{__name__}.Employee]')
1079
1080 def test_cannot_subclass(self):
1081 with self.assertRaises(TypeError):
1082 class C(type(ClassVar)):
1083 pass
1084 with self.assertRaises(TypeError):
1085 class D(type(ClassVar[int])):
1086 pass
1087
1088 def test_cannot_init(self):
1089 with self.assertRaises(TypeError):
1090 ClassVar()
1091 with self.assertRaises(TypeError):
1092 type(ClassVar)()
1093 with self.assertRaises(TypeError):
1094 type(ClassVar[Optional[int]])()
1095
1096 def test_no_isinstance(self):
1097 with self.assertRaises(TypeError):
1098 isinstance(1, ClassVar[int])
1099 with self.assertRaises(TypeError):
1100 issubclass(int, ClassVar)
1101
1102
1103 class FinalTests(BaseTestCase):
1104
1105 def test_basics(self):
1106 if not TYPING_3_11_0:
1107 with self.assertRaises(TypeError):
1108 Final[1]
1109 with self.assertRaises(TypeError):
1110 Final[int, str]
1111 with self.assertRaises(TypeError):
1112 Final[int][str]
1113
1114 def test_repr(self):
1115 self.assertEqual(repr(Final), 'typing.Final')
1116 cv = Final[int]
1117 self.assertEqual(repr(cv), 'typing.Final[int]')
1118 cv = Final[Employee]
1119 self.assertEqual(repr(cv), f'typing.Final[{__name__}.Employee]')
1120
1121 def test_cannot_subclass(self):
1122 with self.assertRaises(TypeError):
1123 class C(type(Final)):
1124 pass
1125 with self.assertRaises(TypeError):
1126 class D(type(Final[int])):
1127 pass
1128
1129 def test_cannot_init(self):
1130 with self.assertRaises(TypeError):
1131 Final()
1132 with self.assertRaises(TypeError):
1133 type(Final)()
1134 with self.assertRaises(TypeError):
1135 type(Final[Optional[int]])()
1136
1137 def test_no_isinstance(self):
1138 with self.assertRaises(TypeError):
1139 isinstance(1, Final[int])
1140 with self.assertRaises(TypeError):
1141 issubclass(int, Final)
1142
1143
1144 class RequiredTests(BaseTestCase):
1145
1146 def test_basics(self):
1147 if not TYPING_3_11_0:
1148 with self.assertRaises(TypeError):
1149 Required[1]
1150 with self.assertRaises(TypeError):
1151 Required[int, str]
1152 with self.assertRaises(TypeError):
1153 Required[int][str]
1154
1155 def test_repr(self):
1156 if hasattr(typing, 'Required'):
1157 mod_name = 'typing'
1158 else:
1159 mod_name = 'typing_extensions'
1160 self.assertEqual(repr(Required), f'{mod_name}.Required')
1161 cv = Required[int]
1162 self.assertEqual(repr(cv), f'{mod_name}.Required[int]')
1163 cv = Required[Employee]
1164 self.assertEqual(repr(cv), f'{mod_name}.Required[{__name__}.Employee]')
1165
1166 def test_cannot_subclass(self):
1167 with self.assertRaises(TypeError):
1168 class C(type(Required)):
1169 pass
1170 with self.assertRaises(TypeError):
1171 class D(type(Required[int])):
1172 pass
1173
1174 def test_cannot_init(self):
1175 with self.assertRaises(TypeError):
1176 Required()
1177 with self.assertRaises(TypeError):
1178 type(Required)()
1179 with self.assertRaises(TypeError):
1180 type(Required[Optional[int]])()
1181
1182 def test_no_isinstance(self):
1183 with self.assertRaises(TypeError):
1184 isinstance(1, Required[int])
1185 with self.assertRaises(TypeError):
1186 issubclass(int, Required)
1187
1188
1189 class NotRequiredTests(BaseTestCase):
1190
1191 def test_basics(self):
1192 if not TYPING_3_11_0:
1193 with self.assertRaises(TypeError):
1194 NotRequired[1]
1195 with self.assertRaises(TypeError):
1196 NotRequired[int, str]
1197 with self.assertRaises(TypeError):
1198 NotRequired[int][str]
1199
1200 def test_repr(self):
1201 if hasattr(typing, 'NotRequired'):
1202 mod_name = 'typing'
1203 else:
1204 mod_name = 'typing_extensions'
1205 self.assertEqual(repr(NotRequired), f'{mod_name}.NotRequired')
1206 cv = NotRequired[int]
1207 self.assertEqual(repr(cv), f'{mod_name}.NotRequired[int]')
1208 cv = NotRequired[Employee]
1209 self.assertEqual(repr(cv), f'{mod_name}.NotRequired[{ __name__}.Employee]')
1210
1211 def test_cannot_subclass(self):
1212 with self.assertRaises(TypeError):
1213 class C(type(NotRequired)):
1214 pass
1215 with self.assertRaises(TypeError):
1216 class D(type(NotRequired[int])):
1217 pass
1218
1219 def test_cannot_init(self):
1220 with self.assertRaises(TypeError):
1221 NotRequired()
1222 with self.assertRaises(TypeError):
1223 type(NotRequired)()
1224 with self.assertRaises(TypeError):
1225 type(NotRequired[Optional[int]])()
1226
1227 def test_no_isinstance(self):
1228 with self.assertRaises(TypeError):
1229 isinstance(1, NotRequired[int])
1230 with self.assertRaises(TypeError):
1231 issubclass(int, NotRequired)
1232
1233
1234 class IntVarTests(BaseTestCase):
1235 def test_valid(self):
1236 IntVar("T_ints")
1237
1238 def test_invalid(self):
1239 with self.assertRaises(TypeError):
1240 IntVar("T_ints", int)
1241 with self.assertRaises(TypeError):
1242 IntVar("T_ints", bound=int)
1243 with self.assertRaises(TypeError):
1244 IntVar("T_ints", covariant=True)
1245
1246
1247 class LiteralTests(BaseTestCase):
1248 def test_basics(self):
1249 Literal[1]
1250 Literal[1, 2, 3]
1251 Literal["x", "y", "z"]
1252 Literal[None]
1253
1254 def test_enum(self):
1255 import enum
1256 class My(enum.Enum):
1257 A = 'A'
1258
1259 self.assertEqual(Literal[My.A].__args__, (My.A,))
1260
1261 def test_strange_parameters_are_allowed(self):
1262 # These are explicitly allowed by the typing spec
1263 Literal[Literal[1, 2], Literal[4, 5]]
1264 Literal[b"foo", "bar"]
1265
1266 # Type checkers should reject these types, but we do not
1267 # raise errors at runtime to maintain maximum flexibility
1268 Literal[int]
1269 Literal[3j + 2, ..., ()]
1270 Literal[{"foo": 3, "bar": 4}]
1271 Literal[T]
1272
1273 def test_literals_inside_other_types(self):
1274 List[Literal[1, 2, 3]]
1275 List[Literal[("foo", "bar", "baz")]]
1276
1277 def test_repr(self):
1278 # we backport various bugfixes that were added in 3.10.1 and earlier
1279 if sys.version_info >= (3, 10, 1):
1280 mod_name = 'typing'
1281 else:
1282 mod_name = 'typing_extensions'
1283 self.assertEqual(repr(Literal[1]), mod_name + ".Literal[1]")
1284 self.assertEqual(repr(Literal[1, True, "foo"]), mod_name + ".Literal[1, True, 'foo']")
1285 self.assertEqual(repr(Literal[int]), mod_name + ".Literal[int]")
1286 self.assertEqual(repr(Literal), mod_name + ".Literal")
1287 self.assertEqual(repr(Literal[None]), mod_name + ".Literal[None]")
1288 self.assertEqual(repr(Literal[1, 2, 3, 3]), mod_name + ".Literal[1, 2, 3]")
1289
1290 def test_cannot_init(self):
1291 with self.assertRaises(TypeError):
1292 Literal()
1293 with self.assertRaises(TypeError):
1294 Literal[1]()
1295 with self.assertRaises(TypeError):
1296 type(Literal)()
1297 with self.assertRaises(TypeError):
1298 type(Literal[1])()
1299
1300 def test_no_isinstance_or_issubclass(self):
1301 with self.assertRaises(TypeError):
1302 isinstance(1, Literal[1])
1303 with self.assertRaises(TypeError):
1304 isinstance(int, Literal[1])
1305 with self.assertRaises(TypeError):
1306 issubclass(1, Literal[1])
1307 with self.assertRaises(TypeError):
1308 issubclass(int, Literal[1])
1309
1310 def test_no_subclassing(self):
1311 with self.assertRaises(TypeError):
1312 class Foo(Literal[1]): pass
1313 with self.assertRaises(TypeError):
1314 class Bar(Literal): pass
1315
1316 def test_no_multiple_subscripts(self):
1317 with self.assertRaises(TypeError):
1318 Literal[1][1]
1319
1320 def test_equal(self):
1321 self.assertNotEqual(Literal[0], Literal[False])
1322 self.assertNotEqual(Literal[True], Literal[1])
1323 self.assertNotEqual(Literal[1], Literal[2])
1324 self.assertNotEqual(Literal[1, True], Literal[1])
1325 self.assertNotEqual(Literal[1, True], Literal[1, 1])
1326 self.assertNotEqual(Literal[1, 2], Literal[True, 2])
1327 self.assertEqual(Literal[1], Literal[1])
1328 self.assertEqual(Literal[1, 2], Literal[2, 1])
1329 self.assertEqual(Literal[1, 2, 3], Literal[1, 2, 3, 3])
1330
1331 def test_hash(self):
1332 self.assertEqual(hash(Literal[1]), hash(Literal[1]))
1333 self.assertEqual(hash(Literal[1, 2]), hash(Literal[2, 1]))
1334 self.assertEqual(hash(Literal[1, 2, 3]), hash(Literal[1, 2, 3, 3]))
1335
1336 def test_args(self):
1337 self.assertEqual(Literal[1, 2, 3].__args__, (1, 2, 3))
1338 self.assertEqual(Literal[1, 2, 3, 3].__args__, (1, 2, 3))
1339 self.assertEqual(Literal[1, Literal[2], Literal[3, 4]].__args__, (1, 2, 3, 4))
1340
1341 def test_union_of_literals(self):
1342 self.assertEqual(Union[Literal[1], Literal[2]].__args__,
1343 (Literal[1], Literal[2]))
1344 self.assertEqual(Union[Literal[1], Literal[1]],
1345 Literal[1])
1346
1347 self.assertEqual(Union[Literal[False], Literal[0]].__args__,
1348 (Literal[False], Literal[0]))
1349 self.assertEqual(Union[Literal[True], Literal[1]].__args__,
1350 (Literal[True], Literal[1]))
1351
1352 import enum
1353 class Ints(enum.IntEnum):
1354 A = 0
1355 B = 1
1356
1357 self.assertEqual(Union[Literal[Ints.A], Literal[Ints.B]].__args__,
1358 (Literal[Ints.A], Literal[Ints.B]))
1359
1360 self.assertEqual(Union[Literal[Ints.A], Literal[Ints.A]],
1361 Literal[Ints.A])
1362 self.assertEqual(Union[Literal[Ints.B], Literal[Ints.B]],
1363 Literal[Ints.B])
1364
1365 self.assertEqual(Union[Literal[0], Literal[Ints.A], Literal[False]].__args__,
1366 (Literal[0], Literal[Ints.A], Literal[False]))
1367 self.assertEqual(Union[Literal[1], Literal[Ints.B], Literal[True]].__args__,
1368 (Literal[1], Literal[Ints.B], Literal[True]))
1369
1370 @skipUnless(TYPING_3_10_0, "Python 3.10+ required")
1371 def test_or_type_operator_with_Literal(self):
1372 self.assertEqual((Literal[1] | Literal[2]).__args__,
1373 (Literal[1], Literal[2]))
1374
1375 self.assertEqual((Literal[0] | Literal[False]).__args__,
1376 (Literal[0], Literal[False]))
1377 self.assertEqual((Literal[1] | Literal[True]).__args__,
1378 (Literal[1], Literal[True]))
1379
1380 self.assertEqual(Literal[1] | Literal[1], Literal[1])
1381 self.assertEqual(Literal['a'] | Literal['a'], Literal['a'])
1382
1383 import enum
1384 class Ints(enum.IntEnum):
1385 A = 0
1386 B = 1
1387
1388 self.assertEqual(Literal[Ints.A] | Literal[Ints.A], Literal[Ints.A])
1389 self.assertEqual(Literal[Ints.B] | Literal[Ints.B], Literal[Ints.B])
1390
1391 self.assertEqual((Literal[Ints.B] | Literal[Ints.A]).__args__,
1392 (Literal[Ints.B], Literal[Ints.A]))
1393
1394 self.assertEqual((Literal[0] | Literal[Ints.A]).__args__,
1395 (Literal[0], Literal[Ints.A]))
1396 self.assertEqual((Literal[1] | Literal[Ints.B]).__args__,
1397 (Literal[1], Literal[Ints.B]))
1398
1399 def test_flatten(self):
1400 l1 = Literal[Literal[1], Literal[2], Literal[3]]
1401 l2 = Literal[Literal[1, 2], 3]
1402 l3 = Literal[Literal[1, 2, 3]]
1403 for lit in l1, l2, l3:
1404 self.assertEqual(lit, Literal[1, 2, 3])
1405 self.assertEqual(lit.__args__, (1, 2, 3))
1406
1407 def test_does_not_flatten_enum(self):
1408 import enum
1409 class Ints(enum.IntEnum):
1410 A = 1
1411 B = 2
1412
1413 literal = Literal[
1414 Literal[Ints.A],
1415 Literal[Ints.B],
1416 Literal[1],
1417 Literal[2],
1418 ]
1419 self.assertEqual(literal.__args__, (Ints.A, Ints.B, 1, 2))
1420
1421 def test_caching_of_Literal_respects_type(self):
1422 self.assertIs(type(Literal[1].__args__[0]), int)
1423 self.assertIs(type(Literal[True].__args__[0]), bool)
1424
1425
1426 class MethodHolder:
1427 @classmethod
1428 def clsmethod(cls): ...
1429 @staticmethod
1430 def stmethod(): ...
1431 def method(self): ...
1432
1433
1434 if TYPING_3_11_0:
1435 registry_holder = typing
1436 else:
1437 registry_holder = typing_extensions
1438
1439
1440 class OverloadTests(BaseTestCase):
1441
1442 def test_overload_fails(self):
1443 with self.assertRaises(RuntimeError):
1444
1445 @overload
1446 def blah():
1447 pass
1448
1449 blah()
1450
1451 def test_overload_succeeds(self):
1452 @overload
1453 def blah():
1454 pass
1455
1456 def blah():
1457 pass
1458
1459 blah()
1460
1461 @skipIf(
1462 sys.implementation.name == "pypy",
1463 "sum() and print() are not compiled in pypy"
1464 )
1465 @patch(
1466 f"{registry_holder.__name__}._overload_registry",
1467 defaultdict(lambda: defaultdict(dict))
1468 )
1469 def test_overload_on_compiled_functions(self):
1470 registry = registry_holder._overload_registry
1471 # The registry starts out empty:
1472 self.assertEqual(registry, {})
1473
1474 # This should just not fail:
1475 overload(sum)
1476 overload(print)
1477
1478 # No overloads are recorded:
1479 self.assertEqual(get_overloads(sum), [])
1480 self.assertEqual(get_overloads(print), [])
1481
1482 def set_up_overloads(self):
1483 def blah():
1484 pass
1485
1486 overload1 = blah
1487 overload(blah)
1488
1489 def blah():
1490 pass
1491
1492 overload2 = blah
1493 overload(blah)
1494
1495 def blah():
1496 pass
1497
1498 return blah, [overload1, overload2]
1499
1500 # Make sure we don't clear the global overload registry
1501 @patch(
1502 f"{registry_holder.__name__}._overload_registry",
1503 defaultdict(lambda: defaultdict(dict))
1504 )
1505 def test_overload_registry(self):
1506 registry = registry_holder._overload_registry
1507 # The registry starts out empty
1508 self.assertEqual(registry, {})
1509
1510 impl, overloads = self.set_up_overloads()
1511 self.assertNotEqual(registry, {})
1512 self.assertEqual(list(get_overloads(impl)), overloads)
1513
1514 def some_other_func(): pass
1515 overload(some_other_func)
1516 other_overload = some_other_func
1517 def some_other_func(): pass
1518 self.assertEqual(list(get_overloads(some_other_func)), [other_overload])
1519 # Unrelated function still has no overloads:
1520 def not_overloaded(): pass
1521 self.assertEqual(list(get_overloads(not_overloaded)), [])
1522
1523 # Make sure that after we clear all overloads, the registry is
1524 # completely empty.
1525 clear_overloads()
1526 self.assertEqual(registry, {})
1527 self.assertEqual(get_overloads(impl), [])
1528
1529 # Querying a function with no overloads shouldn't change the registry.
1530 def the_only_one(): pass
1531 self.assertEqual(get_overloads(the_only_one), [])
1532 self.assertEqual(registry, {})
1533
1534 def test_overload_registry_repeated(self):
1535 for _ in range(2):
1536 impl, overloads = self.set_up_overloads()
1537
1538 self.assertEqual(list(get_overloads(impl)), overloads)
1539
1540
1541 class AssertTypeTests(BaseTestCase):
1542
1543 def test_basics(self):
1544 arg = 42
1545 self.assertIs(assert_type(arg, int), arg)
1546 self.assertIs(assert_type(arg, Union[str, float]), arg)
1547 self.assertIs(assert_type(arg, AnyStr), arg)
1548 self.assertIs(assert_type(arg, None), arg)
1549
1550 def test_errors(self):
1551 # Bogus calls are not expected to fail.
1552 arg = 42
1553 self.assertIs(assert_type(arg, 42), arg)
1554 self.assertIs(assert_type(arg, 'hello'), arg)
1555
1556
1557 T_a = TypeVar('T_a')
1558
1559 class AwaitableWrapper(Awaitable[T_a]):
1560
1561 def __init__(self, value):
1562 self.value = value
1563
1564 def __await__(self) -> typing.Iterator[T_a]:
1565 yield
1566 return self.value # pragma: no cover
1567
1568 class AsyncIteratorWrapper(AsyncIterator[T_a]):
1569
1570 def __init__(self, value: Iterable[T_a]):
1571 self.value = value
1572
1573 def __aiter__(self) -> AsyncIterator[T_a]:
1574 return self # pragma: no cover
1575
1576 async def __anext__(self) -> T_a:
1577 data = await self.value
1578 if data:
1579 return data
1580 else:
1581 raise StopAsyncIteration
1582
1583 class ACM:
1584 async def __aenter__(self) -> int:
1585 return 42
1586
1587 async def __aexit__(self, etype, eval, tb):
1588 return None
1589
1590
1591 class A:
1592 y: float
1593 class B(A):
1594 x: ClassVar[Optional['B']] = None
1595 y: int
1596 b: int
1597 class CSub(B):
1598 z: ClassVar['CSub'] = B()
1599 class G(Generic[T]):
1600 lst: ClassVar[List[T]] = []
1601
1602 class Loop:
1603 attr: Final['Loop']
1604
1605 class NoneAndForward:
1606 parent: 'NoneAndForward'
1607 meaning: None
1608
1609 class XRepr(NamedTuple):
1610 x: int
1611 y: int = 1
1612
1613 def __str__(self):
1614 return f'{self.x} -> {self.y}'
1615
1616 def __add__(self, other):
1617 return 0
1618
1619 @runtime_checkable
1620 class HasCallProtocol(Protocol):
1621 __call__: typing.Callable
1622
1623
1624 async def g_with(am: AsyncContextManager[int]):
1625 x: int
1626 async with am as x:
1627 return x
1628
1629 try:
1630 g_with(ACM()).send(None)
1631 except StopIteration as e:
1632 assert e.args[0] == 42
1633
1634 Label = TypedDict('Label', [('label', str)])
1635
1636 class Point2D(TypedDict):
1637 x: int
1638 y: int
1639
1640 class Point2Dor3D(Point2D, total=False):
1641 z: int
1642
1643 class LabelPoint2D(Point2D, Label): ...
1644
1645 class Options(TypedDict, total=False):
1646 log_level: int
1647 log_path: str
1648
1649 class BaseAnimal(TypedDict):
1650 name: str
1651
1652 class Animal(BaseAnimal, total=False):
1653 voice: str
1654 tail: bool
1655
1656 class Cat(Animal):
1657 fur_color: str
1658
1659 class TotalMovie(TypedDict):
1660 title: str
1661 year: NotRequired[int]
1662
1663 class NontotalMovie(TypedDict, total=False):
1664 title: Required[str]
1665 year: int
1666
1667 class ParentNontotalMovie(TypedDict, total=False):
1668 title: Required[str]
1669
1670 class ChildTotalMovie(ParentNontotalMovie):
1671 year: NotRequired[int]
1672
1673 class ParentDeeplyAnnotatedMovie(TypedDict):
1674 title: Annotated[Annotated[Required[str], "foobar"], "another level"]
1675
1676 class ChildDeeplyAnnotatedMovie(ParentDeeplyAnnotatedMovie):
1677 year: NotRequired[Annotated[int, 2000]]
1678
1679 class AnnotatedMovie(TypedDict):
1680 title: Annotated[Required[str], "foobar"]
1681 year: NotRequired[Annotated[int, 2000]]
1682
1683 class WeirdlyQuotedMovie(TypedDict):
1684 title: Annotated['Annotated[Required[str], "foobar"]', "another level"]
1685 year: NotRequired['Annotated[int, 2000]']
1686
1687
1688 gth = get_type_hints
1689
1690
1691 class GetTypeHintTests(BaseTestCase):
1692 @classmethod
1693 def setUpClass(cls):
1694 with tempfile.TemporaryDirectory() as tempdir:
1695 sys.path.append(tempdir)
1696 Path(tempdir, "ann_module.py").write_text(ANN_MODULE_SOURCE)
1697 Path(tempdir, "ann_module2.py").write_text(ANN_MODULE_2_SOURCE)
1698 Path(tempdir, "ann_module3.py").write_text(ANN_MODULE_3_SOURCE)
1699 cls.ann_module = importlib.import_module("ann_module")
1700 cls.ann_module2 = importlib.import_module("ann_module2")
1701 cls.ann_module3 = importlib.import_module("ann_module3")
1702 sys.path.pop()
1703
1704 @classmethod
1705 def tearDownClass(cls):
1706 for modname in "ann_module", "ann_module2", "ann_module3":
1707 delattr(cls, modname)
1708 del sys.modules[modname]
1709
1710 def test_get_type_hints_modules(self):
1711 if sys.version_info >= (3, 14):
1712 ann_module_type_hints = {'f': Tuple[int, int], 'x': int, 'y': str}
1713 else:
1714 ann_module_type_hints = {1: 2, 'f': Tuple[int, int], 'x': int, 'y': str}
1715 self.assertEqual(gth(self.ann_module), ann_module_type_hints)
1716 self.assertEqual(gth(self.ann_module2), {})
1717 self.assertEqual(gth(self.ann_module3), {})
1718
1719 def test_get_type_hints_classes(self):
1720 self.assertEqual(gth(self.ann_module.C, self.ann_module.__dict__),
1721 {'y': Optional[self.ann_module.C]})
1722 self.assertIsInstance(gth(self.ann_module.j_class), dict)
1723 if sys.version_info >= (3, 14):
1724 self.assertEqual(gth(self.ann_module.M), {'o': type})
1725 else:
1726 self.assertEqual(gth(self.ann_module.M), {'123': 123, 'o': type})
1727 self.assertEqual(gth(self.ann_module.D),
1728 {'j': str, 'k': str, 'y': Optional[self.ann_module.C]})
1729 self.assertEqual(gth(self.ann_module.Y), {'z': int})
1730 self.assertEqual(gth(self.ann_module.h_class),
1731 {'y': Optional[self.ann_module.C]})
1732 self.assertEqual(gth(self.ann_module.S), {'x': str, 'y': str})
1733 self.assertEqual(gth(self.ann_module.foo), {'x': int})
1734 self.assertEqual(gth(NoneAndForward, globals()),
1735 {'parent': NoneAndForward, 'meaning': type(None)})
1736
1737 def test_respect_no_type_check(self):
1738 @no_type_check
1739 class NoTpCheck:
1740 class Inn:
1741 def __init__(self, x: 'not a type'): ... # noqa: F722 # (yes, there's a syntax error in this annotation, that's the point)
1742 self.assertTrue(NoTpCheck.__no_type_check__)
1743 self.assertTrue(NoTpCheck.Inn.__init__.__no_type_check__)
1744 self.assertEqual(gth(self.ann_module2.NTC.meth), {})
1745 class ABase(Generic[T]):
1746 def meth(x: int): ...
1747 @no_type_check
1748 class Der(ABase): ...
1749 self.assertEqual(gth(ABase.meth), {'x': int})
1750
1751 def test_get_type_hints_ClassVar(self):
1752 self.assertEqual(gth(self.ann_module2.CV, self.ann_module2.__dict__),
1753 {'var': ClassVar[self.ann_module2.CV]})
1754 self.assertEqual(gth(B, globals()),
1755 {'y': int, 'x': ClassVar[Optional[B]], 'b': int})
1756 self.assertEqual(gth(CSub, globals()),
1757 {'z': ClassVar[CSub], 'y': int, 'b': int,
1758 'x': ClassVar[Optional[B]]})
1759 self.assertEqual(gth(G), {'lst': ClassVar[List[T]]})
1760
1761 def test_final_forward_ref(self):
1762 self.assertEqual(gth(Loop, globals())['attr'], Final[Loop])
1763 self.assertNotEqual(gth(Loop, globals())['attr'], Final[int])
1764 self.assertNotEqual(gth(Loop, globals())['attr'], Final)
1765
1766 def test_annotation_and_optional_default(self):
1767 annotation = Annotated[Union[int, None], "data"]
1768 NoneAlias = None
1769 StrAlias = str
1770 T_default = TypeVar("T_default", default=None)
1771 Ts = TypeVarTuple("Ts")
1772
1773 cases = {
1774 # annotation: expected_type_hints
1775 Annotated[None, "none"] : Annotated[None, "none"],
1776 annotation : annotation,
1777 Optional[int] : Optional[int],
1778 Optional[List[str]] : Optional[List[str]],
1779 Optional[annotation] : Optional[annotation],
1780 Union[str, None, str] : Optional[str],
1781 Unpack[Tuple[int, None]]: Unpack[Tuple[int, None]],
1782 }
1783 # contains a ForwardRef, TypeVar(~prefix) or no expression
1784 do_not_stringify_cases = {
1785 () : {}, # Special-cased below to create an unannotated parameter
1786 int : int,
1787 "int" : int,
1788 None : type(None),
1789 "NoneAlias" : type(None),
1790 List["str"] : List[str],
1791 Union[str, "str"] : str,
1792 Union[str, None, "str"] : Optional[str],
1793 Union[str, "NoneAlias", "StrAlias"]: Optional[str],
1794 Union[str, "Union[None, StrAlias]"]: Optional[str],
1795 Union["annotation", T_default] : Union[annotation, T_default],
1796 Annotated["annotation", "nested"] : Annotated[Union[int, None], "data", "nested"],
1797 # Note: A starred *Ts will use typing.Unpack in 3.11+ see Issue #485
1798 Unpack[Ts] : Unpack[Ts],
1799 }
1800 # Note: A starred *Ts will use typing.Unpack in 3.11+ see Issue #485
1801 if TYPING_3_15_0:
1802 # The repr is typing.Unpack[~Ts], which cannot be evaluated.
1803 do_not_stringify_cases[Unpack[Ts]] = Unpack[Ts]
1804 else:
1805 cases[Unpack[Ts]] = Unpack[Ts]
1806 if TYPING_3_10_0: # cannot construct UnionTypes before 3.10
1807 do_not_stringify_cases["str | NoneAlias | StrAlias"] = str | None
1808 cases[str | None] = Optional[str]
1809 cases.update(do_not_stringify_cases)
1810 for (annot, expected), none_default, as_str, wrap_optional in itertools.product(
1811 cases.items(), (False, True), (False, True), (False, True)
1812 ):
1813 # Special case:
1814 skip_reason = None
1815 annot_unchanged = annot
1816 if sys.version_info[:2] == (3, 10) and annot == "str | NoneAlias | StrAlias" and none_default:
1817 # In 3.10 converts Optional[str | None] to Optional[str] which has a different repr
1818 skip_reason = "UnionType not preserved in 3.10"
1819 if wrap_optional:
1820 if annot_unchanged == ():
1821 continue
1822 annot = Optional[annot]
1823 expected = {"x": Optional[expected]}
1824 else:
1825 expected = {"x": expected} if annot_unchanged != () else {}
1826 if as_str:
1827 if annot_unchanged in do_not_stringify_cases or annot_unchanged == ():
1828 continue
1829 annot = str(annot)
1830 with self.subTest(
1831 annotation=annot,
1832 as_str=as_str,
1833 wrap_optional=wrap_optional,
1834 none_default=none_default,
1835 expected_type_hints=expected,
1836 ):
1837 # Create function to check
1838 if annot_unchanged == ():
1839 if none_default:
1840 def func(x=None): pass
1841 else:
1842 def func(x): pass
1843 elif none_default:
1844 def func(x: annot = None): pass
1845 else:
1846 def func(x: annot): pass
1847 type_hints = get_type_hints(func, globals(), locals(), include_extras=True)
1848 # Equality
1849 self.assertEqual(type_hints, expected)
1850 # Hash
1851 for k in type_hints.keys():
1852 self.assertEqual(hash(type_hints[k]), hash(expected[k]))
1853 # Test if UnionTypes are preserved
1854 self.assertIs(type(type_hints[k]), type(expected[k]))
1855 # Repr
1856 with self.subTest("Check str and repr"):
1857 if skip_reason == "UnionType not preserved in 3.10":
1858 self.skipTest(skip_reason)
1859 self.assertEqual(repr(type_hints), repr(expected))
1860
1861
1862 class GetUtilitiesTestCase(TestCase):
1863 def test_get_origin(self):
1864 T = TypeVar('T')
1865 P = ParamSpec('P')
1866 Ts = TypeVarTuple('Ts')
1867 class C(Generic[T]): pass
1868 self.assertIs(get_origin(C[int]), C)
1869 self.assertIs(get_origin(C[T]), C)
1870 self.assertIs(get_origin(int), None)
1871 self.assertIs(get_origin(ClassVar[int]), ClassVar)
1872 self.assertIs(get_origin(Union[int, str]), Union)
1873 self.assertIs(get_origin(Literal[42, 43]), Literal)
1874 self.assertIs(get_origin(Final[List[int]]), Final)
1875 self.assertIs(get_origin(Generic), Generic)
1876 self.assertIs(get_origin(Generic[T]), Generic)
1877 self.assertIs(get_origin(List[Tuple[T, T]][int]), list)
1878 self.assertIs(get_origin(Annotated[T, 'thing']), Annotated)
1879 self.assertIs(get_origin(List), list)
1880 self.assertIs(get_origin(Tuple), tuple)
1881 self.assertIs(get_origin(Callable), collections.abc.Callable)
1882 self.assertIs(get_origin(list[int]), list)
1883 self.assertIs(get_origin(list), None)
1884 self.assertIs(get_origin(P.args), P)
1885 self.assertIs(get_origin(P.kwargs), P)
1886 self.assertIs(get_origin(Required[int]), Required)
1887 self.assertIs(get_origin(NotRequired[int]), NotRequired)
1888 self.assertIs(get_origin(Unpack[Ts]), Unpack)
1889 self.assertIs(get_origin(Unpack), None)
1890
1891 def test_get_args(self):
1892 T = TypeVar('T')
1893 Ts = TypeVarTuple('Ts')
1894 class C(Generic[T]): pass
1895 self.assertEqual(get_args(C[int]), (int,))
1896 self.assertEqual(get_args(C[T]), (T,))
1897 self.assertEqual(get_args(int), ())
1898 self.assertEqual(get_args(ClassVar[int]), (int,))
1899 self.assertEqual(get_args(Union[int, str]), (int, str))
1900 self.assertEqual(get_args(Literal[42, 43]), (42, 43))
1901 self.assertEqual(get_args(Final[List[int]]), (List[int],))
1902 self.assertEqual(get_args(Union[int, Tuple[T, int]][str]),
1903 (int, Tuple[str, int]))
1904 self.assertEqual(get_args(typing.Dict[int, Tuple[T, T]][Optional[int]]),
1905 (int, Tuple[Optional[int], Optional[int]]))
1906 self.assertEqual(get_args(Callable[[], T][int]), ([], int))
1907 self.assertEqual(get_args(Callable[..., int]), (..., int))
1908 self.assertEqual(get_args(Union[int, Callable[[Tuple[T, ...]], str]]),
1909 (int, Callable[[Tuple[T, ...]], str]))
1910 self.assertEqual(get_args(Tuple[int, ...]), (int, ...))
1911 if TYPING_3_11_0:
1912 self.assertEqual(get_args(Tuple[()]), ())
1913 else:
1914 self.assertEqual(get_args(Tuple[()]), ((),))
1915 self.assertEqual(get_args(Annotated[T, 'one', 2, ['three']]), (T, 'one', 2, ['three']))
1916 self.assertEqual(get_args(List), ())
1917 self.assertEqual(get_args(Tuple), ())
1918 self.assertEqual(get_args(Callable), ())
1919 self.assertEqual(get_args(list[int]), (int,))
1920 self.assertEqual(get_args(list), ())
1921 # Support Python versions with and without the fix for
1922 # https://bugs.python.org/issue42195
1923 # The first variant is for 3.9.2+, the second for 3.9.0 and 1
1924 self.assertIn(get_args(collections.abc.Callable[[int], str]),
1925 (([int], str), ([[int]], str)))
1926 self.assertIn(get_args(collections.abc.Callable[[], str]),
1927 (([], str), ([[]], str)))
1928 self.assertEqual(get_args(collections.abc.Callable[..., str]), (..., str))
1929 P = ParamSpec('P')
1930 # In 3.9 we use typing_extensions's hacky implementation
1931 # of ParamSpec, which gets incorrectly wrapped in a list
1932 self.assertIn(get_args(Callable[P, int]), [(P, int), ([P], int)])
1933 self.assertEqual(get_args(Required[int]), (int,))
1934 self.assertEqual(get_args(NotRequired[int]), (int,))
1935 self.assertEqual(get_args(Unpack[Ts]), (Ts,))
1936 self.assertEqual(get_args(Unpack), ())
1937 self.assertEqual(get_args(Callable[Concatenate[int, P], int]),
1938 (Concatenate[int, P], int))
1939 self.assertEqual(get_args(Callable[Concatenate[int, ...], int]),
1940 (Concatenate[int, ...], int))
1941
1942
1943 class CollectionsAbcTests(BaseTestCase):
1944
1945 def test_isinstance_collections(self):
1946 self.assertNotIsInstance(1, collections.abc.Mapping)
1947 self.assertNotIsInstance(1, collections.abc.Iterable)
1948 self.assertNotIsInstance(1, collections.abc.Container)
1949 self.assertNotIsInstance(1, collections.abc.Sized)
1950 with self.assertRaises(TypeError):
1951 isinstance(collections.deque(), typing_extensions.Deque[int])
1952 with self.assertRaises(TypeError):
1953 issubclass(collections.Counter, typing_extensions.Counter[str])
1954
1955 def test_awaitable(self):
1956 async def foo() -> typing_extensions.Awaitable[int]:
1957 return await AwaitableWrapper(42)
1958
1959 g = foo()
1960 self.assertIsInstance(g, typing_extensions.Awaitable)
1961 self.assertNotIsInstance(foo, typing_extensions.Awaitable)
1962 g.send(None) # Run foo() till completion, to avoid warning.
1963
1964 def test_coroutine(self):
1965 async def foo():
1966 return
1967
1968 g = foo()
1969 self.assertIsInstance(g, typing_extensions.Coroutine)
1970 with self.assertRaises(TypeError):
1971 isinstance(g, typing_extensions.Coroutine[int])
1972 self.assertNotIsInstance(foo, typing_extensions.Coroutine)
1973 try:
1974 g.send(None)
1975 except StopIteration:
1976 pass
1977
1978 def test_async_iterable(self):
1979 base_it: Iterator[int] = range(10)
1980 it = AsyncIteratorWrapper(base_it)
1981 self.assertIsInstance(it, typing_extensions.AsyncIterable)
1982 self.assertIsInstance(it, typing_extensions.AsyncIterable)
1983 self.assertNotIsInstance(42, typing_extensions.AsyncIterable)
1984
1985 def test_async_iterator(self):
1986 base_it: Iterator[int] = range(10)
1987 it = AsyncIteratorWrapper(base_it)
1988 self.assertIsInstance(it, typing_extensions.AsyncIterator)
1989 self.assertNotIsInstance(42, typing_extensions.AsyncIterator)
1990
1991 def test_deque(self):
1992 self.assertIsSubclass(collections.deque, typing_extensions.Deque)
1993 class MyDeque(typing_extensions.Deque[int]): ...
1994 self.assertIsInstance(MyDeque(), collections.deque)
1995
1996 def test_counter(self):
1997 self.assertIsSubclass(collections.Counter, typing_extensions.Counter)
1998
1999 def test_defaultdict_instantiation(self):
2000 self.assertIs(
2001 type(typing_extensions.DefaultDict()),
2002 collections.defaultdict)
2003 self.assertIs(
2004 type(typing_extensions.DefaultDict[KT, VT]()),
2005 collections.defaultdict)
2006 self.assertIs(
2007 type(typing_extensions.DefaultDict[str, int]()),
2008 collections.defaultdict)
2009
2010 def test_defaultdict_subclass(self):
2011
2012 class MyDefDict(typing_extensions.DefaultDict[str, int]):
2013 pass
2014
2015 dd = MyDefDict()
2016 self.assertIsInstance(dd, MyDefDict)
2017
2018 self.assertIsSubclass(MyDefDict, collections.defaultdict)
2019 self.assertNotIsSubclass(collections.defaultdict, MyDefDict)
2020
2021 def test_ordereddict_instantiation(self):
2022 self.assertIs(
2023 type(typing_extensions.OrderedDict()),
2024 collections.OrderedDict)
2025 self.assertIs(
2026 type(typing_extensions.OrderedDict[KT, VT]()),
2027 collections.OrderedDict)
2028 self.assertIs(
2029 type(typing_extensions.OrderedDict[str, int]()),
2030 collections.OrderedDict)
2031
2032 def test_ordereddict_subclass(self):
2033
2034 class MyOrdDict(typing_extensions.OrderedDict[str, int]):
2035 pass
2036
2037 od = MyOrdDict()
2038 self.assertIsInstance(od, MyOrdDict)
2039
2040 self.assertIsSubclass(MyOrdDict, collections.OrderedDict)
2041 self.assertNotIsSubclass(collections.OrderedDict, MyOrdDict)
2042
2043 def test_chainmap_instantiation(self):
2044 self.assertIs(type(typing_extensions.ChainMap()), collections.ChainMap)
2045 self.assertIs(type(typing_extensions.ChainMap[KT, VT]()), collections.ChainMap)
2046 self.assertIs(type(typing_extensions.ChainMap[str, int]()), collections.ChainMap)
2047 class CM(typing_extensions.ChainMap[KT, VT]): ...
2048 self.assertIs(type(CM[int, str]()), CM)
2049
2050 def test_chainmap_subclass(self):
2051
2052 class MyChainMap(typing_extensions.ChainMap[str, int]):
2053 pass
2054
2055 cm = MyChainMap()
2056 self.assertIsInstance(cm, MyChainMap)
2057
2058 self.assertIsSubclass(MyChainMap, collections.ChainMap)
2059 self.assertNotIsSubclass(collections.ChainMap, MyChainMap)
2060
2061 def test_deque_instantiation(self):
2062 self.assertIs(type(typing_extensions.Deque()), collections.deque)
2063 self.assertIs(type(typing_extensions.Deque[T]()), collections.deque)
2064 self.assertIs(type(typing_extensions.Deque[int]()), collections.deque)
2065 class D(typing_extensions.Deque[T]): ...
2066 self.assertIs(type(D[int]()), D)
2067
2068 def test_counter_instantiation(self):
2069 self.assertIs(type(typing_extensions.Counter()), collections.Counter)
2070 self.assertIs(type(typing_extensions.Counter[T]()), collections.Counter)
2071 self.assertIs(type(typing_extensions.Counter[int]()), collections.Counter)
2072 class C(typing_extensions.Counter[T]): ...
2073 self.assertIs(type(C[int]()), C)
2074 self.assertEqual(C.__bases__, (collections.Counter, typing.Generic))
2075
2076 def test_counter_subclass_instantiation(self):
2077
2078 class MyCounter(typing_extensions.Counter[int]):
2079 pass
2080
2081 d = MyCounter()
2082 self.assertIsInstance(d, MyCounter)
2083 self.assertIsInstance(d, collections.Counter)
2084 self.assertIsInstance(d, typing_extensions.Counter)
2085
2086
2087 # These are a separate TestCase class,
2088 # as (unlike most collections.abc aliases in typing_extensions),
2089 # these are reimplemented on Python <=3.12 so that we can provide
2090 # default values for the second and third parameters
2091 class GeneratorTests(BaseTestCase):
2092
2093 def test_generator_basics(self):
2094 def foo():
2095 yield 42 # pragma: no cover
2096 g = foo()
2097
2098 self.assertIsInstance(g, typing_extensions.Generator)
2099 self.assertNotIsInstance(foo, typing_extensions.Generator)
2100 self.assertIsSubclass(type(g), typing_extensions.Generator)
2101 self.assertNotIsSubclass(type(foo), typing_extensions.Generator)
2102
2103 parameterized = typing_extensions.Generator[int, str, None]
2104 with self.assertRaises(TypeError):
2105 isinstance(g, parameterized)
2106 with self.assertRaises(TypeError):
2107 issubclass(type(g), parameterized)
2108
2109 def test_generator_default(self):
2110 g1 = typing_extensions.Generator[int]
2111 g2 = typing_extensions.Generator[int, None, None]
2112 self.assertEqual(get_args(g1), (int, type(None), type(None)))
2113 self.assertEqual(get_args(g1), get_args(g2))
2114
2115 g3 = typing_extensions.Generator[int, float]
2116 g4 = typing_extensions.Generator[int, float, None]
2117 self.assertEqual(get_args(g3), (int, float, type(None)))
2118 self.assertEqual(get_args(g3), get_args(g4))
2119
2120 def test_no_generator_instantiation(self):
2121 with self.assertRaises(TypeError):
2122 typing_extensions.Generator()
2123 with self.assertRaises(TypeError):
2124 typing_extensions.Generator[T, T, T]()
2125 with self.assertRaises(TypeError):
2126 typing_extensions.Generator[int, int, int]()
2127
2128 def test_subclassing_generator(self):
2129 class G(typing_extensions.Generator[int, int, None]):
2130 def send(self, value):
2131 pass
2132 def throw(self, typ, val=None, tb=None):
2133 pass
2134
2135 def g(): yield 0
2136
2137 self.assertIsSubclass(G, typing_extensions.Generator)
2138 self.assertIsSubclass(G, typing_extensions.Iterable)
2139 self.assertIsSubclass(G, collections.abc.Generator)
2140 self.assertIsSubclass(G, collections.abc.Iterable)
2141 self.assertNotIsSubclass(type(g), G)
2142
2143 instance = G()
2144 self.assertIsInstance(instance, typing_extensions.Generator)
2145 self.assertIsInstance(instance, typing_extensions.Iterable)
2146 self.assertIsInstance(instance, collections.abc.Generator)
2147 self.assertIsInstance(instance, collections.abc.Iterable)
2148 self.assertNotIsInstance(type(g), G)
2149 self.assertNotIsInstance(g, G)
2150
2151 def test_async_generator_basics(self):
2152 async def f():
2153 yield 42 # pragma: no cover
2154 g = f()
2155
2156 self.assertIsInstance(g, typing_extensions.AsyncGenerator)
2157 self.assertIsSubclass(type(g), typing_extensions.AsyncGenerator)
2158 self.assertNotIsInstance(f, typing_extensions.AsyncGenerator)
2159 self.assertNotIsSubclass(type(f), typing_extensions.AsyncGenerator)
2160
2161 parameterized = typing_extensions.AsyncGenerator[int, str]
2162 with self.assertRaises(TypeError):
2163 isinstance(g, parameterized)
2164 with self.assertRaises(TypeError):
2165 issubclass(type(g), parameterized)
2166
2167 def test_async_generator_default(self):
2168 ag1 = typing_extensions.AsyncGenerator[int]
2169 ag2 = typing_extensions.AsyncGenerator[int, None]
2170 self.assertEqual(get_args(ag1), (int, type(None)))
2171 self.assertEqual(get_args(ag1), get_args(ag2))
2172
2173 def test_no_async_generator_instantiation(self):
2174 with self.assertRaises(TypeError):
2175 typing_extensions.AsyncGenerator()
2176 with self.assertRaises(TypeError):
2177 typing_extensions.AsyncGenerator[T, T]()
2178 with self.assertRaises(TypeError):
2179 typing_extensions.AsyncGenerator[int, int]()
2180
2181 def test_subclassing_async_generator(self):
2182 class G(typing_extensions.AsyncGenerator[int, int]):
2183 def asend(self, value):
2184 pass
2185 def athrow(self, typ, val=None, tb=None):
2186 pass
2187
2188 async def g(): yield 0
2189
2190 self.assertIsSubclass(G, typing_extensions.AsyncGenerator)
2191 self.assertIsSubclass(G, typing_extensions.AsyncIterable)
2192 self.assertIsSubclass(G, collections.abc.AsyncGenerator)
2193 self.assertIsSubclass(G, collections.abc.AsyncIterable)
2194 self.assertNotIsSubclass(type(g), G)
2195
2196 instance = G()
2197 self.assertIsInstance(instance, typing_extensions.AsyncGenerator)
2198 self.assertIsInstance(instance, typing_extensions.AsyncIterable)
2199 self.assertIsInstance(instance, collections.abc.AsyncGenerator)
2200 self.assertIsInstance(instance, collections.abc.AsyncIterable)
2201 self.assertNotIsInstance(type(g), G)
2202 self.assertNotIsInstance(g, G)
2203
2204 def test_subclassing_subclasshook(self):
2205
2206 class Base(typing_extensions.Generator):
2207 @classmethod
2208 def __subclasshook__(cls, other):
2209 if other.__name__ == 'Foo':
2210 return True
2211 else:
2212 return False
2213
2214 class C(Base): ...
2215 class Foo: ...
2216 class Bar: ...
2217 self.assertIsSubclass(Foo, Base)
2218 self.assertIsSubclass(Foo, C)
2219 self.assertNotIsSubclass(Bar, C)
2220
2221 def test_subclassing_register(self):
2222
2223 class A(typing_extensions.Generator): ...
2224 class B(A): ...
2225
2226 class C: ...
2227 A.register(C)
2228 self.assertIsSubclass(C, A)
2229 self.assertNotIsSubclass(C, B)
2230
2231 class D: ...
2232 B.register(D)
2233 self.assertIsSubclass(D, A)
2234 self.assertIsSubclass(D, B)
2235
2236 class M: ...
2237 collections.abc.Generator.register(M)
2238 self.assertIsSubclass(M, typing_extensions.Generator)
2239
2240 def test_collections_as_base(self):
2241
2242 class M(collections.abc.Generator): ...
2243 self.assertIsSubclass(M, typing_extensions.Generator)
2244 self.assertIsSubclass(M, typing_extensions.Iterable)
2245
2246 class S(collections.abc.AsyncGenerator): ...
2247 self.assertIsSubclass(S, typing_extensions.AsyncGenerator)
2248 self.assertIsSubclass(S, typing_extensions.AsyncIterator)
2249
2250 class A(collections.abc.Generator, metaclass=abc.ABCMeta): ...
2251 class B: ...
2252 A.register(B)
2253 self.assertIsSubclass(B, typing_extensions.Generator)
2254
2255 @skipIf(sys.version_info < (3, 10), "PEP 604 has yet to be")
2256 def test_or_and_ror(self):
2257 self.assertEqual(
2258 typing_extensions.Generator | typing_extensions.AsyncGenerator,
2259 Union[typing_extensions.Generator, typing_extensions.AsyncGenerator]
2260 )
2261 self.assertEqual(
2262 typing_extensions.Generator | typing.Deque,
2263 Union[typing_extensions.Generator, typing.Deque]
2264 )
2265
2266 def test_setattr(self):
2267 origin = collections.abc.Generator
2268 alias = typing_extensions.Generator
2269 original_name = alias._name
2270
2271 def cleanup():
2272 for obj in origin, alias:
2273 for attr in 'foo', '__dunder__':
2274 try:
2275 delattr(obj, attr)
2276 except Exception:
2277 pass
2278 try:
2279 alias._name = original_name
2280 except Exception:
2281 pass
2282
2283 self.addCleanup(cleanup)
2284
2285 # Attribute assignment on generic alias sets attribute on origin
2286 alias.foo = 1
2287 self.assertEqual(alias.foo, 1)
2288 self.assertEqual(origin.foo, 1)
2289 # Except for dunders...
2290 alias.__dunder__ = 2
2291 self.assertEqual(alias.__dunder__, 2)
2292 self.assertRaises(AttributeError, lambda: origin.__dunder__)
2293
2294 # ...and certain known attributes
2295 alias._name = "NewName"
2296 self.assertEqual(alias._name, "NewName")
2297 self.assertRaises(AttributeError, lambda: origin._name)
2298
2299
2300 class OtherABCTests(BaseTestCase):
2301
2302 def test_contextmanager(self):
2303 @contextlib.contextmanager
2304 def manager():
2305 yield 42 # pragma: no cover
2306
2307 cm = manager()
2308 self.assertIsInstance(cm, typing_extensions.ContextManager)
2309 self.assertNotIsInstance(42, typing_extensions.ContextManager)
2310
2311 def test_contextmanager_type_params(self):
2312 cm1 = typing_extensions.ContextManager[int]
2313 self.assertEqual(get_args(cm1), (int, typing.Optional[bool]))
2314 cm2 = typing_extensions.ContextManager[int, None]
2315 self.assertEqual(get_args(cm2), (int, NoneType))
2316
2317 def test_async_contextmanager(self):
2318 class NotACM:
2319 pass
2320 self.assertIsInstance(ACM(), typing_extensions.AsyncContextManager)
2321 self.assertNotIsInstance(NotACM(), typing_extensions.AsyncContextManager)
2322 @contextlib.contextmanager
2323 def manager():
2324 yield 42 # pragma: no cover
2325
2326 cm = manager()
2327 self.assertNotIsInstance(cm, typing_extensions.AsyncContextManager)
2328 self.assertEqual(
2329 typing_extensions.AsyncContextManager[int].__args__,
2330 (int, typing.Optional[bool])
2331 )
2332 with self.assertRaises(TypeError):
2333 isinstance(42, typing_extensions.AsyncContextManager[int])
2334 with self.assertRaises(TypeError):
2335 typing_extensions.AsyncContextManager[int, str, float]
2336
2337 def test_asynccontextmanager_type_params(self):
2338 cm1 = typing_extensions.AsyncContextManager[int]
2339 self.assertEqual(get_args(cm1), (int, typing.Optional[bool]))
2340 cm2 = typing_extensions.AsyncContextManager[int, None]
2341 self.assertEqual(get_args(cm2), (int, NoneType))
2342
2343
2344 class TypeTests(BaseTestCase):
2345
2346 def test_type_basic(self):
2347
2348 class User: pass
2349 class BasicUser(User): pass
2350 class ProUser(User): pass
2351
2352 def new_user(user_class: Type[User]) -> User:
2353 return user_class()
2354
2355 new_user(BasicUser)
2356
2357 def test_type_typevar(self):
2358
2359 class User: pass
2360 class BasicUser(User): pass
2361 class ProUser(User): pass
2362
2363 U = TypeVar('U', bound=User)
2364
2365 def new_user(user_class: Type[U]) -> U:
2366 return user_class()
2367
2368 new_user(BasicUser)
2369
2370 def test_type_optional(self):
2371 A = Optional[Type[BaseException]]
2372
2373 def foo(a: A) -> Optional[BaseException]:
2374 if a is None:
2375 return None
2376 else:
2377 return a()
2378
2379 assert isinstance(foo(KeyboardInterrupt), KeyboardInterrupt)
2380 assert foo(None) is None
2381
2382
2383 class NewTypeTests(BaseTestCase):
2384 @classmethod
2385 def setUpClass(cls):
2386 global UserId
2387 UserId = NewType('UserId', int)
2388 cls.UserName = NewType(cls.__qualname__ + '.UserName', str)
2389
2390 @classmethod
2391 def tearDownClass(cls):
2392 global UserId
2393 del UserId
2394 del cls.UserName
2395
2396 def test_basic(self):
2397 self.assertIsInstance(UserId(5), int)
2398 self.assertIsInstance(self.UserName('Joe'), str)
2399 self.assertEqual(UserId(5) + 1, 6)
2400
2401 def test_errors(self):
2402 with self.assertRaises(TypeError):
2403 issubclass(UserId, int)
2404 with self.assertRaises(TypeError):
2405 class D(UserId):
2406 pass
2407
2408 @skipUnless(TYPING_3_10_0, "PEP 604 has yet to be")
2409 def test_or(self):
2410 for cls in (int, self.UserName):
2411 with self.subTest(cls=cls):
2412 self.assertEqual(UserId | cls, Union[UserId, cls])
2413 self.assertEqual(cls | UserId, Union[cls, UserId])
2414
2415 self.assertEqual(get_args(UserId | cls), (UserId, cls))
2416 self.assertEqual(get_args(cls | UserId), (cls, UserId))
2417
2418 def test_special_attrs(self):
2419 self.assertEqual(UserId.__name__, 'UserId')
2420 self.assertEqual(UserId.__qualname__, 'UserId')
2421 self.assertEqual(UserId.__module__, __name__)
2422 self.assertEqual(UserId.__supertype__, int)
2423
2424 UserName = self.UserName
2425 self.assertEqual(UserName.__name__, 'UserName')
2426 self.assertEqual(UserName.__qualname__,
2427 self.__class__.__qualname__ + '.UserName')
2428 self.assertEqual(UserName.__module__, __name__)
2429 self.assertEqual(UserName.__supertype__, str)
2430
2431 def test_repr(self):
2432 self.assertEqual(repr(UserId), f'{__name__}.UserId')
2433 self.assertEqual(repr(self.UserName),
2434 f'{__name__}.{self.__class__.__qualname__}.UserName')
2435
2436 def test_pickle(self):
2437 UserAge = NewType('UserAge', float)
2438 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
2439 with self.subTest(proto=proto):
2440 pickled = pickle.dumps(UserId, proto)
2441 loaded = pickle.loads(pickled)
2442 self.assertIs(loaded, UserId)
2443
2444 pickled = pickle.dumps(self.UserName, proto)
2445 loaded = pickle.loads(pickled)
2446 self.assertIs(loaded, self.UserName)
2447
2448 with self.assertRaises(pickle.PicklingError):
2449 pickle.dumps(UserAge, proto)
2450
2451 def test_missing__name__(self):
2452 code = ("import typing_extensions\n"
2453 "NT = typing_extensions.NewType('NT', int)\n"
2454 )
2455 exec(code, {})
2456
2457 def test_error_message_when_subclassing(self):
2458 with self.assertRaisesRegex(
2459 TypeError,
2460 re.escape(
2461 "Cannot subclass an instance of NewType. Perhaps you were looking for: "
2462 "`ProUserId = NewType('ProUserId', UserId)`"
2463 )
2464 ):
2465 class ProUserId(UserId):
2466 ...
2467
2468 def test_module_with_incomplete_sys(self):
2469 def does_not_exist(*args):
2470 raise AttributeError
2471 with (
2472 patch("sys._getframemodulename", does_not_exist, create=True),
2473 patch("sys._getframe", does_not_exist, create=True),
2474 ):
2475 X = NewType("X", int)
2476 self.assertEqual(X.__module__, None)
2477
2478
2479 class Coordinate(Protocol):
2480 x: int
2481 y: int
2482
2483 @runtime_checkable
2484 class Point(Coordinate, Protocol):
2485 label: str
2486
2487 class MyPoint:
2488 x: int
2489 y: int
2490 label: str
2491
2492 class XAxis(Protocol):
2493 x: int
2494
2495 class YAxis(Protocol):
2496 y: int
2497
2498 @runtime_checkable
2499 class Position(XAxis, YAxis, Protocol):
2500 pass
2501
2502 @runtime_checkable
2503 class Proto(Protocol):
2504 attr: int
2505
2506 def meth(self, arg: str) -> int:
2507 ...
2508
2509 class Concrete(Proto):
2510 pass
2511
2512 class Other:
2513 attr: int = 1
2514
2515 def meth(self, arg: str) -> int:
2516 if arg == 'this':
2517 return 1
2518 return 0
2519
2520 class NT(NamedTuple):
2521 x: int
2522 y: int
2523
2524
2525 skip_if_py312b1 = skipIf(
2526 sys.version_info == (3, 12, 0, 'beta', 1),
2527 "CPython had bugs in 3.12.0b1"
2528 )
2529
2530
2531 class ProtocolTests(BaseTestCase):
2532 def test_runtime_alias(self):
2533 self.assertIs(runtime, runtime_checkable)
2534
2535 def test_basic_protocol(self):
2536 @runtime_checkable
2537 class P(Protocol):
2538 def meth(self):
2539 pass
2540 class C: pass
2541 class D:
2542 def meth(self):
2543 pass
2544 def f():
2545 pass
2546 self.assertIsSubclass(D, P)
2547 self.assertIsInstance(D(), P)
2548 self.assertNotIsSubclass(C, P)
2549 self.assertNotIsInstance(C(), P)
2550 self.assertNotIsSubclass(types.FunctionType, P)
2551 self.assertNotIsInstance(f, P)
2552
2553 def test_everything_implements_empty_protocol(self):
2554 @runtime_checkable
2555 class Empty(Protocol): pass
2556 class C: pass
2557 def f():
2558 pass
2559 for thing in (object, type, tuple, C, types.FunctionType):
2560 self.assertIsSubclass(thing, Empty)
2561 for thing in (object(), 1, (), typing, f):
2562 self.assertIsInstance(thing, Empty)
2563
2564 def test_function_implements_protocol(self):
2565 def f():
2566 pass
2567 self.assertIsInstance(f, HasCallProtocol)
2568
2569 def test_no_inheritance_from_nominal(self):
2570 class C: pass
2571 class BP(Protocol): pass
2572 with self.assertRaises(TypeError):
2573 class P(C, Protocol):
2574 pass
2575 with self.assertRaises(TypeError):
2576 class Q(Protocol, C):
2577 pass
2578 with self.assertRaises(TypeError):
2579 class R(BP, C, Protocol):
2580 pass
2581 class D(BP, C): pass
2582 class E(C, BP): pass
2583 self.assertNotIsInstance(D(), E)
2584 self.assertNotIsInstance(E(), D)
2585
2586 def test_runtimecheckable_on_typing_dot_Protocol(self):
2587 @runtime_checkable
2588 class Foo(typing.Protocol):
2589 x: int
2590
2591 class Bar:
2592 def __init__(self):
2593 self.x = 42
2594
2595 self.assertIsInstance(Bar(), Foo)
2596 self.assertNotIsInstance(object(), Foo)
2597
2598 def test_typing_dot_runtimecheckable_on_Protocol(self):
2599 @typing.runtime_checkable
2600 class Foo(Protocol):
2601 x: int
2602
2603 class Bar:
2604 def __init__(self):
2605 self.x = 42
2606
2607 self.assertIsInstance(Bar(), Foo)
2608 self.assertNotIsInstance(object(), Foo)
2609
2610 def test_typing_Protocol_and_extensions_Protocol_can_mix(self):
2611 class TypingProto(typing.Protocol):
2612 x: int
2613
2614 class ExtensionsProto(Protocol):
2615 y: int
2616
2617 class SubProto(TypingProto, ExtensionsProto, typing.Protocol):
2618 z: int
2619
2620 class SubProto2(TypingProto, ExtensionsProto, Protocol):
2621 z: int
2622
2623 class SubProto3(ExtensionsProto, TypingProto, typing.Protocol):
2624 z: int
2625
2626 class SubProto4(ExtensionsProto, TypingProto, Protocol):
2627 z: int
2628
2629 for proto in (
2630 ExtensionsProto, SubProto, SubProto2, SubProto3, SubProto4
2631 ):
2632 with self.subTest(proto=proto.__name__):
2633 self.assertTrue(is_protocol(proto))
2634 if Protocol is not typing.Protocol:
2635 self.assertIsInstance(proto, typing_extensions._ProtocolMeta)
2636 self.assertIsInstance(proto.__protocol_attrs__, set)
2637 with self.assertRaisesRegex(
2638 TypeError, "Protocols cannot be instantiated"
2639 ):
2640 proto()
2641 # check these don't raise
2642 runtime_checkable(proto)
2643 typing.runtime_checkable(proto)
2644
2645 class Concrete(SubProto): pass
2646 class Concrete2(SubProto2): pass
2647 class Concrete3(SubProto3): pass
2648 class Concrete4(SubProto4): pass
2649
2650 for cls in Concrete, Concrete2, Concrete3, Concrete4:
2651 with self.subTest(cls=cls.__name__):
2652 self.assertFalse(is_protocol(cls))
2653 # Check that this doesn't raise:
2654 self.assertIsInstance(cls(), cls)
2655 with self.assertRaises(TypeError):
2656 runtime_checkable(cls)
2657 with self.assertRaises(TypeError):
2658 typing.runtime_checkable(cls)
2659
2660 def test_no_instantiation(self):
2661 class P(Protocol): pass
2662 with self.assertRaises(TypeError):
2663 P()
2664 class C(P): pass
2665 self.assertIsInstance(C(), C)
2666 T = TypeVar('T')
2667 class PG(Protocol[T]): pass
2668 with self.assertRaises(TypeError):
2669 PG()
2670 with self.assertRaises(TypeError):
2671 PG[int]()
2672 with self.assertRaises(TypeError):
2673 PG[T]()
2674 class CG(PG[T]): pass
2675 self.assertIsInstance(CG[int](), CG)
2676
2677 def test_protocol_defining_init_does_not_get_overridden(self):
2678 # check that P.__init__ doesn't get clobbered
2679 # see https://bugs.python.org/issue44807
2680
2681 class P(Protocol):
2682 x: int
2683 def __init__(self, x: int) -> None:
2684 self.x = x
2685 class C: pass
2686
2687 c = C()
2688 P.__init__(c, 1)
2689 self.assertEqual(c.x, 1)
2690
2691 def test_concrete_class_inheriting_init_from_protocol(self):
2692 class P(Protocol):
2693 x: int
2694 def __init__(self, x: int) -> None:
2695 self.x = x
2696
2697 class C(P): pass
2698
2699 c = C(1)
2700 self.assertIsInstance(c, C)
2701 self.assertEqual(c.x, 1)
2702
2703 def test_cannot_instantiate_abstract(self):
2704 @runtime_checkable
2705 class P(Protocol):
2706 @abc.abstractmethod
2707 def ameth(self) -> int:
2708 raise NotImplementedError
2709 class B(P):
2710 pass
2711 class C(B):
2712 def ameth(self) -> int:
2713 return 26 # pragma: no cover
2714 with self.assertRaises(TypeError):
2715 B()
2716 self.assertIsInstance(C(), P)
2717
2718 def test_subprotocols_extending(self):
2719 class P1(Protocol):
2720 def meth1(self):
2721 pass
2722 @runtime_checkable
2723 class P2(P1, Protocol):
2724 def meth2(self):
2725 pass
2726 class C:
2727 def meth1(self):
2728 pass
2729 def meth2(self):
2730 pass
2731 class C1:
2732 def meth1(self):
2733 pass
2734 class C2:
2735 def meth2(self):
2736 pass
2737 self.assertNotIsInstance(C1(), P2)
2738 self.assertNotIsInstance(C2(), P2)
2739 self.assertNotIsSubclass(C1, P2)
2740 self.assertNotIsSubclass(C2, P2)
2741 self.assertIsInstance(C(), P2)
2742 self.assertIsSubclass(C, P2)
2743
2744 def test_subprotocols_merging(self):
2745 class P1(Protocol):
2746 def meth1(self):
2747 pass
2748 class P2(Protocol):
2749 def meth2(self):
2750 pass
2751 @runtime_checkable
2752 class P(P1, P2, Protocol):
2753 pass
2754 class C:
2755 def meth1(self):
2756 pass
2757 def meth2(self):
2758 pass
2759 class C1:
2760 def meth1(self):
2761 pass
2762 class C2:
2763 def meth2(self):
2764 pass
2765 self.assertNotIsInstance(C1(), P)
2766 self.assertNotIsInstance(C2(), P)
2767 self.assertNotIsSubclass(C1, P)
2768 self.assertNotIsSubclass(C2, P)
2769 self.assertIsInstance(C(), P)
2770 self.assertIsSubclass(C, P)
2771
2772 def test_protocols_issubclass(self):
2773 T = TypeVar('T')
2774 @runtime_checkable
2775 class P(Protocol):
2776 def x(self): ...
2777 @runtime_checkable
2778 class PG(Protocol[T]):
2779 def x(self): ...
2780 class BadP(Protocol):
2781 def x(self): ...
2782 class BadPG(Protocol[T]):
2783 def x(self): ...
2784 class C:
2785 def x(self): ...
2786 self.assertIsSubclass(C, P)
2787 self.assertIsSubclass(C, PG)
2788 self.assertIsSubclass(BadP, PG)
2789
2790 no_subscripted_generics = (
2791 "Subscripted generics cannot be used with class and instance checks"
2792 )
2793
2794 with self.assertRaisesRegex(TypeError, no_subscripted_generics):
2795 issubclass(C, PG[T])
2796 with self.assertRaisesRegex(TypeError, no_subscripted_generics):
2797 issubclass(C, PG[C])
2798
2799 only_runtime_checkable_protocols = (
2800 "Instance and class checks can only be used with "
2801 "@runtime_checkable protocols"
2802 )
2803
2804 with self.assertRaisesRegex(TypeError, only_runtime_checkable_protocols):
2805 issubclass(C, BadP)
2806 with self.assertRaisesRegex(TypeError, only_runtime_checkable_protocols):
2807 issubclass(C, BadPG)
2808
2809 with self.assertRaisesRegex(TypeError, no_subscripted_generics):
2810 issubclass(P, PG[T])
2811 with self.assertRaisesRegex(TypeError, no_subscripted_generics):
2812 issubclass(PG, PG[int])
2813
2814 only_classes_allowed = r"issubclass\(\) arg 1 must be a class"
2815
2816 with self.assertRaisesRegex(TypeError, only_classes_allowed):
2817 issubclass(1, P)
2818 with self.assertRaisesRegex(TypeError, only_classes_allowed):
2819 issubclass(1, PG)
2820 with self.assertRaisesRegex(TypeError, only_classes_allowed):
2821 issubclass(1, BadP)
2822 with self.assertRaisesRegex(TypeError, only_classes_allowed):
2823 issubclass(1, BadPG)
2824
2825 def test_implicit_issubclass_between_two_protocols(self):
2826 @runtime_checkable
2827 class CallableMembersProto(Protocol):
2828 def meth(self): ...
2829
2830 # All the below protocols should be considered "subclasses"
2831 # of CallableMembersProto at runtime,
2832 # even though none of them explicitly subclass CallableMembersProto
2833
2834 class IdenticalProto(Protocol):
2835 def meth(self): ...
2836
2837 class SupersetProto(Protocol):
2838 def meth(self): ...
2839 def meth2(self): ...
2840
2841 class NonCallableMembersProto(Protocol):
2842 meth: Callable[[], None]
2843
2844 class NonCallableMembersSupersetProto(Protocol):
2845 meth: Callable[[], None]
2846 meth2: Callable[[str, int], bool]
2847
2848 class MixedMembersProto1(Protocol):
2849 meth: Callable[[], None]
2850 def meth2(self): ...
2851
2852 class MixedMembersProto2(Protocol):
2853 def meth(self): ...
2854 meth2: Callable[[str, int], bool]
2855
2856 for proto in (
2857 IdenticalProto, SupersetProto, NonCallableMembersProto,
2858 NonCallableMembersSupersetProto, MixedMembersProto1, MixedMembersProto2
2859 ):
2860 with self.subTest(proto=proto.__name__):
2861 self.assertIsSubclass(proto, CallableMembersProto)
2862
2863 # These two shouldn't be considered subclasses of CallableMembersProto, however,
2864 # since they don't have the `meth` protocol member
2865
2866 class EmptyProtocol(Protocol): ...
2867 class UnrelatedProtocol(Protocol):
2868 def wut(self): ...
2869
2870 self.assertNotIsSubclass(EmptyProtocol, CallableMembersProto)
2871 self.assertNotIsSubclass(UnrelatedProtocol, CallableMembersProto)
2872
2873 # These aren't protocols at all (despite having annotations),
2874 # so they should only be considered subclasses of CallableMembersProto
2875 # if they *actually have an attribute* matching the `meth` member
2876 # (just having an annotation is insufficient)
2877
2878 class AnnotatedButNotAProtocol:
2879 meth: Callable[[], None]
2880
2881 class NotAProtocolButAnImplicitSubclass:
2882 def meth(self): pass
2883
2884 class NotAProtocolButAnImplicitSubclass2:
2885 meth: Callable[[], None]
2886 def meth(self): pass
2887
2888 class NotAProtocolButAnImplicitSubclass3:
2889 meth: Callable[[], None]
2890 meth2: Callable[[int, str], bool]
2891 def meth(self): pass
2892 def meth2(self, x, y): return True
2893
2894 self.assertNotIsSubclass(AnnotatedButNotAProtocol, CallableMembersProto)
2895 self.assertIsSubclass(NotAProtocolButAnImplicitSubclass, CallableMembersProto)
2896 self.assertIsSubclass(NotAProtocolButAnImplicitSubclass2, CallableMembersProto)
2897 self.assertIsSubclass(NotAProtocolButAnImplicitSubclass3, CallableMembersProto)
2898
2899 @skip_if_py312b1
2900 def test_issubclass_and_isinstance_on_Protocol_itself(self):
2901 class C:
2902 def x(self): pass
2903
2904 self.assertNotIsSubclass(object, Protocol)
2905 self.assertNotIsInstance(object(), Protocol)
2906
2907 self.assertNotIsSubclass(str, Protocol)
2908 self.assertNotIsInstance('foo', Protocol)
2909
2910 self.assertNotIsSubclass(C, Protocol)
2911 self.assertNotIsInstance(C(), Protocol)
2912
2913 only_classes_allowed = r"issubclass\(\) arg 1 must be a class"
2914
2915 with self.assertRaisesRegex(TypeError, only_classes_allowed):
2916 issubclass(1, Protocol)
2917 with self.assertRaisesRegex(TypeError, only_classes_allowed):
2918 issubclass('foo', Protocol)
2919 with self.assertRaisesRegex(TypeError, only_classes_allowed):
2920 issubclass(C(), Protocol)
2921
2922 T = TypeVar('T')
2923
2924 @runtime_checkable
2925 class EmptyProtocol(Protocol): pass
2926
2927 @runtime_checkable
2928 class SupportsStartsWith(Protocol):
2929 def startswith(self, x: str) -> bool: ...
2930
2931 @runtime_checkable
2932 class SupportsX(Protocol[T]):
2933 def x(self): ...
2934
2935 for proto in EmptyProtocol, SupportsStartsWith, SupportsX:
2936 with self.subTest(proto=proto.__name__):
2937 self.assertIsSubclass(proto, Protocol)
2938
2939 # gh-105237 / PR #105239:
2940 # check that the presence of Protocol subclasses
2941 # where `issubclass(X, <subclass>)` evaluates to True
2942 # doesn't influence the result of `issubclass(X, Protocol)`
2943
2944 self.assertIsSubclass(object, EmptyProtocol)
2945 self.assertIsInstance(object(), EmptyProtocol)
2946 self.assertNotIsSubclass(object, Protocol)
2947 self.assertNotIsInstance(object(), Protocol)
2948
2949 self.assertIsSubclass(str, SupportsStartsWith)
2950 self.assertIsInstance('foo', SupportsStartsWith)
2951 self.assertNotIsSubclass(str, Protocol)
2952 self.assertNotIsInstance('foo', Protocol)
2953
2954 self.assertIsSubclass(C, SupportsX)
2955 self.assertIsInstance(C(), SupportsX)
2956 self.assertNotIsSubclass(C, Protocol)
2957 self.assertNotIsInstance(C(), Protocol)
2958
2959 @skip_if_py312b1
2960 def test_isinstance_checks_not_at_whim_of_gc(self):
2961 self.addCleanup(gc.enable)
2962 gc.disable()
2963
2964 with self.assertRaisesRegex(
2965 TypeError,
2966 "Protocols can only inherit from other protocols"
2967 ):
2968 class Foo(collections.abc.Mapping, Protocol):
2969 pass
2970
2971 self.assertNotIsInstance([], collections.abc.Mapping)
2972
2973 def test_protocols_issubclass_non_callable(self):
2974 class C:
2975 x = 1
2976
2977 @runtime_checkable
2978 class PNonCall(Protocol):
2979 x = 1
2980
2981 non_callable_members_illegal = (
2982 "Protocols with non-method members don't support issubclass()"
2983 )
2984
2985 with self.assertRaisesRegex(TypeError, non_callable_members_illegal):
2986 issubclass(C, PNonCall)
2987
2988 self.assertIsInstance(C(), PNonCall)
2989 PNonCall.register(C)
2990
2991 with self.assertRaisesRegex(TypeError, non_callable_members_illegal):
2992 issubclass(C, PNonCall)
2993
2994 self.assertIsInstance(C(), PNonCall)
2995
2996 # check that non-protocol subclasses are not affected
2997 class D(PNonCall): ...
2998
2999 self.assertNotIsSubclass(C, D)
3000 self.assertNotIsInstance(C(), D)
3001 D.register(C)
3002 self.assertIsSubclass(C, D)
3003 self.assertIsInstance(C(), D)
3004
3005 with self.assertRaisesRegex(TypeError, non_callable_members_illegal):
3006 issubclass(D, PNonCall)
3007
3008 def test_no_weird_caching_with_issubclass_after_isinstance(self):
3009 @runtime_checkable
3010 class Spam(Protocol):
3011 x: int
3012
3013 class Eggs:
3014 def __init__(self) -> None:
3015 self.x = 42
3016
3017 self.assertIsInstance(Eggs(), Spam)
3018
3019 # gh-104555: If we didn't override ABCMeta.__subclasscheck__ in _ProtocolMeta,
3020 # TypeError wouldn't be raised here,
3021 # as the cached result of the isinstance() check immediately above
3022 # would mean the issubclass() call would short-circuit
3023 # before we got to the "raise TypeError" line
3024 with self.assertRaisesRegex(
3025 TypeError,
3026 "Protocols with non-method members don't support issubclass()"
3027 ):
3028 issubclass(Eggs, Spam)
3029
3030 def test_no_weird_caching_with_issubclass_after_isinstance_2(self):
3031 @runtime_checkable
3032 class Spam(Protocol):
3033 x: int
3034
3035 class Eggs: ...
3036
3037 self.assertNotIsInstance(Eggs(), Spam)
3038
3039 # gh-104555: If we didn't override ABCMeta.__subclasscheck__ in _ProtocolMeta,
3040 # TypeError wouldn't be raised here,
3041 # as the cached result of the isinstance() check immediately above
3042 # would mean the issubclass() call would short-circuit
3043 # before we got to the "raise TypeError" line
3044 with self.assertRaisesRegex(
3045 TypeError,
3046 "Protocols with non-method members don't support issubclass()"
3047 ):
3048 issubclass(Eggs, Spam)
3049
3050 def test_no_weird_caching_with_issubclass_after_isinstance_3(self):
3051 @runtime_checkable
3052 class Spam(Protocol):
3053 x: int
3054
3055 class Eggs:
3056 def __getattr__(self, attr):
3057 if attr == "x":
3058 return 42
3059 raise AttributeError(attr)
3060
3061 self.assertNotIsInstance(Eggs(), Spam)
3062
3063 # gh-104555: If we didn't override ABCMeta.__subclasscheck__ in _ProtocolMeta,
3064 # TypeError wouldn't be raised here,
3065 # as the cached result of the isinstance() check immediately above
3066 # would mean the issubclass() call would short-circuit
3067 # before we got to the "raise TypeError" line
3068 with self.assertRaisesRegex(
3069 TypeError,
3070 "Protocols with non-method members don't support issubclass()"
3071 ):
3072 issubclass(Eggs, Spam)
3073
3074 def test_protocols_isinstance(self):
3075 T = TypeVar('T')
3076 @runtime_checkable
3077 class P(Protocol):
3078 def meth(x): ...
3079 @runtime_checkable
3080 class PG(Protocol[T]):
3081 def meth(x): ...
3082 @runtime_checkable
3083 class WeirdProto(Protocol):
3084 meth = str.maketrans
3085 @runtime_checkable
3086 class WeirdProto2(Protocol):
3087 meth = lambda *args, **kwargs: None # noqa: E731
3088 class CustomCallable:
3089 def __call__(self, *args, **kwargs):
3090 pass
3091 @runtime_checkable
3092 class WeirderProto(Protocol):
3093 meth = CustomCallable()
3094 class BadP(Protocol):
3095 def meth(x): ...
3096 class BadPG(Protocol[T]):
3097 def meth(x): ...
3098 class C:
3099 def meth(x): ...
3100 class C2:
3101 def __init__(self):
3102 self.meth = lambda: None
3103 for klass in C, C2:
3104 for proto in P, PG, WeirdProto, WeirdProto2, WeirderProto:
3105 with self.subTest(klass=klass.__name__, proto=proto.__name__):
3106 self.assertIsInstance(klass(), proto)
3107
3108 no_subscripted_generics = (
3109 "Subscripted generics cannot be used with class and instance checks"
3110 )
3111
3112 with self.assertRaisesRegex(TypeError, no_subscripted_generics):
3113 isinstance(C(), PG[T])
3114 with self.assertRaisesRegex(TypeError, no_subscripted_generics):
3115 isinstance(C(), PG[C])
3116
3117 only_runtime_checkable_msg = (
3118 "Instance and class checks can only be used "
3119 "with @runtime_checkable protocols"
3120 )
3121
3122 with self.assertRaisesRegex(TypeError, only_runtime_checkable_msg):
3123 isinstance(C(), BadP)
3124 with self.assertRaisesRegex(TypeError, only_runtime_checkable_msg):
3125 isinstance(C(), BadPG)
3126
3127 def test_protocols_isinstance_properties_and_descriptors(self):
3128 class C:
3129 @property
3130 def attr(self):
3131 return 42 # pragma: no cover
3132
3133 class CustomDescriptor:
3134 def __get__(self, obj, objtype=None):
3135 return 42 # pragma: no cover
3136
3137 class D:
3138 attr = CustomDescriptor()
3139
3140 # Check that properties set on superclasses
3141 # are still found by the isinstance() logic
3142 class E(C): ...
3143 class F(D): ...
3144
3145 class Empty: ...
3146
3147 T = TypeVar('T')
3148
3149 @runtime_checkable
3150 class P(Protocol):
3151 @property
3152 def attr(self): ...
3153
3154 @runtime_checkable
3155 class P1(Protocol):
3156 attr: int
3157
3158 @runtime_checkable
3159 class PG(Protocol[T]):
3160 @property
3161 def attr(self): ...
3162
3163 @runtime_checkable
3164 class PG1(Protocol[T]):
3165 attr: T
3166
3167 @runtime_checkable
3168 class MethodP(Protocol):
3169 def attr(self): ...
3170
3171 @runtime_checkable
3172 class MethodPG(Protocol[T]):
3173 def attr(self) -> T: ...
3174
3175 for protocol_class in P, P1, PG, PG1, MethodP, MethodPG:
3176 for klass in C, D, E, F:
3177 with self.subTest(
3178 klass=klass.__name__,
3179 protocol_class=protocol_class.__name__
3180 ):
3181 self.assertIsInstance(klass(), protocol_class)
3182
3183 with self.subTest(klass="Empty", protocol_class=protocol_class.__name__):
3184 self.assertNotIsInstance(Empty(), protocol_class)
3185
3186 class BadP(Protocol):
3187 @property
3188 def attr(self): ...
3189
3190 class BadP1(Protocol):
3191 attr: int
3192
3193 class BadPG(Protocol[T]):
3194 @property
3195 def attr(self): ...
3196
3197 class BadPG1(Protocol[T]):
3198 attr: T
3199
3200 cases = (
3201 PG[T], PG[C], PG1[T], PG1[C], MethodPG[T],
3202 MethodPG[C], BadP, BadP1, BadPG, BadPG1
3203 )
3204
3205 for obj in cases:
3206 for klass in C, D, E, F, Empty:
3207 with self.subTest(klass=klass.__name__, obj=obj):
3208 with self.assertRaises(TypeError):
3209 isinstance(klass(), obj)
3210
3211 def test_protocols_isinstance_not_fooled_by_custom_dir(self):
3212 @runtime_checkable
3213 class HasX(Protocol):
3214 x: int
3215
3216 class CustomDirWithX:
3217 x = 10
3218 def __dir__(self):
3219 return [] # pragma: no cover
3220
3221 class CustomDirWithoutX:
3222 def __dir__(self):
3223 return ["x"] # pragma: no cover
3224
3225 self.assertIsInstance(CustomDirWithX(), HasX)
3226 self.assertNotIsInstance(CustomDirWithoutX(), HasX)
3227
3228 def test_protocols_isinstance_attribute_access_with_side_effects(self):
3229 class C:
3230 @property
3231 def attr(self):
3232 raise AttributeError('no') # pragma: no cover
3233
3234 class CustomDescriptor:
3235 def __get__(self, obj, objtype=None):
3236 raise RuntimeError("NO") # pragma: no cover
3237
3238 class D:
3239 attr = CustomDescriptor()
3240
3241 # Check that properties set on superclasses
3242 # are still found by the isinstance() logic
3243 class E(C): ...
3244 class F(D): ...
3245
3246 class WhyWouldYouDoThis:
3247 def __getattr__(self, name):
3248 raise RuntimeError("wut") # pragma: no cover
3249
3250 T = TypeVar('T')
3251
3252 @runtime_checkable
3253 class P(Protocol):
3254 @property
3255 def attr(self): ...
3256
3257 @runtime_checkable
3258 class P1(Protocol):
3259 attr: int
3260
3261 @runtime_checkable
3262 class PG(Protocol[T]):
3263 @property
3264 def attr(self): ...
3265
3266 @runtime_checkable
3267 class PG1(Protocol[T]):
3268 attr: T
3269
3270 @runtime_checkable
3271 class MethodP(Protocol):
3272 def attr(self): ...
3273
3274 @runtime_checkable
3275 class MethodPG(Protocol[T]):
3276 def attr(self) -> T: ...
3277
3278 for protocol_class in P, P1, PG, PG1, MethodP, MethodPG:
3279 for klass in C, D, E, F:
3280 with self.subTest(
3281 klass=klass.__name__,
3282 protocol_class=protocol_class.__name__
3283 ):
3284 self.assertIsInstance(klass(), protocol_class)
3285
3286 with self.subTest(
3287 klass="WhyWouldYouDoThis",
3288 protocol_class=protocol_class.__name__
3289 ):
3290 self.assertNotIsInstance(WhyWouldYouDoThis(), protocol_class)
3291
3292 def test_protocols_isinstance___slots__(self):
3293 # As per the consensus in https://github.com/python/typing/issues/1367,
3294 # this is desirable behaviour
3295 @runtime_checkable
3296 class HasX(Protocol):
3297 x: int
3298
3299 class HasNothingButSlots:
3300 __slots__ = ("x",)
3301
3302 self.assertIsInstance(HasNothingButSlots(), HasX)
3303
3304 def test_protocols_isinstance_py36(self):
3305 class APoint:
3306 def __init__(self, x, y, label):
3307 self.x = x
3308 self.y = y
3309 self.label = label
3310 class BPoint:
3311 label = 'B'
3312 def __init__(self, x, y):
3313 self.x = x
3314 self.y = y
3315 class C:
3316 def __init__(self, attr):
3317 self.attr = attr
3318 def meth(self, arg):
3319 return 0 # pragma: no cover
3320 class Bad: pass
3321 self.assertIsInstance(APoint(1, 2, 'A'), Point)
3322 self.assertIsInstance(BPoint(1, 2), Point)
3323 self.assertNotIsInstance(MyPoint(), Point)
3324 self.assertIsInstance(BPoint(1, 2), Position)
3325 self.assertIsInstance(Other(), Proto)
3326 self.assertIsInstance(Concrete(), Proto)
3327 self.assertIsInstance(C(42), Proto)
3328 self.assertNotIsInstance(Bad(), Proto)
3329 self.assertNotIsInstance(Bad(), Point)
3330 self.assertNotIsInstance(Bad(), Position)
3331 self.assertNotIsInstance(Bad(), Concrete)
3332 self.assertNotIsInstance(Other(), Concrete)
3333 self.assertIsInstance(NT(1, 2), Position)
3334
3335 def test_runtime_checkable_with_match_args(self):
3336 @runtime_checkable
3337 class P_regular(Protocol):
3338 x: int
3339 y: int
3340
3341 @runtime_checkable
3342 class P_match(Protocol):
3343 __match_args__ = ("x", "y")
3344 x: int
3345 y: int
3346
3347 class Regular:
3348 def __init__(self, x: int, y: int):
3349 self.x = x
3350 self.y = y
3351
3352 class WithMatch:
3353 __match_args__ = ("x", "y", "z")
3354 def __init__(self, x: int, y: int, z: int):
3355 self.x = x
3356 self.y = y
3357 self.z = z
3358
3359 class Nope: ...
3360
3361 self.assertIsInstance(Regular(1, 2), P_regular)
3362 self.assertIsInstance(Regular(1, 2), P_match)
3363 self.assertIsInstance(WithMatch(1, 2, 3), P_regular)
3364 self.assertIsInstance(WithMatch(1, 2, 3), P_match)
3365 self.assertNotIsInstance(Nope(), P_regular)
3366 self.assertNotIsInstance(Nope(), P_match)
3367
3368 def test_protocols_isinstance_init(self):
3369 T = TypeVar('T')
3370 @runtime_checkable
3371 class P(Protocol):
3372 x = 1
3373 @runtime_checkable
3374 class PG(Protocol[T]):
3375 x = 1
3376 class C:
3377 def __init__(self, x):
3378 self.x = x
3379 self.assertIsInstance(C(1), P)
3380 self.assertIsInstance(C(1), PG)
3381
3382 def test_protocols_isinstance_monkeypatching(self):
3383 @runtime_checkable
3384 class HasX(Protocol):
3385 x: int
3386
3387 class Foo: ...
3388
3389 f = Foo()
3390 self.assertNotIsInstance(f, HasX)
3391 f.x = 42
3392 self.assertIsInstance(f, HasX)
3393 del f.x
3394 self.assertNotIsInstance(f, HasX)
3395
3396 @skip_if_py312b1
3397 def test_runtime_checkable_generic_non_protocol(self):
3398 # Make sure this doesn't raise AttributeError
3399 with self.assertRaisesRegex(
3400 TypeError,
3401 "@runtime_checkable can be only applied to protocol classes",
3402 ):
3403 @runtime_checkable
3404 class Foo(Generic[T]): ...
3405
3406 def test_runtime_checkable_generic(self):
3407 @runtime_checkable
3408 class Foo(Protocol[T]):
3409 def meth(self) -> T: ...
3410
3411 class Impl:
3412 def meth(self) -> int: ...
3413
3414 self.assertIsSubclass(Impl, Foo)
3415
3416 class NotImpl:
3417 def method(self) -> int: ...
3418
3419 self.assertNotIsSubclass(NotImpl, Foo)
3420
3421 if sys.version_info >= (3, 12):
3422 exec(textwrap.dedent(
3423 """
3424 @skip_if_py312b1
3425 def test_pep695_generics_can_be_runtime_checkable(self):
3426 @runtime_checkable
3427 class HasX(Protocol):
3428 x: int
3429
3430 class Bar[T]:
3431 x: T
3432 def __init__(self, x):
3433 self.x = x
3434
3435 class Capybara[T]:
3436 y: str
3437 def __init__(self, y):
3438 self.y = y
3439
3440 self.assertIsInstance(Bar(1), HasX)
3441 self.assertNotIsInstance(Capybara('a'), HasX)
3442 """
3443 ))
3444
3445 @skip_if_py312b1
3446 def test_protocols_isinstance_generic_classes(self):
3447 T = TypeVar("T")
3448
3449 class Foo(Generic[T]):
3450 x: T
3451
3452 def __init__(self, x):
3453 self.x = x
3454
3455 class Bar(Foo[int]):
3456 ...
3457
3458 @runtime_checkable
3459 class HasX(Protocol):
3460 x: int
3461
3462 foo = Foo(1)
3463 self.assertIsInstance(foo, HasX)
3464
3465 bar = Bar(2)
3466 self.assertIsInstance(bar, HasX)
3467
3468 def test_protocols_support_register(self):
3469 @runtime_checkable
3470 class P(Protocol):
3471 x = 1
3472 class PM(Protocol):
3473 def meth(self): pass
3474 class D(PM): pass
3475 class C: pass
3476 D.register(C)
3477 P.register(C)
3478 self.assertIsInstance(C(), P)
3479 self.assertIsInstance(C(), D)
3480
3481 def test_none_on_non_callable_doesnt_block_implementation(self):
3482 @runtime_checkable
3483 class P(Protocol):
3484 x = 1
3485 class A:
3486 x = 1
3487 class B(A):
3488 x = None
3489 class C:
3490 def __init__(self):
3491 self.x = None
3492 self.assertIsInstance(B(), P)
3493 self.assertIsInstance(C(), P)
3494
3495 def test_none_on_callable_blocks_implementation(self):
3496 @runtime_checkable
3497 class P(Protocol):
3498 def x(self): ...
3499 class A:
3500 def x(self): ...
3501 class B(A):
3502 x = None
3503 class C:
3504 def __init__(self):
3505 self.x = None
3506 self.assertNotIsInstance(B(), P)
3507 self.assertNotIsInstance(C(), P)
3508
3509 def test_non_protocol_subclasses(self):
3510 class P(Protocol):
3511 x = 1
3512 @runtime_checkable
3513 class PR(Protocol):
3514 def meth(self): pass
3515 class NonP(P):
3516 x = 1
3517 class NonPR(PR): pass
3518 class C(metaclass=abc.ABCMeta):
3519 x = 1
3520 class D(metaclass=abc.ABCMeta):
3521 def meth(self): pass # noqa: B027
3522 self.assertNotIsInstance(C(), NonP)
3523 self.assertNotIsInstance(D(), NonPR)
3524 self.assertNotIsSubclass(C, NonP)
3525 self.assertNotIsSubclass(D, NonPR)
3526 self.assertIsInstance(NonPR(), PR)
3527 self.assertIsSubclass(NonPR, PR)
3528
3529 self.assertNotIn("__protocol_attrs__", vars(NonP))
3530 self.assertNotIn("__protocol_attrs__", vars(NonPR))
3531 self.assertNotIn("__non_callable_proto_members__", vars(NonP))
3532 self.assertNotIn("__non_callable_proto_members__", vars(NonPR))
3533
3534 acceptable_extra_attrs = {
3535 '_is_protocol', '_is_runtime_protocol', '__parameters__',
3536 '__init__', '__annotations__', '__subclasshook__', '__annotate__'
3537 }
3538 self.assertLessEqual(vars(NonP).keys(), vars(C).keys() | acceptable_extra_attrs)
3539 self.assertLessEqual(
3540 vars(NonPR).keys(), vars(D).keys() | acceptable_extra_attrs
3541 )
3542
3543 def test_custom_subclasshook(self):
3544 class P(Protocol):
3545 x = 1
3546 class OKClass: pass
3547 class BadClass:
3548 x = 1
3549 class C(P):
3550 @classmethod
3551 def __subclasshook__(cls, other):
3552 return other.__name__.startswith("OK")
3553 self.assertIsInstance(OKClass(), C)
3554 self.assertNotIsInstance(BadClass(), C)
3555 self.assertIsSubclass(OKClass, C)
3556 self.assertNotIsSubclass(BadClass, C)
3557
3558 @skipIf(
3559 sys.version_info[:4] == (3, 12, 0, 'beta') and sys.version_info[4] < 4,
3560 "Early betas of Python 3.12 had a bug"
3561 )
3562 def test_custom_subclasshook_2(self):
3563 @runtime_checkable
3564 class HasX(Protocol):
3565 # The presence of a non-callable member
3566 # would mean issubclass() checks would fail with TypeError
3567 # if it weren't for the custom `__subclasshook__` method
3568 x = 1
3569
3570 @classmethod
3571 def __subclasshook__(cls, other):
3572 return hasattr(other, 'x')
3573
3574 class Empty: pass
3575
3576 class ImplementsHasX:
3577 x = 1
3578
3579 self.assertIsInstance(ImplementsHasX(), HasX)
3580 self.assertNotIsInstance(Empty(), HasX)
3581 self.assertIsSubclass(ImplementsHasX, HasX)
3582 self.assertNotIsSubclass(Empty, HasX)
3583
3584 # isinstance() and issubclass() checks against this still raise TypeError,
3585 # despite the presence of the custom __subclasshook__ method,
3586 # as it's not decorated with @runtime_checkable
3587 class NotRuntimeCheckable(Protocol):
3588 @classmethod
3589 def __subclasshook__(cls, other):
3590 return hasattr(other, 'x') # pragma: no cover
3591
3592 must_be_runtime_checkable = (
3593 "Instance and class checks can only be used "
3594 "with @runtime_checkable protocols"
3595 )
3596
3597 with self.assertRaisesRegex(TypeError, must_be_runtime_checkable):
3598 issubclass(object, NotRuntimeCheckable)
3599 with self.assertRaisesRegex(TypeError, must_be_runtime_checkable):
3600 isinstance(object(), NotRuntimeCheckable)
3601
3602 @skip_if_py312b1
3603 def test_issubclass_fails_correctly(self):
3604 @runtime_checkable
3605 class NonCallableMembers(Protocol):
3606 x = 1
3607
3608 class NotRuntimeCheckable(Protocol):
3609 def callable_member(self) -> int: ...
3610
3611 @runtime_checkable
3612 class RuntimeCheckable(Protocol):
3613 def callable_member(self) -> int: ...
3614
3615 class C: pass
3616
3617 # These three all exercise different code paths,
3618 # but should result in the same error message:
3619 for protocol in NonCallableMembers, NotRuntimeCheckable, RuntimeCheckable:
3620 with self.subTest(proto_name=protocol.__name__):
3621 with self.assertRaisesRegex(
3622 TypeError, r"issubclass\(\) arg 1 must be a class"
3623 ):
3624 issubclass(C(), protocol)
3625
3626 def test_defining_generic_protocols(self):
3627 T = TypeVar('T')
3628 S = TypeVar('S')
3629 @runtime_checkable
3630 class PR(Protocol[T, S]):
3631 def meth(self): pass
3632 class P(PR[int, T], Protocol[T]):
3633 y = 1
3634 with self.assertRaises(TypeError):
3635 issubclass(PR[int, T], PR)
3636 with self.assertRaises(TypeError):
3637 issubclass(P[str], PR)
3638 with self.assertRaises(TypeError):
3639 PR[int]
3640 with self.assertRaises(TypeError):
3641 P[int, str]
3642 if not TYPING_3_10_0:
3643 with self.assertRaises(TypeError):
3644 PR[int, 1]
3645 with self.assertRaises(TypeError):
3646 PR[int, ClassVar]
3647 class C(PR[int, T]): pass
3648 self.assertIsInstance(C[str](), C)
3649
3650 def test_defining_generic_protocols_old_style(self):
3651 T = TypeVar('T')
3652 S = TypeVar('S')
3653 @runtime_checkable
3654 class PR(Protocol, Generic[T, S]):
3655 def meth(self): pass
3656 class P(PR[int, str], Protocol):
3657 y = 1
3658 with self.assertRaises(TypeError):
3659 self.assertIsSubclass(PR[int, str], PR)
3660 self.assertIsSubclass(P, PR)
3661 with self.assertRaises(TypeError):
3662 PR[int]
3663 if not TYPING_3_10_0:
3664 with self.assertRaises(TypeError):
3665 PR[int, 1]
3666 class P1(Protocol, Generic[T]):
3667 def bar(self, x: T) -> str: ...
3668 class P2(Generic[T], Protocol):
3669 def bar(self, x: T) -> str: ...
3670 @runtime_checkable
3671 class PSub(P1[str], Protocol):
3672 x = 1
3673 class Test:
3674 x = 1
3675 def bar(self, x: str) -> str:
3676 return x # pragma: no cover
3677 self.assertIsInstance(Test(), PSub)
3678 if not TYPING_3_10_0:
3679 with self.assertRaises(TypeError):
3680 PR[int, ClassVar]
3681
3682 if hasattr(typing, "TypeAliasType"):
3683 exec(textwrap.dedent(
3684 """
3685 def test_pep695_generic_protocol_callable_members(self):
3686 @runtime_checkable
3687 class Foo[T](Protocol):
3688 def meth(self, x: T) -> None: ...
3689
3690 class Bar[T]:
3691 def meth(self, x: T) -> None: ...
3692
3693 self.assertIsInstance(Bar(), Foo)
3694 self.assertIsSubclass(Bar, Foo)
3695
3696 @runtime_checkable
3697 class SupportsTrunc[T](Protocol):
3698 def __trunc__(self) -> T: ...
3699
3700 self.assertIsInstance(0.0, SupportsTrunc)
3701 self.assertIsSubclass(float, SupportsTrunc)
3702
3703 def test_no_weird_caching_with_issubclass_after_isinstance_pep695(self):
3704 @runtime_checkable
3705 class Spam[T](Protocol):
3706 x: T
3707
3708 class Eggs[T]:
3709 def __init__(self, x: T) -> None:
3710 self.x = x
3711
3712 self.assertIsInstance(Eggs(42), Spam)
3713
3714 # gh-104555: If we didn't override ABCMeta.__subclasscheck__ in _ProtocolMeta,
3715 # TypeError wouldn't be raised here,
3716 # as the cached result of the isinstance() check immediately above
3717 # would mean the issubclass() call would short-circuit
3718 # before we got to the "raise TypeError" line
3719 with self.assertRaises(TypeError):
3720 issubclass(Eggs, Spam)
3721 """
3722 ))
3723
3724 def test_init_called(self):
3725 T = TypeVar('T')
3726 class P(Protocol[T]): pass
3727 class C(P[T]):
3728 def __init__(self):
3729 self.test = 'OK'
3730 self.assertEqual(C[int]().test, 'OK')
3731
3732 def test_protocols_bad_subscripts(self):
3733 T = TypeVar('T')
3734 S = TypeVar('S')
3735 with self.assertRaises(TypeError):
3736 class P(Protocol[T, T]): pass
3737 with self.assertRaises(TypeError):
3738 class P2(Protocol[int]): pass
3739 with self.assertRaises(TypeError):
3740 class P3(Protocol[T], Protocol[S]): pass
3741 with self.assertRaises(TypeError):
3742 class P4(typing.Mapping[T, S], Protocol[T]): pass
3743
3744 def test_generic_protocols_repr(self):
3745 T = TypeVar('T')
3746 S = TypeVar('S')
3747 class P(Protocol[T, S]): pass
3748 self.assertTrue(repr(P[T, S]).endswith('P[~T, ~S]'))
3749 self.assertTrue(repr(P[int, str]).endswith('P[int, str]'))
3750
3751 def test_generic_protocols_eq(self):
3752 T = TypeVar('T')
3753 S = TypeVar('S')
3754 class P(Protocol[T, S]): pass
3755 self.assertEqual(P, P)
3756 self.assertEqual(P[int, T], P[int, T])
3757 self.assertEqual(P[T, T][Tuple[T, S]][int, str],
3758 P[Tuple[int, str], Tuple[int, str]])
3759
3760 def test_generic_protocols_special_from_generic(self):
3761 T = TypeVar('T')
3762 class P(Protocol[T]): pass
3763 self.assertEqual(P.__parameters__, (T,))
3764 self.assertEqual(P[int].__parameters__, ())
3765 self.assertEqual(P[int].__args__, (int,))
3766 self.assertIs(P[int].__origin__, P)
3767
3768 def test_generic_protocols_special_from_protocol(self):
3769 @runtime_checkable
3770 class PR(Protocol):
3771 x = 1
3772 class P(Protocol):
3773 def meth(self):
3774 pass
3775 T = TypeVar('T')
3776 class PG(Protocol[T]):
3777 x = 1
3778 def meth(self):
3779 pass
3780 self.assertTrue(P._is_protocol)
3781 self.assertTrue(PR._is_protocol)
3782 self.assertTrue(PG._is_protocol)
3783 self.assertFalse(P._is_runtime_protocol)
3784 self.assertTrue(PR._is_runtime_protocol)
3785 self.assertTrue(PG[int]._is_protocol)
3786 self.assertEqual(typing_extensions._get_protocol_attrs(P), {'meth'})
3787 self.assertEqual(typing_extensions._get_protocol_attrs(PR), {'x'})
3788 self.assertEqual(frozenset(typing_extensions._get_protocol_attrs(PG)),
3789 frozenset({'x', 'meth'}))
3790
3791 def test_no_runtime_deco_on_nominal(self):
3792 with self.assertRaises(TypeError):
3793 @runtime_checkable
3794 class C: pass
3795 class Proto(Protocol):
3796 x = 1
3797 with self.assertRaises(TypeError):
3798 @runtime_checkable
3799 class Concrete(Proto):
3800 pass
3801
3802 def test_none_treated_correctly(self):
3803 @runtime_checkable
3804 class P(Protocol):
3805 x: int = None
3806 class B: pass
3807 self.assertNotIsInstance(B(), P)
3808 class C:
3809 x = 1
3810 class D:
3811 x = None
3812 self.assertIsInstance(C(), P)
3813 self.assertIsInstance(D(), P)
3814 class CI:
3815 def __init__(self):
3816 self.x = 1
3817 class DI:
3818 def __init__(self):
3819 self.x = None
3820 self.assertIsInstance(CI(), P)
3821 self.assertIsInstance(DI(), P)
3822
3823 def test_protocols_in_unions(self):
3824 class P(Protocol):
3825 x: int = None
3826 Alias = typing.Union[typing.Iterable, P]
3827 Alias2 = typing.Union[P, typing.Iterable]
3828 self.assertEqual(Alias, Alias2)
3829
3830 def test_protocols_pickleable(self):
3831 global P, CP # pickle wants to reference the class by name
3832 T = TypeVar('T')
3833
3834 @runtime_checkable
3835 class P(Protocol[T]):
3836 x = 1
3837 class CP(P[int]):
3838 pass
3839
3840 c = CP()
3841 c.foo = 42
3842 c.bar = 'abc'
3843 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
3844 z = pickle.dumps(c, proto)
3845 x = pickle.loads(z)
3846 self.assertEqual(x.foo, 42)
3847 self.assertEqual(x.bar, 'abc')
3848 self.assertEqual(x.x, 1)
3849 self.assertEqual(x.__dict__, {'foo': 42, 'bar': 'abc'})
3850 s = pickle.dumps(P)
3851 D = pickle.loads(s)
3852 class E:
3853 x = 1
3854 self.assertIsInstance(E(), D)
3855
3856 def test_collections_protocols_allowed(self):
3857 @runtime_checkable
3858 class Custom(collections.abc.Iterable, Protocol):
3859 def close(self): pass
3860
3861 class A: ...
3862 class B:
3863 def __iter__(self):
3864 return [] # pragma: no cover
3865 def close(self):
3866 return 0 # pragma: no cover
3867
3868 self.assertIsSubclass(B, Custom)
3869 self.assertNotIsSubclass(A, Custom)
3870
3871 @skipUnless(
3872 hasattr(collections.abc, "Buffer"),
3873 "needs collections.abc.Buffer to exist"
3874 )
3875 @skip_if_py312b1
3876 def test_collections_abc_buffer_protocol_allowed(self):
3877 @runtime_checkable
3878 class ReleasableBuffer(collections.abc.Buffer, Protocol):
3879 def __release_buffer__(self, mv: memoryview) -> None: ...
3880
3881 class C: pass
3882 class D:
3883 def __buffer__(self, flags: int) -> memoryview:
3884 return memoryview(b'') # pragma: no cover
3885 def __release_buffer__(self, mv: memoryview) -> None:
3886 pass
3887
3888 self.assertIsSubclass(D, ReleasableBuffer)
3889 self.assertIsInstance(D(), ReleasableBuffer)
3890 self.assertNotIsSubclass(C, ReleasableBuffer)
3891 self.assertNotIsInstance(C(), ReleasableBuffer)
3892
3893 def test_builtin_protocol_allowlist(self):
3894 with self.assertRaises(TypeError):
3895 class CustomProtocol(TestCase, Protocol):
3896 pass
3897
3898 class CustomPathLikeProtocol(os.PathLike, Protocol):
3899 pass
3900
3901 class CustomContextManager(typing.ContextManager, Protocol):
3902 pass
3903
3904 class CustomAsyncIterator(typing.AsyncIterator, Protocol):
3905 pass
3906
3907 @skip_if_py312b1
3908 def test_typing_extensions_protocol_allowlist(self):
3909 @runtime_checkable
3910 class ReleasableBuffer(Buffer, Protocol):
3911 def __release_buffer__(self, mv: memoryview) -> None: ...
3912
3913 class C: pass
3914 class D:
3915 def __buffer__(self, flags: int) -> memoryview:
3916 return memoryview(b'') # pragma: no cover
3917 def __release_buffer__(self, mv: memoryview) -> None:
3918 pass
3919
3920 self.assertIsSubclass(D, ReleasableBuffer)
3921 self.assertIsInstance(D(), ReleasableBuffer)
3922 self.assertNotIsSubclass(C, ReleasableBuffer)
3923 self.assertNotIsInstance(C(), ReleasableBuffer)
3924
3925 def test_non_runtime_protocol_isinstance_check(self):
3926 class P(Protocol):
3927 x: int
3928
3929 with self.assertRaisesRegex(TypeError, "@runtime_checkable"):
3930 isinstance(1, P)
3931
3932 def test_no_init_same_for_different_protocol_implementations(self):
3933 class CustomProtocolWithoutInitA(Protocol):
3934 pass
3935
3936 class CustomProtocolWithoutInitB(Protocol):
3937 pass
3938
3939 self.assertEqual(CustomProtocolWithoutInitA.__init__, CustomProtocolWithoutInitB.__init__)
3940
3941 def test_protocol_generic_over_paramspec(self):
3942 P = ParamSpec("P")
3943 T = TypeVar("T")
3944 T2 = TypeVar("T2")
3945
3946 class MemoizedFunc(Protocol[P, T, T2]):
3947 cache: typing.Dict[T2, T]
3948 def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T: ...
3949
3950 self.assertEqual(MemoizedFunc.__parameters__, (P, T, T2))
3951 self.assertTrue(MemoizedFunc._is_protocol)
3952
3953 with self.assertRaises(TypeError):
3954 MemoizedFunc[[int, str, str]]
3955
3956 if sys.version_info >= (3, 10):
3957 # These unfortunately don't pass on 3.9,
3958 # due to typing._type_check on older Python versions
3959 X = MemoizedFunc[[int, str, str], T, T2]
3960 self.assertEqual(X.__parameters__, (T, T2))
3961 self.assertEqual(X.__args__, ((int, str, str), T, T2))
3962
3963 Y = X[bytes, memoryview]
3964 self.assertEqual(Y.__parameters__, ())
3965 self.assertEqual(Y.__args__, ((int, str, str), bytes, memoryview))
3966
3967 # Regression test; fixing #126 might cause an error here
3968 with self.assertRaisesRegex(TypeError, "not a generic class"):
3969 Y[int]
3970
3971 def test_protocol_generic_over_typevartuple(self):
3972 Ts = TypeVarTuple("Ts")
3973 T = TypeVar("T")
3974 T2 = TypeVar("T2")
3975
3976 class MemoizedFunc(Protocol[Unpack[Ts], T, T2]):
3977 cache: typing.Dict[T2, T]
3978 def __call__(self, *args: Unpack[Ts]) -> T: ...
3979
3980 self.assertEqual(MemoizedFunc.__parameters__, (Ts, T, T2))
3981 self.assertTrue(MemoizedFunc._is_protocol)
3982
3983 things = "arguments" if sys.version_info >= (3, 10) else "parameters"
3984
3985 # A bug was fixed in 3.11.1
3986 # (https://github.com/python/cpython/commit/74920aa27d0c57443dd7f704d6272cca9c507ab3)
3987 # That means this assertion doesn't pass on 3.11.0,
3988 # but it passes on all other Python versions
3989 if sys.version_info[:3] != (3, 11, 0):
3990 with self.assertRaisesRegex(TypeError, f"Too few {things}"):
3991 MemoizedFunc[int]
3992
3993 X = MemoizedFunc[int, T, T2]
3994 self.assertEqual(X.__parameters__, (T, T2))
3995 self.assertEqual(X.__args__, (int, T, T2))
3996
3997 Y = X[bytes, memoryview]
3998 self.assertEqual(Y.__parameters__, ())
3999 self.assertEqual(Y.__args__, (int, bytes, memoryview))
4000
4001 def test_get_protocol_members(self):
4002 with self.assertRaisesRegex(TypeError, "not a Protocol"):
4003 get_protocol_members(object)
4004 with self.assertRaisesRegex(TypeError, "not a Protocol"):
4005 get_protocol_members(object())
4006 with self.assertRaisesRegex(TypeError, "not a Protocol"):
4007 get_protocol_members(Protocol)
4008 with self.assertRaisesRegex(TypeError, "not a Protocol"):
4009 get_protocol_members(Generic)
4010
4011 class P(Protocol):
4012 a: int
4013 def b(self) -> str: ...
4014 @property
4015 def c(self) -> int: ...
4016
4017 self.assertEqual(get_protocol_members(P), {'a', 'b', 'c'})
4018 self.assertIsInstance(get_protocol_members(P), frozenset)
4019 self.assertIsNot(get_protocol_members(P), P.__protocol_attrs__)
4020
4021 class Concrete:
4022 a: int
4023 def b(self) -> str: return "capybara"
4024 @property
4025 def c(self) -> int: return 5
4026
4027 with self.assertRaisesRegex(TypeError, "not a Protocol"):
4028 get_protocol_members(Concrete)
4029 with self.assertRaisesRegex(TypeError, "not a Protocol"):
4030 get_protocol_members(Concrete())
4031
4032 class ConcreteInherit(P):
4033 a: int = 42
4034 def b(self) -> str: return "capybara"
4035 @property
4036 def c(self) -> int: return 5
4037
4038 with self.assertRaisesRegex(TypeError, "not a Protocol"):
4039 get_protocol_members(ConcreteInherit)
4040 with self.assertRaisesRegex(TypeError, "not a Protocol"):
4041 get_protocol_members(ConcreteInherit())
4042
4043 def test_get_protocol_members_typing(self):
4044 with self.assertRaisesRegex(TypeError, "not a Protocol"):
4045 get_protocol_members(typing.Protocol)
4046
4047 class P(typing.Protocol):
4048 a: int
4049 def b(self) -> str: ...
4050 @property
4051 def c(self) -> int: ...
4052
4053 self.assertEqual(get_protocol_members(P), {'a', 'b', 'c'})
4054 self.assertIsInstance(get_protocol_members(P), frozenset)
4055 if hasattr(P, "__protocol_attrs__"):
4056 self.assertIsNot(get_protocol_members(P), P.__protocol_attrs__)
4057
4058 class Concrete:
4059 a: int
4060 def b(self) -> str: return "capybara"
4061 @property
4062 def c(self) -> int: return 5
4063
4064 with self.assertRaisesRegex(TypeError, "not a Protocol"):
4065 get_protocol_members(Concrete)
4066 with self.assertRaisesRegex(TypeError, "not a Protocol"):
4067 get_protocol_members(Concrete())
4068
4069 class ConcreteInherit(P):
4070 a: int = 42
4071 def b(self) -> str: return "capybara"
4072 @property
4073 def c(self) -> int: return 5
4074
4075 with self.assertRaisesRegex(TypeError, "not a Protocol"):
4076 get_protocol_members(ConcreteInherit)
4077 with self.assertRaisesRegex(TypeError, "not a Protocol"):
4078 get_protocol_members(ConcreteInherit())
4079
4080 def test_is_protocol(self):
4081 self.assertTrue(is_protocol(Proto))
4082 self.assertTrue(is_protocol(Point))
4083 self.assertFalse(is_protocol(Concrete))
4084 self.assertFalse(is_protocol(Concrete()))
4085 self.assertFalse(is_protocol(Generic))
4086 self.assertFalse(is_protocol(object))
4087
4088 # Protocol is not itself a protocol
4089 self.assertFalse(is_protocol(Protocol))
4090
4091 def test_is_protocol_with_typing(self):
4092 self.assertFalse(is_protocol(typing.Protocol))
4093
4094 class TypingProto(typing.Protocol):
4095 a: int
4096
4097 self.assertTrue(is_protocol(TypingProto))
4098
4099 class Concrete(TypingProto):
4100 a: int
4101
4102 self.assertFalse(is_protocol(Concrete))
4103
4104 @skip_if_py312b1
4105 def test_interaction_with_isinstance_checks_on_superclasses_with_ABCMeta(self):
4106 # Ensure the cache is empty, or this test won't work correctly
4107 collections.abc.Sized._abc_registry_clear()
4108
4109 class Foo(collections.abc.Sized, Protocol): pass
4110
4111 # CPython gh-105144: this previously raised TypeError
4112 # if a Protocol subclass of Sized had been created
4113 # before any isinstance() checks against Sized
4114 self.assertNotIsInstance(1, collections.abc.Sized)
4115
4116 @skip_if_py312b1
4117 def test_interaction_with_isinstance_checks_on_superclasses_with_ABCMeta_2(self):
4118 # Ensure the cache is empty, or this test won't work correctly
4119 collections.abc.Sized._abc_registry_clear()
4120
4121 class Foo(typing.Sized, Protocol): pass
4122
4123 # CPython gh-105144: this previously raised TypeError
4124 # if a Protocol subclass of Sized had been created
4125 # before any isinstance() checks against Sized
4126 self.assertNotIsInstance(1, typing.Sized)
4127
4128 def test_empty_protocol_decorated_with_final(self):
4129 @final
4130 @runtime_checkable
4131 class EmptyProtocol(Protocol): ...
4132
4133 self.assertIsSubclass(object, EmptyProtocol)
4134 self.assertIsInstance(object(), EmptyProtocol)
4135
4136 def test_protocol_decorated_with_final_callable_members(self):
4137 @final
4138 @runtime_checkable
4139 class ProtocolWithMethod(Protocol):
4140 def startswith(self, string: str) -> bool: ...
4141
4142 self.assertIsSubclass(str, ProtocolWithMethod)
4143 self.assertNotIsSubclass(int, ProtocolWithMethod)
4144 self.assertIsInstance('foo', ProtocolWithMethod)
4145 self.assertNotIsInstance(42, ProtocolWithMethod)
4146
4147 def test_protocol_decorated_with_final_noncallable_members(self):
4148 @final
4149 @runtime_checkable
4150 class ProtocolWithNonCallableMember(Protocol):
4151 x: int
4152
4153 class Foo:
4154 x = 42
4155
4156 only_callable_members_please = (
4157 r"Protocols with non-method members don't support issubclass()"
4158 )
4159
4160 with self.assertRaisesRegex(TypeError, only_callable_members_please):
4161 issubclass(Foo, ProtocolWithNonCallableMember)
4162
4163 with self.assertRaisesRegex(TypeError, only_callable_members_please):
4164 issubclass(int, ProtocolWithNonCallableMember)
4165
4166 self.assertIsInstance(Foo(), ProtocolWithNonCallableMember)
4167 self.assertNotIsInstance(42, ProtocolWithNonCallableMember)
4168
4169 def test_protocol_decorated_with_final_mixed_members(self):
4170 @final
4171 @runtime_checkable
4172 class ProtocolWithMixedMembers(Protocol):
4173 x: int
4174 def method(self) -> None: ...
4175
4176 class Foo:
4177 x = 42
4178 def method(self) -> None: ...
4179
4180 only_callable_members_please = (
4181 r"Protocols with non-method members don't support issubclass()"
4182 )
4183
4184 with self.assertRaisesRegex(TypeError, only_callable_members_please):
4185 issubclass(Foo, ProtocolWithMixedMembers)
4186
4187 with self.assertRaisesRegex(TypeError, only_callable_members_please):
4188 issubclass(int, ProtocolWithMixedMembers)
4189
4190 self.assertIsInstance(Foo(), ProtocolWithMixedMembers)
4191 self.assertNotIsInstance(42, ProtocolWithMixedMembers)
4192
4193 def test_protocol_issubclass_error_message(self):
4194 @runtime_checkable
4195 class Vec2D(Protocol):
4196 x: float
4197 y: float
4198
4199 def square_norm(self) -> float:
4200 return self.x ** 2 + self.y ** 2 # pragma: no cover
4201
4202 self.assertEqual(Vec2D.__protocol_attrs__, {'x', 'y', 'square_norm'})
4203 expected_error_message = (
4204 "Protocols with non-method members don't support issubclass()."
4205 " Non-method members: 'x', 'y'."
4206 )
4207 with self.assertRaisesRegex(TypeError, re.escape(expected_error_message)):
4208 issubclass(int, Vec2D)
4209
4210 def test_nonruntime_protocol_interaction_with_evil_classproperty(self):
4211 class classproperty:
4212 def __get__(self, instance, type):
4213 raise RuntimeError("NO") # pragma: no cover
4214
4215 class Commentable(Protocol):
4216 evil = classproperty()
4217
4218 # recognised as a protocol attr,
4219 # but not actually accessed by the protocol metaclass
4220 # (which would raise RuntimeError) for non-runtime protocols.
4221 # See gh-113320
4222 self.assertEqual(get_protocol_members(Commentable), {"evil"})
4223
4224 def test_runtime_protocol_interaction_with_evil_classproperty(self):
4225 class CustomError(Exception): pass
4226
4227 class classproperty:
4228 def __get__(self, instance, type):
4229 raise CustomError
4230
4231 with self.assertRaises(TypeError) as cm:
4232 @runtime_checkable
4233 class Commentable(Protocol):
4234 evil = classproperty()
4235
4236 exc = cm.exception
4237 self.assertEqual(
4238 exc.args[0],
4239 "Failed to determine whether protocol member 'evil' is a method member"
4240 )
4241 self.assertIs(type(exc.__cause__), CustomError)
4242
4243 def test_extensions_runtimecheckable_on_typing_Protocol(self):
4244 @runtime_checkable
4245 class Functor(typing.Protocol):
4246 def foo(self) -> None: ...
4247
4248 self.assertNotIsSubclass(object, Functor)
4249
4250 class Bar:
4251 def foo(self): pass
4252
4253 self.assertIsSubclass(Bar, Functor)
4254
4255
4256 class SpecificProtocolTests(BaseTestCase):
4257 def test_reader_runtime_checkable(self):
4258 class MyReader:
4259 def read(self, n: int) -> bytes:
4260 return b"" # pragma: no cover
4261
4262 class WrongReader:
4263 def readx(self, n: int) -> bytes:
4264 return b"" # pragma: no cover
4265
4266 self.assertIsInstance(MyReader(), typing_extensions.Reader)
4267 self.assertNotIsInstance(WrongReader(), typing_extensions.Reader)
4268
4269 def test_writer_runtime_checkable(self):
4270 class MyWriter:
4271 def write(self, b: bytes) -> int:
4272 return 0 # pragma: no cover
4273
4274 class WrongWriter:
4275 def writex(self, b: bytes) -> int:
4276 return 0 # pragma: no cover
4277
4278 self.assertIsInstance(MyWriter(), typing_extensions.Writer)
4279 self.assertNotIsInstance(WrongWriter(), typing_extensions.Writer)
4280
4281
4282 class Point2DGeneric(Generic[T], TypedDict):
4283 a: T
4284 b: T
4285
4286
4287 class Bar(Foo):
4288 b: int
4289
4290
4291 class BarGeneric(FooGeneric[T], total=False):
4292 b: int
4293
4294
4295 class TypedDictTests(BaseTestCase):
4296 def test_basics_functional_syntax(self):
4297 Emp = TypedDict('Emp', {'name': str, 'id': int})
4298 self.assertIsSubclass(Emp, dict)
4299 self.assertIsSubclass(Emp, typing.MutableMapping)
4300 self.assertNotIsSubclass(Emp, collections.abc.Sequence)
4301 jim = Emp(name='Jim', id=1)
4302 self.assertIs(type(jim), dict)
4303 self.assertEqual(jim['name'], 'Jim')
4304 self.assertEqual(jim['id'], 1)
4305 self.assertEqual(Emp.__name__, 'Emp')
4306 self.assertEqual(Emp.__module__, __name__)
4307 self.assertEqual(Emp.__bases__, (dict,))
4308 self.assertEqual(Emp.__annotations__, {'name': str, 'id': int})
4309 self.assertEqual(Emp.__total__, True)
4310
4311 def test_allowed_as_type_argument(self):
4312 # https://github.com/python/typing_extensions/issues/613
4313 obj = typing.Type[typing_extensions.TypedDict]
4314 self.assertIs(typing_extensions.get_origin(obj), type)
4315 self.assertEqual(typing_extensions.get_args(obj), (typing_extensions.TypedDict,))
4316
4317 @skipIf(sys.version_info < (3, 13), "Change in behavior in 3.13")
4318 def test_keywords_syntax_raises_on_3_13(self):
4319 with self.assertRaises(TypeError), self.assertWarns(DeprecationWarning):
4320 TypedDict('Emp', name=str, id=int)
4321
4322 @skipIf(sys.version_info >= (3, 13), "3.13 removes support for kwargs")
4323 def test_basics_keywords_syntax(self):
4324 with self.assertWarns(DeprecationWarning):
4325 Emp = TypedDict('Emp', name=str, id=int)
4326 self.assertIsSubclass(Emp, dict)
4327 self.assertIsSubclass(Emp, typing.MutableMapping)
4328 self.assertNotIsSubclass(Emp, collections.abc.Sequence)
4329 jim = Emp(name='Jim', id=1)
4330 self.assertIs(type(jim), dict)
4331 self.assertEqual(jim['name'], 'Jim')
4332 self.assertEqual(jim['id'], 1)
4333 self.assertEqual(Emp.__name__, 'Emp')
4334 self.assertEqual(Emp.__module__, __name__)
4335 self.assertEqual(Emp.__bases__, (dict,))
4336 self.assertEqual(Emp.__annotations__, {'name': str, 'id': int})
4337 self.assertEqual(Emp.__total__, True)
4338
4339 @skipIf(sys.version_info >= (3, 13), "3.13 removes support for kwargs")
4340 def test_typeddict_special_keyword_names(self):
4341 with self.assertWarns(DeprecationWarning):
4342 TD = TypedDict("TD", cls=type, self=object, typename=str, _typename=int,
4343 fields=list, _fields=dict,
4344 closed=bool, extra_items=bool)
4345 self.assertEqual(TD.__name__, 'TD')
4346 self.assertEqual(TD.__annotations__, {'cls': type, 'self': object, 'typename': str,
4347 '_typename': int, 'fields': list, '_fields': dict,
4348 'closed': bool, 'extra_items': bool})
4349 self.assertIsNone(TD.__closed__)
4350 self.assertIs(TD.__extra_items__, NoExtraItems)
4351 a = TD(cls=str, self=42, typename='foo', _typename=53,
4352 fields=[('bar', tuple)], _fields={'baz', set},
4353 closed=None, extra_items="tea pot")
4354 self.assertEqual(a['cls'], str)
4355 self.assertEqual(a['self'], 42)
4356 self.assertEqual(a['typename'], 'foo')
4357 self.assertEqual(a['_typename'], 53)
4358 self.assertEqual(a['fields'], [('bar', tuple)])
4359 self.assertEqual(a['_fields'], {'baz', set})
4360 self.assertIsNone(a['closed'])
4361 self.assertEqual(a['extra_items'], "tea pot")
4362
4363 def test_typeddict_create_errors(self):
4364 with self.assertRaises(TypeError):
4365 TypedDict.__new__()
4366 with self.assertRaises(TypeError):
4367 TypedDict()
4368 with self.assertRaises(TypeError):
4369 TypedDict('Emp', [('name', str)], None)
4370
4371 def test_typeddict_errors(self):
4372 Emp = TypedDict('Emp', {'name': str, 'id': int})
4373 self.assertEqual(TypedDict.__module__, 'typing_extensions')
4374 jim = Emp(name='Jim', id=1)
4375 with self.assertRaises(TypeError):
4376 isinstance({}, Emp)
4377 with self.assertRaises(TypeError):
4378 isinstance(jim, Emp)
4379 with self.assertRaises(TypeError):
4380 issubclass(dict, Emp)
4381
4382 if not TYPING_3_11_0:
4383 with self.assertRaises(TypeError), self.assertWarns(DeprecationWarning):
4384 TypedDict('Hi', x=1)
4385 with self.assertRaises(TypeError):
4386 TypedDict('Hi', [('x', int), ('y', 1)])
4387 with self.assertRaises(TypeError):
4388 TypedDict('Hi', [('x', int)], y=int)
4389
4390 def test_py36_class_syntax_usage(self):
4391 self.assertEqual(LabelPoint2D.__name__, 'LabelPoint2D')
4392 self.assertEqual(LabelPoint2D.__module__, __name__)
4393 self.assertEqual(LabelPoint2D.__annotations__, {'x': int, 'y': int, 'label': str})
4394 self.assertEqual(LabelPoint2D.__bases__, (dict,))
4395 self.assertEqual(LabelPoint2D.__total__, True)
4396 self.assertNotIsSubclass(LabelPoint2D, typing.Sequence)
4397 not_origin = Point2D(x=0, y=1)
4398 self.assertEqual(not_origin['x'], 0)
4399 self.assertEqual(not_origin['y'], 1)
4400 other = LabelPoint2D(x=0, y=1, label='hi')
4401 self.assertEqual(other['label'], 'hi')
4402
4403 def test_pickle(self):
4404 global EmpD # pickle wants to reference the class by name
4405 EmpD = TypedDict('EmpD', {'name': str, 'id': int})
4406 jane = EmpD({'name': 'jane', 'id': 37})
4407 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
4408 z = pickle.dumps(jane, proto)
4409 jane2 = pickle.loads(z)
4410 self.assertEqual(jane2, jane)
4411 self.assertEqual(jane2, {'name': 'jane', 'id': 37})
4412 ZZ = pickle.dumps(EmpD, proto)
4413 EmpDnew = pickle.loads(ZZ)
4414 self.assertEqual(EmpDnew({'name': 'jane', 'id': 37}), jane)
4415
4416 def test_pickle_generic(self):
4417 point = Point2DGeneric(a=5.0, b=3.0)
4418 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
4419 z = pickle.dumps(point, proto)
4420 point2 = pickle.loads(z)
4421 self.assertEqual(point2, point)
4422 self.assertEqual(point2, {'a': 5.0, 'b': 3.0})
4423 ZZ = pickle.dumps(Point2DGeneric, proto)
4424 Point2DGenericNew = pickle.loads(ZZ)
4425 self.assertEqual(Point2DGenericNew({'a': 5.0, 'b': 3.0}), point)
4426
4427 def test_optional(self):
4428 EmpD = TypedDict('EmpD', {'name': str, 'id': int})
4429
4430 self.assertEqual(typing.Optional[EmpD], typing.Union[None, EmpD])
4431 self.assertNotEqual(typing.List[EmpD], typing.Tuple[EmpD])
4432
4433 def test_total(self):
4434 D = TypedDict('D', {'x': int}, total=False)
4435 self.assertEqual(D(), {})
4436 self.assertEqual(D(x=1), {'x': 1})
4437 self.assertEqual(D.__total__, False)
4438 self.assertEqual(D.__required_keys__, frozenset())
4439 self.assertEqual(D.__optional_keys__, {'x'})
4440
4441 self.assertEqual(Options(), {})
4442 self.assertEqual(Options(log_level=2), {'log_level': 2})
4443 self.assertEqual(Options.__total__, False)
4444 self.assertEqual(Options.__required_keys__, frozenset())
4445 self.assertEqual(Options.__optional_keys__, {'log_level', 'log_path'})
4446
4447 def test_total_inherits_non_total(self):
4448 class TD1(TypedDict, total=False):
4449 a: int
4450
4451 self.assertIs(TD1.__total__, False)
4452
4453 class TD2(TD1):
4454 b: str
4455
4456 self.assertIs(TD2.__total__, True)
4457
4458 def test_total_with_assigned_value(self):
4459 class TD(TypedDict):
4460 __total__ = "some_value"
4461
4462 self.assertIs(TD.__total__, True)
4463
4464 class TD2(TypedDict, total=True):
4465 __total__ = "some_value"
4466
4467 self.assertIs(TD2.__total__, True)
4468
4469 class TD3(TypedDict, total=False):
4470 __total__ = "some value"
4471
4472 self.assertIs(TD3.__total__, False)
4473
4474 TD4 = TypedDict('TD4', {'__total__': "some_value"}) # noqa: F821
4475 self.assertIs(TD4.__total__, True)
4476
4477
4478 def test_optional_keys(self):
4479 class Point2Dor3D(Point2D, total=False):
4480 z: int
4481
4482 assert Point2Dor3D.__required_keys__ == frozenset(['x', 'y'])
4483 assert Point2Dor3D.__optional_keys__ == frozenset(['z'])
4484
4485 def test_keys_inheritance(self):
4486 class BaseAnimal(TypedDict):
4487 name: str
4488
4489 class Animal(BaseAnimal, total=False):
4490 voice: str
4491 tail: bool
4492
4493 class Cat(Animal):
4494 fur_color: str
4495
4496 assert BaseAnimal.__required_keys__ == frozenset(['name'])
4497 assert BaseAnimal.__optional_keys__ == frozenset([])
4498 assert BaseAnimal.__annotations__ == {'name': str}
4499
4500 assert Animal.__required_keys__ == frozenset(['name'])
4501 assert Animal.__optional_keys__ == frozenset(['tail', 'voice'])
4502 assert Animal.__annotations__ == {
4503 'name': str,
4504 'tail': bool,
4505 'voice': str,
4506 }
4507
4508 assert Cat.__required_keys__ == frozenset(['name', 'fur_color'])
4509 assert Cat.__optional_keys__ == frozenset(['tail', 'voice'])
4510 assert Cat.__annotations__ == {
4511 'fur_color': str,
4512 'name': str,
4513 'tail': bool,
4514 'voice': str,
4515 }
4516
4517 @skipIf(sys.version_info == (3, 14, 0, "beta", 1), "Broken on beta 1, fixed in beta 2")
4518 def test_inheritance_pep563(self):
4519 def _make_td(future, class_name, annos, base, extra_names=None):
4520 lines = []
4521 if future:
4522 lines.append('from __future__ import annotations')
4523 lines.append('from typing import TypedDict')
4524 lines.append(f'class {class_name}({base}):')
4525 for name, anno in annos.items():
4526 lines.append(f' {name}: {anno}')
4527 code = '\n'.join(lines)
4528 ns = {**extra_names} if extra_names else {}
4529 exec(code, ns)
4530 return ns[class_name]
4531
4532 for base_future in (True, False):
4533 for child_future in (True, False):
4534 with self.subTest(base_future=base_future, child_future=child_future):
4535 base = _make_td(
4536 base_future, "Base", {"base": "int"}, "TypedDict"
4537 )
4538 if sys.version_info >= (3, 14):
4539 self.assertIsNotNone(base.__annotate__)
4540 child = _make_td(
4541 child_future, "Child", {"child": "int"}, "Base", {"Base": base}
4542 )
4543 if sys.version_info >= (3, 14):
4544 base_anno = typing.ForwardRef("int", module="builtins", owner=base) if base_future else int
4545 child_anno = typing.ForwardRef("int", module="builtins", owner=child) if child_future else int
4546 else:
4547 base_anno = typing.ForwardRef("int", module="builtins") if base_future else int
4548 child_anno = typing.ForwardRef("int", module="builtins") if child_future else int
4549 self.assertEqual(base.__annotations__, {'base': base_anno})
4550 self.assertEqual(
4551 child.__annotations__, {'child': child_anno, 'base': base_anno}
4552 )
4553
4554 def test_required_notrequired_keys(self):
4555 self.assertEqual(NontotalMovie.__required_keys__,
4556 frozenset({"title"}))
4557 self.assertEqual(NontotalMovie.__optional_keys__,
4558 frozenset({"year"}))
4559
4560 self.assertEqual(TotalMovie.__required_keys__,
4561 frozenset({"title"}))
4562 self.assertEqual(TotalMovie.__optional_keys__,
4563 frozenset({"year"}))
4564
4565 self.assertEqual(VeryAnnotated.__required_keys__,
4566 frozenset())
4567 self.assertEqual(VeryAnnotated.__optional_keys__,
4568 frozenset({"a"}))
4569
4570 self.assertEqual(AnnotatedMovie.__required_keys__,
4571 frozenset({"title"}))
4572 self.assertEqual(AnnotatedMovie.__optional_keys__,
4573 frozenset({"year"}))
4574
4575 self.assertEqual(WeirdlyQuotedMovie.__required_keys__,
4576 frozenset({"title"}))
4577 self.assertEqual(WeirdlyQuotedMovie.__optional_keys__,
4578 frozenset({"year"}))
4579
4580 self.assertEqual(ChildTotalMovie.__required_keys__,
4581 frozenset({"title"}))
4582 self.assertEqual(ChildTotalMovie.__optional_keys__,
4583 frozenset({"year"}))
4584
4585 self.assertEqual(ChildDeeplyAnnotatedMovie.__required_keys__,
4586 frozenset({"title"}))
4587 self.assertEqual(ChildDeeplyAnnotatedMovie.__optional_keys__,
4588 frozenset({"year"}))
4589
4590 def test_multiple_inheritance(self):
4591 class One(TypedDict):
4592 one: int
4593 class Two(TypedDict):
4594 two: str
4595 class Untotal(TypedDict, total=False):
4596 untotal: str
4597 Inline = TypedDict('Inline', {'inline': bool})
4598 class Regular:
4599 pass
4600
4601 class Child(One, Two):
4602 child: bool
4603 self.assertEqual(
4604 Child.__required_keys__,
4605 frozenset(['one', 'two', 'child']),
4606 )
4607 self.assertEqual(
4608 Child.__optional_keys__,
4609 frozenset([]),
4610 )
4611 self.assertEqual(
4612 Child.__annotations__,
4613 {'one': int, 'two': str, 'child': bool},
4614 )
4615
4616 class ChildWithOptional(One, Untotal):
4617 child: bool
4618 self.assertEqual(
4619 ChildWithOptional.__required_keys__,
4620 frozenset(['one', 'child']),
4621 )
4622 self.assertEqual(
4623 ChildWithOptional.__optional_keys__,
4624 frozenset(['untotal']),
4625 )
4626 self.assertEqual(
4627 ChildWithOptional.__annotations__,
4628 {'one': int, 'untotal': str, 'child': bool},
4629 )
4630
4631 class ChildWithTotalFalse(One, Untotal, total=False):
4632 child: bool
4633 self.assertEqual(
4634 ChildWithTotalFalse.__required_keys__,
4635 frozenset(['one']),
4636 )
4637 self.assertEqual(
4638 ChildWithTotalFalse.__optional_keys__,
4639 frozenset(['untotal', 'child']),
4640 )
4641 self.assertEqual(
4642 ChildWithTotalFalse.__annotations__,
4643 {'one': int, 'untotal': str, 'child': bool},
4644 )
4645
4646 class ChildWithInlineAndOptional(Untotal, Inline):
4647 child: bool
4648 self.assertEqual(
4649 ChildWithInlineAndOptional.__required_keys__,
4650 frozenset(['inline', 'child']),
4651 )
4652 self.assertEqual(
4653 ChildWithInlineAndOptional.__optional_keys__,
4654 frozenset(['untotal']),
4655 )
4656 self.assertEqual(
4657 ChildWithInlineAndOptional.__annotations__,
4658 {'inline': bool, 'untotal': str, 'child': bool},
4659 )
4660
4661 wrong_bases = [
4662 (One, Regular),
4663 (Regular, One),
4664 (One, Two, Regular),
4665 (Inline, Regular),
4666 (Untotal, Regular),
4667 ]
4668 for bases in wrong_bases:
4669 with self.subTest(bases=bases):
4670 with self.assertRaisesRegex(
4671 TypeError,
4672 'cannot inherit from both a TypedDict type and a non-TypedDict',
4673 ):
4674 class Wrong(*bases):
4675 pass
4676
4677 def test_keys_inheritance_with_same_name(self):
4678 class NotTotal(TypedDict, total=False):
4679 a: int
4680
4681 class Total(NotTotal):
4682 a: int
4683
4684 self.assertEqual(NotTotal.__required_keys__, frozenset())
4685 self.assertEqual(NotTotal.__optional_keys__, frozenset(['a']))
4686 self.assertEqual(Total.__required_keys__, frozenset(['a']))
4687 self.assertEqual(Total.__optional_keys__, frozenset())
4688
4689 class Base(TypedDict):
4690 a: NotRequired[int]
4691 b: Required[int]
4692
4693 class Child(Base):
4694 a: Required[int]
4695 b: NotRequired[int]
4696
4697 self.assertEqual(Base.__required_keys__, frozenset(['b']))
4698 self.assertEqual(Base.__optional_keys__, frozenset(['a']))
4699 self.assertEqual(Child.__required_keys__, frozenset(['a']))
4700 self.assertEqual(Child.__optional_keys__, frozenset(['b']))
4701
4702 def test_multiple_inheritance_with_same_key(self):
4703 class Base1(TypedDict):
4704 a: NotRequired[int]
4705
4706 class Base2(TypedDict):
4707 a: Required[str]
4708
4709 class Child(Base1, Base2):
4710 pass
4711
4712 # Last base wins
4713 self.assertEqual(Child.__annotations__, {'a': Required[str]})
4714 self.assertEqual(Child.__required_keys__, frozenset(['a']))
4715 self.assertEqual(Child.__optional_keys__, frozenset())
4716
4717
4718 def test_closed_values(self):
4719 class Implicit(TypedDict): ...
4720 class ExplicitTrue(TypedDict, closed=True): ...
4721 class ExplicitFalse(TypedDict, closed=False): ...
4722
4723 self.assertIsNone(Implicit.__closed__)
4724 self.assertIs(ExplicitTrue.__closed__, True)
4725 self.assertIs(ExplicitFalse.__closed__, False)
4726
4727
4728 @skipIf(TYPING_3_14_0, "only supported on older versions")
4729 def test_closed_typeddict_compat(self):
4730 class Closed(TypedDict, closed=True):
4731 __extra_items__: None
4732
4733 class Unclosed(TypedDict, closed=False):
4734 ...
4735
4736 class ChildUnclosed(Closed, Unclosed):
4737 ...
4738
4739 self.assertIsNone(ChildUnclosed.__closed__)
4740 self.assertEqual(ChildUnclosed.__extra_items__, NoExtraItems)
4741
4742 class ChildClosed(Unclosed, Closed):
4743 ...
4744
4745 self.assertIsNone(ChildClosed.__closed__)
4746 self.assertEqual(ChildClosed.__extra_items__, NoExtraItems)
4747
4748 def test_extra_items_class_arg(self):
4749 class TD(TypedDict, extra_items=int):
4750 a: str
4751
4752 self.assertIs(TD.__extra_items__, int)
4753 self.assertEqual(TD.__annotations__, {'a': str})
4754 self.assertEqual(TD.__required_keys__, frozenset({'a'}))
4755 self.assertEqual(TD.__optional_keys__, frozenset())
4756
4757 class NoExtra(TypedDict):
4758 a: str
4759
4760 self.assertIs(NoExtra.__extra_items__, NoExtraItems)
4761 self.assertEqual(NoExtra.__annotations__, {'a': str})
4762 self.assertEqual(NoExtra.__required_keys__, frozenset({'a'}))
4763 self.assertEqual(NoExtra.__optional_keys__, frozenset())
4764
4765 def test_is_typeddict(self):
4766 self.assertIs(is_typeddict(Point2D), True)
4767 self.assertIs(is_typeddict(Point2Dor3D), True)
4768 self.assertIs(is_typeddict(Union[str, int]), False)
4769 # classes, not instances
4770 self.assertIs(is_typeddict(Point2D()), False)
4771 call_based = TypedDict('call_based', {'a': int})
4772 self.assertIs(is_typeddict(call_based), True)
4773 self.assertIs(is_typeddict(call_based()), False)
4774
4775 T = TypeVar("T")
4776 class BarGeneric(TypedDict, Generic[T]):
4777 a: T
4778 self.assertIs(is_typeddict(BarGeneric), True)
4779 self.assertIs(is_typeddict(BarGeneric[int]), False)
4780 self.assertIs(is_typeddict(BarGeneric()), False)
4781
4782 if hasattr(typing, "TypeAliasType"):
4783 ns = {"TypedDict": TypedDict}
4784 exec("""if True:
4785 class NewGeneric[T](TypedDict):
4786 a: T
4787 """, ns)
4788 NewGeneric = ns["NewGeneric"]
4789 self.assertIs(is_typeddict(NewGeneric), True)
4790 self.assertIs(is_typeddict(NewGeneric[int]), False)
4791 self.assertIs(is_typeddict(NewGeneric()), False)
4792
4793 # The TypedDict constructor is not itself a TypedDict
4794 self.assertIs(is_typeddict(TypedDict), False)
4795 if hasattr(typing, "TypedDict"):
4796 self.assertIs(is_typeddict(typing.TypedDict), False)
4797
4798 def test_is_typeddict_against_typeddict_from_typing(self):
4799 Point = typing.TypedDict('Point', {'x': int, 'y': int})
4800
4801 class PointDict2D(typing.TypedDict):
4802 x: int
4803 y: int
4804
4805 class PointDict3D(PointDict2D, total=False):
4806 z: int
4807
4808 assert is_typeddict(Point) is True
4809 assert is_typeddict(PointDict2D) is True
4810 assert is_typeddict(PointDict3D) is True
4811
4812 @skipUnless(HAS_FORWARD_MODULE, "ForwardRef.__forward_module__ was added in 3.9.7")
4813 def test_get_type_hints_cross_module_subclass(self):
4814 self.assertNotIn("_DoNotImport", globals())
4815 self.assertEqual(
4816 {k: v.__name__ for k, v in get_type_hints(Bar).items()},
4817 {'a': "_DoNotImport", 'b': "int"}
4818 )
4819
4820 def test_get_type_hints_generic(self):
4821 self.assertEqual(
4822 get_type_hints(BarGeneric),
4823 {'a': typing.Optional[T], 'b': int}
4824 )
4825
4826 class FooBarGeneric(BarGeneric[int]):
4827 c: str
4828
4829 self.assertEqual(
4830 get_type_hints(FooBarGeneric),
4831 {'a': typing.Optional[T], 'b': int, 'c': str}
4832 )
4833
4834 @skipUnless(TYPING_3_12_0, "PEP 695 required")
4835 def test_pep695_generic_typeddict(self):
4836 ns = {"TypedDict": TypedDict}
4837 exec("""if True:
4838 class A[T](TypedDict):
4839 a: T
4840 """, ns)
4841 A = ns["A"]
4842 T, = A.__type_params__
4843 self.assertIsInstance(T, TypeVar)
4844 self.assertEqual(T.__name__, 'T')
4845 self.assertEqual(A.__bases__, (Generic, dict))
4846 self.assertEqual(A.__orig_bases__, (TypedDict, Generic[T]))
4847 self.assertEqual(A.__mro__, (A, Generic, dict, object))
4848 self.assertEqual(A.__parameters__, (T,))
4849 self.assertEqual(A[str].__parameters__, ())
4850 self.assertEqual(A[str].__args__, (str,))
4851
4852 def test_generic_inheritance(self):
4853 class A(TypedDict, Generic[T]):
4854 a: T
4855
4856 self.assertEqual(A.__bases__, (Generic, dict))
4857 self.assertEqual(A.__orig_bases__, (TypedDict, Generic[T]))
4858 self.assertEqual(A.__mro__, (A, Generic, dict, object))
4859 self.assertEqual(A.__parameters__, (T,))
4860 self.assertEqual(A[str].__parameters__, ())
4861 self.assertEqual(A[str].__args__, (str,))
4862
4863 class A2(Generic[T], TypedDict):
4864 a: T
4865
4866 self.assertEqual(A2.__bases__, (Generic, dict))
4867 self.assertEqual(A2.__orig_bases__, (Generic[T], TypedDict))
4868 self.assertEqual(A2.__mro__, (A2, Generic, dict, object))
4869 self.assertEqual(A2.__parameters__, (T,))
4870 self.assertEqual(A2[str].__parameters__, ())
4871 self.assertEqual(A2[str].__args__, (str,))
4872
4873 class B(A[KT], total=False):
4874 b: KT
4875
4876 self.assertEqual(B.__bases__, (Generic, dict))
4877 self.assertEqual(B.__orig_bases__, (A[KT],))
4878 self.assertEqual(B.__mro__, (B, Generic, dict, object))
4879 self.assertEqual(B.__parameters__, (KT,))
4880 self.assertEqual(B.__total__, False)
4881 self.assertEqual(B.__optional_keys__, frozenset(['b']))
4882 self.assertEqual(B.__required_keys__, frozenset(['a']))
4883
4884 self.assertEqual(B[str].__parameters__, ())
4885 self.assertEqual(B[str].__args__, (str,))
4886 self.assertEqual(B[str].__origin__, B)
4887
4888 class C(B[int]):
4889 c: int
4890
4891 self.assertEqual(C.__bases__, (Generic, dict))
4892 self.assertEqual(C.__orig_bases__, (B[int],))
4893 self.assertEqual(C.__mro__, (C, Generic, dict, object))
4894 self.assertEqual(C.__parameters__, ())
4895 self.assertEqual(C.__total__, True)
4896 self.assertEqual(C.__optional_keys__, frozenset(['b']))
4897 self.assertEqual(C.__required_keys__, frozenset(['a', 'c']))
4898 assert C.__annotations__ == {
4899 'a': T,
4900 'b': KT,
4901 'c': int,
4902 }
4903 with self.assertRaises(TypeError):
4904 C[str]
4905
4906 class Point3D(Point2DGeneric[T], Generic[T, KT]):
4907 c: KT
4908
4909 self.assertEqual(Point3D.__bases__, (Generic, dict))
4910 self.assertEqual(Point3D.__orig_bases__, (Point2DGeneric[T], Generic[T, KT]))
4911 self.assertEqual(Point3D.__mro__, (Point3D, Generic, dict, object))
4912 self.assertEqual(Point3D.__parameters__, (T, KT))
4913 self.assertEqual(Point3D.__total__, True)
4914 self.assertEqual(Point3D.__optional_keys__, frozenset())
4915 self.assertEqual(Point3D.__required_keys__, frozenset(['a', 'b', 'c']))
4916 self.assertEqual(Point3D.__annotations__, {
4917 'a': T,
4918 'b': T,
4919 'c': KT,
4920 })
4921 self.assertEqual(Point3D[int, str].__origin__, Point3D)
4922
4923 with self.assertRaises(TypeError):
4924 Point3D[int]
4925
4926 with self.assertRaises(TypeError):
4927 class Point3D(Point2DGeneric[T], Generic[KT]):
4928 c: KT
4929
4930 def test_implicit_any_inheritance(self):
4931 class A(TypedDict, Generic[T]):
4932 a: T
4933
4934 class B(A[KT], total=False):
4935 b: KT
4936
4937 class WithImplicitAny(B):
4938 c: int
4939
4940 self.assertEqual(WithImplicitAny.__bases__, (Generic, dict,))
4941 self.assertEqual(WithImplicitAny.__mro__, (WithImplicitAny, Generic, dict, object))
4942 # Consistent with GenericTests.test_implicit_any
4943 self.assertEqual(WithImplicitAny.__parameters__, ())
4944 self.assertEqual(WithImplicitAny.__total__, True)
4945 self.assertEqual(WithImplicitAny.__optional_keys__, frozenset(['b']))
4946 self.assertEqual(WithImplicitAny.__required_keys__, frozenset(['a', 'c']))
4947 assert WithImplicitAny.__annotations__ == {
4948 'a': T,
4949 'b': KT,
4950 'c': int,
4951 }
4952 with self.assertRaises(TypeError):
4953 WithImplicitAny[str]
4954
4955 def test_non_generic_subscript(self):
4956 # For backward compatibility, subscription works
4957 # on arbitrary TypedDict types.
4958 class TD(TypedDict):
4959 a: T
4960 A = TD[int]
4961 self.assertEqual(A.__origin__, TD)
4962 self.assertEqual(A.__parameters__, ())
4963 self.assertEqual(A.__args__, (int,))
4964 a = A(a=1)
4965 self.assertIs(type(a), dict)
4966 self.assertEqual(a, {'a': 1})
4967
4968 def test_orig_bases(self):
4969 T = TypeVar('T')
4970
4971 class Parent(TypedDict):
4972 pass
4973
4974 class Child(Parent):
4975 pass
4976
4977 class OtherChild(Parent):
4978 pass
4979
4980 class MixedChild(Child, OtherChild, Parent):
4981 pass
4982
4983 class GenericParent(TypedDict, Generic[T]):
4984 pass
4985
4986 class GenericChild(GenericParent[int]):
4987 pass
4988
4989 class OtherGenericChild(GenericParent[str]):
4990 pass
4991
4992 class MixedGenericChild(GenericChild, OtherGenericChild, GenericParent[float]):
4993 pass
4994
4995 class MultipleGenericBases(GenericParent[int], GenericParent[float]):
4996 pass
4997
4998 CallTypedDict = TypedDict('CallTypedDict', {})
4999
5000 self.assertEqual(Parent.__orig_bases__, (TypedDict,))
5001 self.assertEqual(Child.__orig_bases__, (Parent,))
5002 self.assertEqual(OtherChild.__orig_bases__, (Parent,))
5003 self.assertEqual(MixedChild.__orig_bases__, (Child, OtherChild, Parent,))
5004 self.assertEqual(GenericParent.__orig_bases__, (TypedDict, Generic[T]))
5005 self.assertEqual(GenericChild.__orig_bases__, (GenericParent[int],))
5006 self.assertEqual(OtherGenericChild.__orig_bases__, (GenericParent[str],))
5007 self.assertEqual(MixedGenericChild.__orig_bases__, (GenericChild, OtherGenericChild, GenericParent[float]))
5008 self.assertEqual(MultipleGenericBases.__orig_bases__, (GenericParent[int], GenericParent[float]))
5009 self.assertEqual(CallTypedDict.__orig_bases__, (TypedDict,))
5010
5011 def test_zero_fields_typeddicts(self):
5012 T1 = TypedDict("T1", {})
5013 class T2(TypedDict): pass
5014 try:
5015 ns = {"TypedDict": TypedDict}
5016 exec("class T3[tvar](TypedDict): pass", ns)
5017 T3 = ns["T3"]
5018 except SyntaxError:
5019 class T3(TypedDict): pass
5020 S = TypeVar("S")
5021 class T4(TypedDict, Generic[S]): pass
5022
5023 expected_warning = re.escape(
5024 "Failing to pass a value for the 'fields' parameter is deprecated "
5025 "and will be disallowed in Python 3.15. "
5026 "To create a TypedDict class with 0 fields "
5027 "using the functional syntax, "
5028 "pass an empty dictionary, e.g. `T5 = TypedDict('T5', {})`."
5029 )
5030 with self.assertWarnsRegex(DeprecationWarning, fr"^{expected_warning}$"):
5031 T5 = TypedDict('T5')
5032
5033 expected_warning = re.escape(
5034 "Passing `None` as the 'fields' parameter is deprecated "
5035 "and will be disallowed in Python 3.15. "
5036 "To create a TypedDict class with 0 fields "
5037 "using the functional syntax, "
5038 "pass an empty dictionary, e.g. `T6 = TypedDict('T6', {})`."
5039 )
5040 with self.assertWarnsRegex(DeprecationWarning, fr"^{expected_warning}$"):
5041 T6 = TypedDict('T6', None)
5042
5043 for klass in T1, T2, T3, T4, T5, T6:
5044 with self.subTest(klass=klass.__name__):
5045 self.assertEqual(klass.__annotations__, {})
5046 self.assertEqual(klass.__required_keys__, set())
5047 self.assertEqual(klass.__optional_keys__, set())
5048 self.assertIsInstance(klass(), dict)
5049
5050 def test_readonly_inheritance(self):
5051 class Base1(TypedDict):
5052 a: ReadOnly[int]
5053
5054 class Child1(Base1):
5055 b: str
5056
5057 self.assertEqual(Child1.__readonly_keys__, frozenset({'a'}))
5058 self.assertEqual(Child1.__mutable_keys__, frozenset({'b'}))
5059
5060 class Base2(TypedDict):
5061 a: int
5062
5063 class Child2(Base2):
5064 b: ReadOnly[str]
5065
5066 self.assertEqual(Child2.__readonly_keys__, frozenset({'b'}))
5067 self.assertEqual(Child2.__mutable_keys__, frozenset({'a'}))
5068
5069 def test_make_mutable_key_readonly(self):
5070 class Base(TypedDict):
5071 a: int
5072
5073 self.assertEqual(Base.__readonly_keys__, frozenset())
5074 self.assertEqual(Base.__mutable_keys__, frozenset({'a'}))
5075
5076 class Child(Base):
5077 a: ReadOnly[int] # type checker error, but allowed at runtime
5078
5079 self.assertEqual(Child.__readonly_keys__, frozenset({'a'}))
5080 self.assertEqual(Child.__mutable_keys__, frozenset())
5081
5082 def test_can_make_readonly_key_mutable(self):
5083 class Base(TypedDict):
5084 a: ReadOnly[int]
5085
5086 class Child(Base):
5087 a: int
5088
5089 self.assertEqual(Child.__readonly_keys__, frozenset())
5090 self.assertEqual(Child.__mutable_keys__, frozenset({'a'}))
5091
5092 def test_combine_qualifiers(self):
5093 class AllTheThings(TypedDict):
5094 a: Annotated[Required[ReadOnly[int]], "why not"]
5095 b: Required[Annotated[ReadOnly[int], "why not"]]
5096 c: ReadOnly[NotRequired[Annotated[int, "why not"]]]
5097 d: NotRequired[Annotated[int, "why not"]]
5098
5099 self.assertEqual(AllTheThings.__required_keys__, frozenset({'a', 'b'}))
5100 self.assertEqual(AllTheThings.__optional_keys__, frozenset({'c', 'd'}))
5101 self.assertEqual(AllTheThings.__readonly_keys__, frozenset({'a', 'b', 'c'}))
5102 self.assertEqual(AllTheThings.__mutable_keys__, frozenset({'d'}))
5103
5104 self.assertEqual(
5105 get_type_hints(AllTheThings, include_extras=False),
5106 {'a': int, 'b': int, 'c': int, 'd': int},
5107 )
5108 self.assertEqual(
5109 get_type_hints(AllTheThings, include_extras=True),
5110 {
5111 'a': Annotated[Required[ReadOnly[int]], 'why not'],
5112 'b': Required[Annotated[ReadOnly[int], 'why not']],
5113 'c': ReadOnly[NotRequired[Annotated[int, 'why not']]],
5114 'd': NotRequired[Annotated[int, 'why not']],
5115 },
5116 )
5117
5118 @skipIf(TYPING_3_14_0, "Old syntax only supported on <3.14")
5119 def test_extra_keys_non_readonly_legacy(self):
5120 class Base(TypedDict, closed=True):
5121 __extra_items__: str
5122
5123 class Child(Base):
5124 a: NotRequired[int]
5125
5126 self.assertEqual(Child.__required_keys__, frozenset({}))
5127 self.assertEqual(Child.__optional_keys__, frozenset({'a'}))
5128 self.assertEqual(Child.__readonly_keys__, frozenset({}))
5129 self.assertEqual(Child.__mutable_keys__, frozenset({'a'}))
5130
5131 @skipIf(TYPING_3_14_0, "Only supported on <3.14")
5132 def test_extra_keys_readonly_legacy(self):
5133 class Base(TypedDict, closed=True):
5134 __extra_items__: ReadOnly[str]
5135
5136 class Child(Base):
5137 a: NotRequired[str]
5138
5139 self.assertEqual(Child.__required_keys__, frozenset({}))
5140 self.assertEqual(Child.__optional_keys__, frozenset({'a'}))
5141 self.assertEqual(Child.__readonly_keys__, frozenset({}))
5142 self.assertEqual(Child.__mutable_keys__, frozenset({'a'}))
5143
5144 @skipIf(TYPING_3_14_0, "Only supported on <3.14")
5145 def test_extra_keys_readonly_explicit_closed_legacy(self):
5146 class Base(TypedDict, closed=True):
5147 __extra_items__: ReadOnly[str]
5148
5149 class Child(Base, closed=True):
5150 a: NotRequired[str]
5151
5152 self.assertEqual(Child.__required_keys__, frozenset({}))
5153 self.assertEqual(Child.__optional_keys__, frozenset({'a'}))
5154 self.assertEqual(Child.__readonly_keys__, frozenset({}))
5155 self.assertEqual(Child.__mutable_keys__, frozenset({'a'}))
5156
5157 @skipIf(TYPING_3_14_0, "Only supported on <3.14")
5158 def test_extra_key_required_legacy(self):
5159 with self.assertRaisesRegex(
5160 TypeError,
5161 "Special key __extra_items__ does not support Required"
5162 ):
5163 TypedDict("A", {"__extra_items__": Required[int]}, closed=True)
5164
5165 with self.assertRaisesRegex(
5166 TypeError,
5167 "Special key __extra_items__ does not support NotRequired"
5168 ):
5169 TypedDict("A", {"__extra_items__": NotRequired[int]}, closed=True)
5170
5171 def test_regular_extra_items_legacy(self):
5172 class ExtraReadOnly(TypedDict):
5173 __extra_items__: ReadOnly[str]
5174
5175 self.assertEqual(ExtraReadOnly.__required_keys__, frozenset({'__extra_items__'}))
5176 self.assertEqual(ExtraReadOnly.__optional_keys__, frozenset({}))
5177 self.assertEqual(ExtraReadOnly.__readonly_keys__, frozenset({'__extra_items__'}))
5178 self.assertEqual(ExtraReadOnly.__mutable_keys__, frozenset({}))
5179 self.assertIs(ExtraReadOnly.__extra_items__, NoExtraItems)
5180 self.assertIsNone(ExtraReadOnly.__closed__)
5181
5182 class ExtraRequired(TypedDict):
5183 __extra_items__: Required[str]
5184
5185 self.assertEqual(ExtraRequired.__required_keys__, frozenset({'__extra_items__'}))
5186 self.assertEqual(ExtraRequired.__optional_keys__, frozenset({}))
5187 self.assertEqual(ExtraRequired.__readonly_keys__, frozenset({}))
5188 self.assertEqual(ExtraRequired.__mutable_keys__, frozenset({'__extra_items__'}))
5189 self.assertIs(ExtraRequired.__extra_items__, NoExtraItems)
5190 self.assertIsNone(ExtraRequired.__closed__)
5191
5192 class ExtraNotRequired(TypedDict):
5193 __extra_items__: NotRequired[str]
5194
5195 self.assertEqual(ExtraNotRequired.__required_keys__, frozenset({}))
5196 self.assertEqual(ExtraNotRequired.__optional_keys__, frozenset({'__extra_items__'}))
5197 self.assertEqual(ExtraNotRequired.__readonly_keys__, frozenset({}))
5198 self.assertEqual(ExtraNotRequired.__mutable_keys__, frozenset({'__extra_items__'}))
5199 self.assertIs(ExtraNotRequired.__extra_items__, NoExtraItems)
5200 self.assertIsNone(ExtraNotRequired.__closed__)
5201
5202 @skipIf(TYPING_3_14_0, "Only supported on <3.14")
5203 def test_closed_inheritance_legacy(self):
5204 class Base(TypedDict, closed=True):
5205 __extra_items__: ReadOnly[Union[str, None]]
5206
5207 self.assertEqual(Base.__required_keys__, frozenset({}))
5208 self.assertEqual(Base.__optional_keys__, frozenset({}))
5209 self.assertEqual(Base.__readonly_keys__, frozenset({}))
5210 self.assertEqual(Base.__mutable_keys__, frozenset({}))
5211 self.assertEqual(Base.__annotations__, {})
5212 self.assertEqual(Base.__extra_items__, ReadOnly[Union[str, None]])
5213 self.assertIs(Base.__closed__, True)
5214
5215 class Child(Base, closed=True):
5216 a: int
5217 __extra_items__: int
5218
5219 self.assertEqual(Child.__required_keys__, frozenset({'a'}))
5220 self.assertEqual(Child.__optional_keys__, frozenset({}))
5221 self.assertEqual(Child.__readonly_keys__, frozenset({}))
5222 self.assertEqual(Child.__mutable_keys__, frozenset({'a'}))
5223 self.assertEqual(Child.__annotations__, {"a": int})
5224 self.assertIs(Child.__extra_items__, int)
5225 self.assertIs(Child.__closed__, True)
5226
5227 class GrandChild(Child, closed=True):
5228 __extra_items__: str
5229
5230 self.assertEqual(GrandChild.__required_keys__, frozenset({'a'}))
5231 self.assertEqual(GrandChild.__optional_keys__, frozenset({}))
5232 self.assertEqual(GrandChild.__readonly_keys__, frozenset({}))
5233 self.assertEqual(GrandChild.__mutable_keys__, frozenset({'a'}))
5234 self.assertEqual(GrandChild.__annotations__, {"a": int})
5235 self.assertIs(GrandChild.__extra_items__, str)
5236 self.assertIs(GrandChild.__closed__, True)
5237
5238 def test_closed_inheritance(self):
5239 class Base(TypedDict, extra_items=ReadOnly[Union[str, None]]):
5240 a: int
5241
5242 self.assertEqual(Base.__required_keys__, frozenset({"a"}))
5243 self.assertEqual(Base.__optional_keys__, frozenset({}))
5244 self.assertEqual(Base.__readonly_keys__, frozenset({}))
5245 self.assertEqual(Base.__mutable_keys__, frozenset({"a"}))
5246 self.assertEqual(Base.__annotations__, {"a": int})
5247 self.assertEqual(Base.__extra_items__, ReadOnly[Union[str, None]])
5248 self.assertIsNone(Base.__closed__)
5249
5250 class Child(Base, extra_items=int):
5251 a: str
5252
5253 self.assertEqual(Child.__required_keys__, frozenset({'a'}))
5254 self.assertEqual(Child.__optional_keys__, frozenset({}))
5255 self.assertEqual(Child.__readonly_keys__, frozenset({}))
5256 self.assertEqual(Child.__mutable_keys__, frozenset({'a'}))
5257 self.assertEqual(Child.__annotations__, {"a": str})
5258 self.assertIs(Child.__extra_items__, int)
5259 self.assertIsNone(Child.__closed__)
5260
5261 class GrandChild(Child, closed=True):
5262 a: float
5263
5264 self.assertEqual(GrandChild.__required_keys__, frozenset({'a'}))
5265 self.assertEqual(GrandChild.__optional_keys__, frozenset({}))
5266 self.assertEqual(GrandChild.__readonly_keys__, frozenset({}))
5267 self.assertEqual(GrandChild.__mutable_keys__, frozenset({'a'}))
5268 self.assertEqual(GrandChild.__annotations__, {"a": float})
5269 self.assertIs(GrandChild.__extra_items__, NoExtraItems)
5270 self.assertIs(GrandChild.__closed__, True)
5271
5272 class GrandGrandChild(GrandChild):
5273 ...
5274 self.assertEqual(GrandGrandChild.__required_keys__, frozenset({'a'}))
5275 self.assertEqual(GrandGrandChild.__optional_keys__, frozenset({}))
5276 self.assertEqual(GrandGrandChild.__readonly_keys__, frozenset({}))
5277 self.assertEqual(GrandGrandChild.__mutable_keys__, frozenset({'a'}))
5278 self.assertEqual(GrandGrandChild.__annotations__, {"a": float})
5279 self.assertIs(GrandGrandChild.__extra_items__, NoExtraItems)
5280 self.assertIsNone(GrandGrandChild.__closed__)
5281
5282 def test_implicit_extra_items(self):
5283 class Base(TypedDict):
5284 a: int
5285
5286 self.assertIs(Base.__extra_items__, NoExtraItems)
5287 self.assertIsNone(Base.__closed__)
5288
5289 class ChildA(Base, closed=True):
5290 ...
5291
5292 self.assertEqual(ChildA.__extra_items__, NoExtraItems)
5293 self.assertIs(ChildA.__closed__, True)
5294
5295 @skipIf(TYPING_3_14_0, "Backwards compatibility only for Python 3.13")
5296 def test_implicit_extra_items_before_3_14(self):
5297 class Base(TypedDict):
5298 a: int
5299 class ChildB(Base, closed=True):
5300 __extra_items__: None
5301
5302 self.assertIs(ChildB.__extra_items__, type(None))
5303 self.assertIs(ChildB.__closed__, True)
5304
5305 @skipIf(
5306 TYPING_3_13_0,
5307 "The keyword argument alternative to define a "
5308 "TypedDict type using the functional syntax is no longer supported"
5309 )
5310 def test_backwards_compatibility(self):
5311 with self.assertWarns(DeprecationWarning):
5312 TD = TypedDict("TD", closed=int)
5313 self.assertIs(TD.__closed__, None)
5314 self.assertEqual(TD.__annotations__, {"closed": int})
5315
5316 with self.assertWarns(DeprecationWarning):
5317 TD = TypedDict("TD", extra_items=int)
5318 self.assertIs(TD.__extra_items__, NoExtraItems)
5319 self.assertEqual(TD.__annotations__, {"extra_items": int})
5320
5321 def test_cannot_combine_closed_and_extra_items(self):
5322 with self.assertRaisesRegex(
5323 TypeError,
5324 "Cannot combine closed=True and extra_items"
5325 ):
5326 class TD(TypedDict, closed=True, extra_items=range):
5327 x: str
5328
5329 def test_typed_dict_signature(self):
5330 self.assertListEqual(
5331 list(inspect.signature(TypedDict).parameters),
5332 ['typename', 'fields', 'total', 'closed', 'extra_items', 'kwargs']
5333 )
5334
5335 def test_inline_too_many_arguments(self):
5336 with self.assertRaises(TypeError):
5337 TypedDict[{"a": int}, "extra"]
5338
5339 def test_inline_not_a_dict(self):
5340 with self.assertRaises(TypeError):
5341 TypedDict["not_a_dict"]
5342
5343 # a tuple of elements isn't allowed, even if the first element is a dict:
5344 with self.assertRaises(TypeError):
5345 TypedDict[({"key": int},)]
5346
5347 def test_inline_empty(self):
5348 TD = TypedDict[{}]
5349 self.assertIs(TD.__total__, True)
5350 self.assertIs(TD.__closed__, True)
5351 self.assertEqual(TD.__extra_items__, NoExtraItems)
5352 self.assertEqual(TD.__required_keys__, set())
5353 self.assertEqual(TD.__optional_keys__, set())
5354 self.assertEqual(TD.__readonly_keys__, set())
5355 self.assertEqual(TD.__mutable_keys__, set())
5356
5357 def test_inline(self):
5358 TD = TypedDict[{
5359 "a": int,
5360 "b": Required[int],
5361 "c": NotRequired[int],
5362 "d": ReadOnly[int],
5363 }]
5364 self.assertIsSubclass(TD, dict)
5365 self.assertIsSubclass(TD, typing.MutableMapping)
5366 self.assertNotIsSubclass(TD, collections.abc.Sequence)
5367 self.assertTrue(is_typeddict(TD))
5368 self.assertEqual(TD.__name__, "<inline TypedDict>")
5369 self.assertEqual(
5370 TD.__annotations__,
5371 {"a": int, "b": Required[int], "c": NotRequired[int], "d": ReadOnly[int]},
5372 )
5373 self.assertEqual(TD.__module__, __name__)
5374 self.assertEqual(TD.__bases__, (dict,))
5375 self.assertIs(TD.__total__, True)
5376 self.assertIs(TD.__closed__, True)
5377 self.assertEqual(TD.__extra_items__, NoExtraItems)
5378 self.assertEqual(TD.__required_keys__, {"a", "b", "d"})
5379 self.assertEqual(TD.__optional_keys__, {"c"})
5380 self.assertEqual(TD.__readonly_keys__, {"d"})
5381 self.assertEqual(TD.__mutable_keys__, {"a", "b", "c"})
5382
5383 inst = TD(a=1, b=2, d=3)
5384 self.assertIs(type(inst), dict)
5385 self.assertEqual(inst["a"], 1)
5386
5387 def test_annotations(self):
5388 # _type_check is applied
5389 with self.assertRaisesRegex(TypeError, "Plain typing.Optional is not valid as type argument"):
5390 class X(TypedDict):
5391 a: Optional
5392
5393 # _type_convert is applied
5394 class Y(TypedDict):
5395 a: None
5396 b: "int"
5397 if sys.version_info >= (3, 14):
5398 import annotationlib
5399
5400 fwdref = EqualToForwardRef('int', module=__name__)
5401 self.assertEqual(Y.__annotations__, {'a': type(None), 'b': fwdref})
5402 self.assertEqual(Y.__annotate__(annotationlib.Format.FORWARDREF), {'a': type(None), 'b': fwdref})
5403 else:
5404 self.assertEqual(Y.__annotations__, {'a': type(None), 'b': typing.ForwardRef('int', module=__name__)})
5405
5406 @skipUnless(TYPING_3_14_0, "Only supported on 3.14")
5407 def test_delayed_type_check(self):
5408 # _type_check is also applied later
5409 class Z(TypedDict):
5410 a: undefined # noqa: F821
5411
5412 with self.assertRaises(NameError):
5413 Z.__annotations__
5414
5415 undefined = Final
5416 with self.assertRaisesRegex(TypeError, "Plain typing.Final is not valid as type argument"):
5417 Z.__annotations__
5418
5419 undefined = None # noqa: F841
5420 self.assertEqual(Z.__annotations__, {'a': type(None)})
5421
5422 @skipUnless(TYPING_3_14_0, "Only supported on 3.14")
5423 def test_deferred_evaluation(self):
5424 class A(TypedDict):
5425 x: NotRequired[undefined] # noqa: F821
5426 y: ReadOnly[undefined] # noqa: F821
5427 z: Required[undefined] # noqa: F821
5428
5429 self.assertEqual(A.__required_keys__, frozenset({'y', 'z'}))
5430 self.assertEqual(A.__optional_keys__, frozenset({'x'}))
5431 self.assertEqual(A.__readonly_keys__, frozenset({'y'}))
5432 self.assertEqual(A.__mutable_keys__, frozenset({'x', 'z'}))
5433
5434 with self.assertRaises(NameError):
5435 A.__annotations__
5436
5437 import annotationlib
5438 self.assertEqual(
5439 A.__annotate__(annotationlib.Format.STRING),
5440 {'x': 'NotRequired[undefined]', 'y': 'ReadOnly[undefined]',
5441 'z': 'Required[undefined]'},
5442 )
5443
5444 def test_dunder_dict(self):
5445 self.assertIsInstance(TypedDict.__dict__, dict)
5446
5447 @skipUnless(TYPING_3_10_0, "PEP 604 has yet to be")
5448 def test_or(self):
5449 class TD(TypedDict):
5450 a: int
5451
5452 self.assertEqual(TD | int, Union[TD, int])
5453 self.assertEqual(int | TD, Union[int, TD])
5454
5455 self.assertEqual(get_args(TD | int), (TD, int))
5456 self.assertEqual(get_args(int | TD), (int, TD))
5457
5458 class AnnotatedTests(BaseTestCase):
5459
5460 def test_repr(self):
5461 if hasattr(typing, 'Annotated'):
5462 mod_name = 'typing'
5463 else:
5464 mod_name = "typing_extensions"
5465 self.assertEqual(
5466 repr(Annotated[int, 4, 5]),
5467 mod_name + ".Annotated[int, 4, 5]"
5468 )
5469 self.assertEqual(
5470 repr(Annotated[List[int], 4, 5]),
5471 mod_name + ".Annotated[typing.List[int], 4, 5]"
5472 )
5473
5474 def test_flatten(self):
5475 A = Annotated[Annotated[int, 4], 5]
5476 self.assertEqual(A, Annotated[int, 4, 5])
5477 self.assertEqual(A.__metadata__, (4, 5))
5478 self.assertEqual(A.__origin__, int)
5479
5480 def test_specialize(self):
5481 L = Annotated[List[T], "my decoration"]
5482 LI = Annotated[List[int], "my decoration"]
5483 self.assertEqual(L[int], Annotated[List[int], "my decoration"])
5484 self.assertEqual(L[int].__metadata__, ("my decoration",))
5485 self.assertEqual(L[int].__origin__, List[int])
5486 with self.assertRaises(TypeError):
5487 LI[int]
5488 with self.assertRaises(TypeError):
5489 L[int, float]
5490
5491 def test_hash_eq(self):
5492 self.assertEqual(len({Annotated[int, 4, 5], Annotated[int, 4, 5]}), 1)
5493 self.assertNotEqual(Annotated[int, 4, 5], Annotated[int, 5, 4])
5494 self.assertNotEqual(Annotated[int, 4, 5], Annotated[str, 4, 5])
5495 self.assertNotEqual(Annotated[int, 4], Annotated[int, 4, 4])
5496 self.assertEqual(
5497 {Annotated[int, 4, 5], Annotated[int, 4, 5], Annotated[T, 4, 5]},
5498 {Annotated[int, 4, 5], Annotated[T, 4, 5]}
5499 )
5500
5501 def test_instantiate(self):
5502 class C:
5503 classvar = 4
5504
5505 def __init__(self, x):
5506 self.x = x
5507
5508 def __eq__(self, other):
5509 if not isinstance(other, C):
5510 return NotImplemented
5511 return other.x == self.x
5512
5513 A = Annotated[C, "a decoration"]
5514 a = A(5)
5515 c = C(5)
5516 self.assertEqual(a, c)
5517 self.assertEqual(a.x, c.x)
5518 self.assertEqual(a.classvar, c.classvar)
5519
5520 def test_instantiate_generic(self):
5521 MyCount = Annotated[typing_extensions.Counter[T], "my decoration"]
5522 self.assertEqual(MyCount([4, 4, 5]), {4: 2, 5: 1})
5523 self.assertEqual(MyCount[int]([4, 4, 5]), {4: 2, 5: 1})
5524
5525 def test_cannot_instantiate_forward(self):
5526 A = Annotated["int", (5, 6)]
5527 with self.assertRaises(TypeError):
5528 A(5)
5529
5530 def test_cannot_instantiate_type_var(self):
5531 A = Annotated[T, (5, 6)]
5532 with self.assertRaises(TypeError):
5533 A(5)
5534
5535 def test_cannot_getattr_typevar(self):
5536 with self.assertRaises(AttributeError):
5537 Annotated[T, (5, 7)].x
5538
5539 def test_attr_passthrough(self):
5540 class C:
5541 classvar = 4
5542
5543 A = Annotated[C, "a decoration"]
5544 self.assertEqual(A.classvar, 4)
5545 A.x = 5
5546 self.assertEqual(C.x, 5)
5547
5548 @skipIf(sys.version_info[:2] == (3, 10), "Waiting for https://github.com/python/cpython/issues/90649 bugfix.")
5549 def test_special_form_containment(self):
5550 class C:
5551 classvar: Annotated[ClassVar[int], "a decoration"] = 4
5552 const: Annotated[Final[int], "Const"] = 4
5553
5554 self.assertEqual(get_type_hints(C, globals())["classvar"], ClassVar[int])
5555 self.assertEqual(get_type_hints(C, globals())["const"], Final[int])
5556
5557 def test_cannot_subclass(self):
5558 with self.assertRaisesRegex(TypeError, "Cannot subclass .*Annotated"):
5559 class C(Annotated):
5560 pass
5561
5562 def test_cannot_check_instance(self):
5563 with self.assertRaises(TypeError):
5564 isinstance(5, Annotated[int, "positive"])
5565
5566 def test_cannot_check_subclass(self):
5567 with self.assertRaises(TypeError):
5568 issubclass(int, Annotated[int, "positive"])
5569
5570 def test_pickle(self):
5571 samples = [typing.Any, typing.Union[int, str],
5572 typing.Optional[str], Tuple[int, ...],
5573 typing.Callable[[str], bytes],
5574 Self, LiteralString, Never]
5575
5576 for t in samples:
5577 x = Annotated[t, "a"]
5578
5579 for prot in range(pickle.HIGHEST_PROTOCOL + 1):
5580 with self.subTest(protocol=prot, type=t):
5581 pickled = pickle.dumps(x, prot)
5582 restored = pickle.loads(pickled)
5583 self.assertEqual(x, restored)
5584
5585 global _Annotated_test_G
5586
5587 class _Annotated_test_G(Generic[T]):
5588 x = 1
5589
5590 G = Annotated[_Annotated_test_G[int], "A decoration"]
5591 G.foo = 42
5592 G.bar = 'abc'
5593
5594 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
5595 z = pickle.dumps(G, proto)
5596 x = pickle.loads(z)
5597 self.assertEqual(x.foo, 42)
5598 self.assertEqual(x.bar, 'abc')
5599 self.assertEqual(x.x, 1)
5600
5601 def test_subst(self):
5602 dec = "a decoration"
5603 dec2 = "another decoration"
5604
5605 S = Annotated[T, dec2]
5606 self.assertEqual(S[int], Annotated[int, dec2])
5607
5608 self.assertEqual(S[Annotated[int, dec]], Annotated[int, dec, dec2])
5609 L = Annotated[List[T], dec]
5610
5611 self.assertEqual(L[int], Annotated[List[int], dec])
5612 with self.assertRaises(TypeError):
5613 L[int, int]
5614
5615 self.assertEqual(S[L[int]], Annotated[List[int], dec, dec2])
5616
5617 D = Annotated[Dict[KT, VT], dec]
5618 self.assertEqual(D[str, int], Annotated[Dict[str, int], dec])
5619 with self.assertRaises(TypeError):
5620 D[int]
5621
5622 It = Annotated[int, dec]
5623 with self.assertRaises(TypeError):
5624 It[None]
5625
5626 LI = L[int]
5627 with self.assertRaises(TypeError):
5628 LI[None]
5629
5630 def test_annotated_in_other_types(self):
5631 X = List[Annotated[T, 5]]
5632 self.assertEqual(X[int], List[Annotated[int, 5]])
5633
5634 def test_nested_annotated_with_unhashable_metadata(self):
5635 X = Annotated[
5636 List[Annotated[str, {"unhashable_metadata"}]],
5637 "metadata"
5638 ]
5639 self.assertEqual(X.__origin__, List[Annotated[str, {"unhashable_metadata"}]])
5640 self.assertEqual(X.__metadata__, ("metadata",))
5641
5642 def test_compatibility(self):
5643 # Test that the _AnnotatedAlias compatibility alias works
5644 self.assertTrue(hasattr(typing_extensions, "_AnnotatedAlias"))
5645 self.assertIs(typing_extensions._AnnotatedAlias, typing._AnnotatedAlias)
5646
5647
5648 class GetTypeHintsTests(BaseTestCase):
5649 def test_get_type_hints(self):
5650 def foobar(x: List['X']): ...
5651 X = Annotated[int, (1, 10)]
5652 self.assertEqual(
5653 get_type_hints(foobar, globals(), locals()),
5654 {'x': List[int]}
5655 )
5656 self.assertEqual(
5657 get_type_hints(foobar, globals(), locals(), include_extras=True),
5658 {'x': List[Annotated[int, (1, 10)]]}
5659 )
5660 BA = Tuple[Annotated[T, (1, 0)], ...]
5661 def barfoo(x: BA): ...
5662 self.assertEqual(get_type_hints(barfoo, globals(), locals())['x'], Tuple[T, ...])
5663 self.assertIs(
5664 get_type_hints(barfoo, globals(), locals(), include_extras=True)['x'],
5665 BA
5666 )
5667 def barfoo2(x: typing.Callable[..., Annotated[List[T], "const"]],
5668 y: typing.Union[int, Annotated[T, "mutable"]]): ...
5669 self.assertEqual(
5670 get_type_hints(barfoo2, globals(), locals()),
5671 {'x': typing.Callable[..., List[T]], 'y': typing.Union[int, T]}
5672 )
5673 BA2 = typing.Callable[..., List[T]]
5674 def barfoo3(x: BA2): ...
5675 self.assertIs(
5676 get_type_hints(barfoo3, globals(), locals(), include_extras=True)["x"],
5677 BA2
5678 )
5679
5680 @skipUnless(TYPING_3_11_0, "TODO: evaluate nested forward refs in Python < 3.11")
5681 def test_get_type_hints_genericalias(self):
5682 def foobar(x: list['X']): ...
5683 X = Annotated[int, (1, 10)]
5684 self.assertEqual(
5685 get_type_hints(foobar, globals(), locals()),
5686 {'x': list[int]}
5687 )
5688 self.assertEqual(
5689 get_type_hints(foobar, globals(), locals(), include_extras=True),
5690 {'x': list[Annotated[int, (1, 10)]]}
5691 )
5692
5693 def test_get_type_hints_refs(self):
5694
5695 Const = Annotated[T, "Const"]
5696
5697 class MySet(Generic[T]):
5698
5699 def __ior__(self, other: "Const[MySet[T]]") -> "MySet[T]":
5700 ...
5701
5702 def __iand__(self, other: Const["MySet[T]"]) -> "MySet[T]":
5703 ...
5704
5705 self.assertEqual(
5706 get_type_hints(MySet.__iand__, globals(), locals()),
5707 {'other': MySet[T], 'return': MySet[T]}
5708 )
5709
5710 self.assertEqual(
5711 get_type_hints(MySet.__iand__, globals(), locals(), include_extras=True),
5712 {'other': Const[MySet[T]], 'return': MySet[T]}
5713 )
5714
5715 self.assertEqual(
5716 get_type_hints(MySet.__ior__, globals(), locals()),
5717 {'other': MySet[T], 'return': MySet[T]}
5718 )
5719
5720 def test_get_type_hints_typeddict(self):
5721 assert get_type_hints(TotalMovie) == {'title': str, 'year': int}
5722 assert get_type_hints(TotalMovie, include_extras=True) == {
5723 'title': str,
5724 'year': NotRequired[int],
5725 }
5726
5727 assert get_type_hints(AnnotatedMovie) == {'title': str, 'year': int}
5728 assert get_type_hints(AnnotatedMovie, include_extras=True) == {
5729 'title': Annotated[Required[str], "foobar"],
5730 'year': NotRequired[Annotated[int, 2000]],
5731 }
5732
5733 def test_orig_bases(self):
5734 T = TypeVar('T')
5735
5736 class Parent(TypedDict):
5737 pass
5738
5739 class Child(Parent):
5740 pass
5741
5742 class OtherChild(Parent):
5743 pass
5744
5745 class MixedChild(Child, OtherChild, Parent):
5746 pass
5747
5748 class GenericParent(TypedDict, Generic[T]):
5749 pass
5750
5751 class GenericChild(GenericParent[int]):
5752 pass
5753
5754 class OtherGenericChild(GenericParent[str]):
5755 pass
5756
5757 class MixedGenericChild(GenericChild, OtherGenericChild, GenericParent[float]):
5758 pass
5759
5760 class MultipleGenericBases(GenericParent[int], GenericParent[float]):
5761 pass
5762
5763 CallTypedDict = TypedDict('CallTypedDict', {})
5764
5765 self.assertEqual(Parent.__orig_bases__, (TypedDict,))
5766 self.assertEqual(Child.__orig_bases__, (Parent,))
5767 self.assertEqual(OtherChild.__orig_bases__, (Parent,))
5768 self.assertEqual(MixedChild.__orig_bases__, (Child, OtherChild, Parent,))
5769 self.assertEqual(GenericParent.__orig_bases__, (TypedDict, Generic[T]))
5770 self.assertEqual(GenericChild.__orig_bases__, (GenericParent[int],))
5771 self.assertEqual(OtherGenericChild.__orig_bases__, (GenericParent[str],))
5772 self.assertEqual(MixedGenericChild.__orig_bases__, (GenericChild, OtherGenericChild, GenericParent[float]))
5773 self.assertEqual(MultipleGenericBases.__orig_bases__, (GenericParent[int], GenericParent[float]))
5774 self.assertEqual(CallTypedDict.__orig_bases__, (TypedDict,))
5775
5776
5777 class TypeAliasTests(BaseTestCase):
5778 def test_canonical_usage_with_variable_annotation(self):
5779 ns = {}
5780 exec('Alias: TypeAlias = Employee', globals(), ns)
5781
5782 def test_canonical_usage_with_type_comment(self):
5783 Alias: TypeAlias = Employee # noqa: F841
5784
5785 def test_cannot_instantiate(self):
5786 with self.assertRaises(TypeError):
5787 TypeAlias()
5788
5789 def test_no_isinstance(self):
5790 with self.assertRaises(TypeError):
5791 isinstance(42, TypeAlias)
5792
5793 def test_no_issubclass(self):
5794 with self.assertRaises(TypeError):
5795 issubclass(Employee, TypeAlias)
5796
5797 with self.assertRaises(TypeError):
5798 issubclass(TypeAlias, Employee)
5799
5800 def test_cannot_subclass(self):
5801 with self.assertRaises(TypeError):
5802 class C(TypeAlias):
5803 pass
5804
5805 with self.assertRaises(TypeError):
5806 class D(type(TypeAlias)):
5807 pass
5808
5809 def test_repr(self):
5810 if hasattr(typing, 'TypeAlias'):
5811 self.assertEqual(repr(TypeAlias), 'typing.TypeAlias')
5812 else:
5813 self.assertEqual(repr(TypeAlias), 'typing_extensions.TypeAlias')
5814
5815 def test_cannot_subscript(self):
5816 with self.assertRaises(TypeError):
5817 TypeAlias[int]
5818
5819 class ParamSpecTests(BaseTestCase):
5820
5821 def test_basic_plain(self):
5822 P = ParamSpec('P')
5823 self.assertEqual(P, P)
5824 self.assertIsInstance(P, ParamSpec)
5825 self.assertEqual(P.__name__, 'P')
5826 # Should be hashable
5827 hash(P)
5828
5829 def test_repr(self):
5830 P = ParamSpec('P')
5831 P_co = ParamSpec('P_co', covariant=True)
5832 P_contra = ParamSpec('P_contra', contravariant=True)
5833 P_infer = ParamSpec('P_infer', infer_variance=True)
5834 P_2 = ParamSpec('P_2')
5835 self.assertEqual(repr(P), '~P')
5836 self.assertEqual(repr(P_2), '~P_2')
5837
5838 # Note: PEP 612 doesn't require these to be repr-ed correctly, but
5839 # just follow CPython.
5840 self.assertEqual(repr(P_co), '+P_co')
5841 self.assertEqual(repr(P_contra), '-P_contra')
5842 # On other versions we use typing.ParamSpec, but it is not aware of
5843 # infer_variance=. Not worth creating our own version of ParamSpec
5844 # for this.
5845 if hasattr(typing, 'TypeAliasType') or not hasattr(typing, 'ParamSpec'):
5846 self.assertEqual(repr(P_infer), 'P_infer')
5847 else:
5848 self.assertEqual(repr(P_infer), '~P_infer')
5849
5850 def test_variance(self):
5851 P_co = ParamSpec('P_co', covariant=True)
5852 P_contra = ParamSpec('P_contra', contravariant=True)
5853 P_infer = ParamSpec('P_infer', infer_variance=True)
5854
5855 self.assertIs(P_co.__covariant__, True)
5856 self.assertIs(P_co.__contravariant__, False)
5857 self.assertIs(P_co.__infer_variance__, False)
5858
5859 self.assertIs(P_contra.__covariant__, False)
5860 self.assertIs(P_contra.__contravariant__, True)
5861 self.assertIs(P_contra.__infer_variance__, False)
5862
5863 self.assertIs(P_infer.__covariant__, False)
5864 self.assertIs(P_infer.__contravariant__, False)
5865 self.assertIs(P_infer.__infer_variance__, True)
5866
5867 def test_valid_uses(self):
5868 P = ParamSpec('P')
5869 T = TypeVar('T')
5870 C1 = typing.Callable[P, int]
5871 self.assertEqual(C1.__args__, (P, int))
5872 self.assertEqual(C1.__parameters__, (P,))
5873 C2 = typing.Callable[P, T]
5874 self.assertEqual(C2.__args__, (P, T))
5875 self.assertEqual(C2.__parameters__, (P, T))
5876
5877 # Test collections.abc.Callable too.
5878 # Note: no tests for Callable.__parameters__ here
5879 # because types.GenericAlias Callable is hardcoded to search
5880 # for tp_name "TypeVar" in C. This was changed in 3.10.
5881 C3 = collections.abc.Callable[P, int]
5882 self.assertEqual(C3.__args__, (P, int))
5883 C4 = collections.abc.Callable[P, T]
5884 self.assertEqual(C4.__args__, (P, T))
5885
5886 # ParamSpec instances should also have args and kwargs attributes.
5887 # Note: not in dir(P) because of __class__ hacks
5888 self.assertTrue(hasattr(P, 'args'))
5889 self.assertTrue(hasattr(P, 'kwargs'))
5890
5891 @skipIf((3, 10, 0) <= sys.version_info[:3] <= (3, 10, 2), "Needs https://github.com/python/cpython/issues/90834.")
5892 def test_args_kwargs(self):
5893 P = ParamSpec('P')
5894 P_2 = ParamSpec('P_2')
5895 # Note: not in dir(P) because of __class__ hacks
5896 self.assertTrue(hasattr(P, 'args'))
5897 self.assertTrue(hasattr(P, 'kwargs'))
5898 self.assertIsInstance(P.args, ParamSpecArgs)
5899 self.assertIsInstance(P.kwargs, ParamSpecKwargs)
5900 self.assertIs(P.args.__origin__, P)
5901 self.assertIs(P.kwargs.__origin__, P)
5902 self.assertEqual(P.args, P.args)
5903 self.assertEqual(P.kwargs, P.kwargs)
5904 self.assertNotEqual(P.args, P_2.args)
5905 self.assertNotEqual(P.kwargs, P_2.kwargs)
5906 self.assertNotEqual(P.args, P.kwargs)
5907 self.assertNotEqual(P.kwargs, P.args)
5908 self.assertNotEqual(P.args, P_2.kwargs)
5909 self.assertEqual(repr(P.args), "P.args")
5910 self.assertEqual(repr(P.kwargs), "P.kwargs")
5911
5912 def test_user_generics(self):
5913 T = TypeVar("T")
5914 P = ParamSpec("P")
5915 P_2 = ParamSpec("P_2")
5916
5917 class X(Generic[T, P]):
5918 pass
5919
5920 class Y(Protocol[T, P]):
5921 pass
5922
5923 things = "arguments" if sys.version_info >= (3, 10) else "parameters"
5924 for klass in X, Y:
5925 with self.subTest(klass=klass.__name__):
5926 G1 = klass[int, P_2]
5927 self.assertEqual(G1.__args__, (int, P_2))
5928 self.assertEqual(G1.__parameters__, (P_2,))
5929
5930 G2 = klass[int, Concatenate[int, P_2]]
5931 self.assertEqual(G2.__args__, (int, Concatenate[int, P_2]))
5932 self.assertEqual(G2.__parameters__, (P_2,))
5933
5934 G3 = klass[int, Concatenate[int, ...]]
5935 self.assertEqual(G3.__args__, (int, Concatenate[int, ...]))
5936 self.assertEqual(G3.__parameters__, ())
5937
5938 with self.assertRaisesRegex(
5939 TypeError,
5940 f"Too few {things} for {klass}"
5941 ):
5942 klass[int]
5943
5944 # The following are some valid uses cases in PEP 612 that don't work:
5945 # These do not work in 3.9, _type_check blocks the list and ellipsis.
5946 # G3 = X[int, [int, bool]]
5947 # G4 = X[int, ...]
5948 # G5 = Z[[int, str, bool]]
5949
5950 def test_single_argument_generic(self):
5951 P = ParamSpec("P")
5952 T = TypeVar("T")
5953 P_2 = ParamSpec("P_2")
5954
5955 class Z(Generic[P]):
5956 pass
5957
5958 class ProtoZ(Protocol[P]):
5959 pass
5960
5961 for klass in Z, ProtoZ:
5962 with self.subTest(klass=klass.__name__):
5963 # Note: For 3.10+ __args__ are nested tuples here ((int, ),) instead of (int, )
5964 G6 = klass[int, str, T]
5965 G6args = G6.__args__[0] if sys.version_info >= (3, 10) else G6.__args__
5966 self.assertEqual(G6args, (int, str, T))
5967 self.assertEqual(G6.__parameters__, (T,))
5968
5969 # P = [int]
5970 G7 = klass[int]
5971 G7args = G7.__args__[0] if sys.version_info >= (3, 10) else G7.__args__
5972 self.assertEqual(G7args, (int,))
5973 self.assertEqual(G7.__parameters__, ())
5974
5975 G8 = klass[Concatenate[T, ...]]
5976 self.assertEqual(G8.__args__, (Concatenate[T, ...], ))
5977 self.assertEqual(G8.__parameters__, (T,))
5978
5979 G9 = klass[Concatenate[T, P_2]]
5980 self.assertEqual(G9.__args__, (Concatenate[T, P_2], ))
5981
5982 # This is an invalid form but useful for testing correct subsitution
5983 G10 = klass[int, Concatenate[str, P]]
5984 G10args = G10.__args__[0] if sys.version_info >= (3, 10) else G10.__args__
5985 self.assertEqual(G10args, (int, Concatenate[str, P], ))
5986
5987 @skipUnless(TYPING_3_10_0, "ParamSpec not present before 3.10")
5988 def test_is_param_expr(self):
5989 P = ParamSpec("P")
5990 P_typing = typing.ParamSpec("P_typing")
5991 self.assertTrue(typing_extensions._is_param_expr(P))
5992 self.assertTrue(typing_extensions._is_param_expr(P_typing))
5993 if hasattr(typing, "_is_param_expr"):
5994 self.assertTrue(typing._is_param_expr(P))
5995 self.assertTrue(typing._is_param_expr(P_typing))
5996
5997 def test_single_argument_generic_with_parameter_expressions(self):
5998 P = ParamSpec("P")
5999 T = TypeVar("T")
6000 P_2 = ParamSpec("P_2")
6001
6002 class Z(Generic[P]):
6003 pass
6004
6005 class ProtoZ(Protocol[P]):
6006 pass
6007
6008 things = "arguments" if sys.version_info >= (3, 10) else "parameters"
6009 for klass in Z, ProtoZ:
6010 with self.subTest(klass=klass.__name__):
6011 G8 = klass[Concatenate[T, ...]]
6012
6013 H8_1 = G8[int]
6014 self.assertEqual(H8_1.__parameters__, ())
6015 with self.assertRaisesRegex(TypeError, "not a generic class"):
6016 H8_1[str]
6017
6018 H8_2 = G8[T][int]
6019 self.assertEqual(H8_2.__parameters__, ())
6020 with self.assertRaisesRegex(TypeError, "not a generic class"):
6021 H8_2[str]
6022
6023 G9 = klass[Concatenate[T, P_2]]
6024 self.assertEqual(G9.__parameters__, (T, P_2))
6025
6026 with self.assertRaisesRegex(TypeError,
6027 "The last parameter to Concatenate should be a ParamSpec variable or ellipsis."
6028 if sys.version_info < (3, 10) else
6029 # from __typing_subst__
6030 "Expected a list of types, an ellipsis, ParamSpec, or Concatenate"
6031 ):
6032 G9[int, int]
6033
6034 with self.assertRaisesRegex(TypeError, f"Too few {things}"):
6035 G9[int]
6036
6037 with self.subTest("Check list as parameter expression", klass=klass.__name__):
6038 if sys.version_info < (3, 10):
6039 self.skipTest("Cannot pass non-types")
6040 G5 = klass[[int, str, T]]
6041 self.assertEqual(G5.__parameters__, (T,))
6042 self.assertEqual(G5.__args__, ((int, str, T),))
6043
6044 H9 = G9[int, [T]]
6045 self.assertEqual(H9.__parameters__, (T,))
6046
6047 # This is an invalid parameter expression but useful for testing correct subsitution
6048 G10 = klass[int, Concatenate[str, P]]
6049 with self.subTest("Check invalid form substitution"):
6050 self.assertEqual(G10.__parameters__, (P, ))
6051 H10 = G10[int]
6052 if (3, 10) <= sys.version_info < (3, 11, 3):
6053 self.skipTest("3.10-3.11.2 does not substitute Concatenate here")
6054 self.assertEqual(H10.__parameters__, ())
6055 H10args = H10.__args__[0] if sys.version_info >= (3, 10) else H10.__args__
6056 self.assertEqual(H10args, (int, (str, int)))
6057
6058 @skipUnless(TYPING_3_10_0, "ParamSpec not present before 3.10")
6059 def test_substitution_with_typing_variants(self):
6060 # verifies substitution and typing._check_generic working with typing variants
6061 P = ParamSpec("P")
6062 typing_P = typing.ParamSpec("typing_P")
6063 typing_Concatenate = typing.Concatenate[int, P]
6064
6065 class Z(Generic[typing_P]):
6066 pass
6067
6068 P1 = Z[typing_P]
6069 self.assertEqual(P1.__parameters__, (typing_P,))
6070 self.assertEqual(P1.__args__, (typing_P,))
6071
6072 C1 = Z[typing_Concatenate]
6073 self.assertEqual(C1.__parameters__, (P,))
6074 self.assertEqual(C1.__args__, (typing_Concatenate,))
6075
6076 def test_pickle(self):
6077 global P, P_co, P_contra, P_default
6078 P = ParamSpec('P')
6079 P_co = ParamSpec('P_co', covariant=True)
6080 P_contra = ParamSpec('P_contra', contravariant=True)
6081 P_default = ParamSpec('P_default', default=[int])
6082 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
6083 with self.subTest(f'Pickle protocol {proto}'):
6084 for paramspec in (P, P_co, P_contra, P_default):
6085 z = pickle.loads(pickle.dumps(paramspec, proto))
6086 self.assertEqual(z.__name__, paramspec.__name__)
6087 self.assertEqual(z.__covariant__, paramspec.__covariant__)
6088 self.assertEqual(z.__contravariant__, paramspec.__contravariant__)
6089 self.assertEqual(z.__bound__, paramspec.__bound__)
6090 self.assertEqual(z.__default__, paramspec.__default__)
6091
6092 def test_eq(self):
6093 P = ParamSpec('P')
6094 self.assertEqual(P, P)
6095 self.assertEqual(hash(P), hash(P))
6096 # ParamSpec should compare by id similar to TypeVar in CPython
6097 self.assertNotEqual(ParamSpec('P'), P)
6098 self.assertIsNot(ParamSpec('P'), P)
6099 # Note: normally you don't test this as it breaks when there's
6100 # a hash collision. However, ParamSpec *must* guarantee that
6101 # as long as two objects don't have the same ID, their hashes
6102 # won't be the same.
6103 self.assertNotEqual(hash(ParamSpec('P')), hash(P))
6104
6105 def test_isinstance_results_unaffected_by_presence_of_tracing_function(self):
6106 # See https://github.com/python/typing_extensions/issues/318
6107
6108 code = textwrap.dedent(
6109 """\
6110 import sys, typing
6111
6112 def trace_call(*args):
6113 return trace_call
6114
6115 def run():
6116 sys.modules.pop("typing_extensions", None)
6117 from typing_extensions import ParamSpec
6118 return isinstance(ParamSpec("P"), typing.TypeVar)
6119
6120 isinstance_result_1 = run()
6121 sys.setprofile(trace_call)
6122 isinstance_result_2 = run()
6123 sys.stdout.write(f"{isinstance_result_1} {isinstance_result_2}")
6124 """
6125 )
6126
6127 # Run this in an isolated process or it pollutes the environment
6128 # and makes other tests fail:
6129 try:
6130 proc = subprocess.run(
6131 [sys.executable, "-c", code], check=True, capture_output=True, text=True,
6132 )
6133 except subprocess.CalledProcessError as exc: # pragma: no cover
6134 print("stdout", exc.stdout, sep="\n")
6135 print("stderr", exc.stderr, sep="\n")
6136 raise
6137
6138 # Sanity checks that assert the test is working as expected
6139 self.assertIsInstance(proc.stdout, str)
6140 result1, result2 = proc.stdout.split(" ")
6141 self.assertIn(result1, {"True", "False"})
6142 self.assertIn(result2, {"True", "False"})
6143
6144 # The actual test:
6145 self.assertEqual(result1, result2)
6146
6147 def test_subclass(self):
6148 with self.assertRaises(TypeError):
6149 class MyParamSpec(ParamSpec):
6150 pass
6151
6152
6153 class ConcatenateTests(BaseTestCase):
6154 def test_basics(self):
6155 P = ParamSpec('P')
6156
6157 class MyClass: ...
6158
6159 c = Concatenate[MyClass, P]
6160 self.assertNotEqual(c, Concatenate)
6161
6162 # Test Ellipsis Concatenation
6163 d = Concatenate[MyClass, ...]
6164 self.assertNotEqual(d, c)
6165 self.assertNotEqual(d, Concatenate)
6166
6167 @skipUnless(TYPING_3_10_0, "Concatenate not available in <3.10")
6168 def test_typing_compatibility(self):
6169 P = ParamSpec('P')
6170 C1 = Concatenate[int, P][typing.Concatenate[int, P]]
6171 self.assertEqual(C1, Concatenate[int, int, P])
6172 self.assertEqual(get_args(C1), (int, int, P))
6173
6174 C2 = typing.Concatenate[int, P][Concatenate[int, P]]
6175 with self.subTest("typing compatibility with typing_extensions"):
6176 if sys.version_info < (3, 10, 3):
6177 self.skipTest("Unpacking not introduced until 3.10.3")
6178 self.assertEqual(get_args(C2), (int, int, P))
6179
6180 def test_valid_uses(self):
6181 P = ParamSpec('P')
6182 T = TypeVar('T')
6183 for callable_variant in (Callable, collections.abc.Callable):
6184 with self.subTest(callable_variant=callable_variant):
6185 C1 = callable_variant[Concatenate[int, P], int]
6186 C2 = callable_variant[Concatenate[int, T, P], T]
6187 self.assertEqual(C1.__origin__, C2.__origin__)
6188 self.assertNotEqual(C1, C2)
6189
6190 C3 = callable_variant[Concatenate[int, ...], int]
6191 C4 = callable_variant[Concatenate[int, T, ...], T]
6192 self.assertEqual(C3.__origin__, C4.__origin__)
6193 self.assertNotEqual(C3, C4)
6194
6195 def test_invalid_uses(self):
6196 P = ParamSpec('P')
6197 T = TypeVar('T')
6198
6199 with self.assertRaisesRegex(
6200 TypeError,
6201 'Cannot take a Concatenate of no types',
6202 ):
6203 Concatenate[()]
6204
6205 with self.assertRaisesRegex(
6206 TypeError,
6207 'The last parameter to Concatenate should be a ParamSpec variable or ellipsis',
6208 ):
6209 Concatenate[P, T]
6210
6211 # Test with tuple argument
6212 with self.assertRaisesRegex(
6213 TypeError,
6214 "The last parameter to Concatenate should be a ParamSpec variable or ellipsis.",
6215 ):
6216 Concatenate[(P, T)]
6217
6218 with self.assertRaisesRegex(
6219 TypeError,
6220 'is not a generic class',
6221 ):
6222 Callable[Concatenate[int, ...], Any][Any]
6223
6224 # Assure that `_type_check` is called.
6225 P = ParamSpec('P')
6226 with self.assertRaisesRegex(
6227 TypeError,
6228 "each arg must be a type",
6229 ):
6230 Concatenate[(str,), P]
6231
6232 @skipUnless(TYPING_3_10_0, "Missing backport to 3.9. See issue #48")
6233 def test_alias_subscription_with_ellipsis(self):
6234 P = ParamSpec('P')
6235 X = Callable[Concatenate[int, P], Any]
6236
6237 C1 = X[...]
6238 self.assertEqual(C1.__parameters__, ())
6239 self.assertEqual(get_args(C1), (Concatenate[int, ...], Any))
6240
6241 def test_basic_introspection(self):
6242 P = ParamSpec('P')
6243 C1 = Concatenate[int, P]
6244 C2 = Concatenate[int, T, P]
6245 C3 = Concatenate[int, ...]
6246 C4 = Concatenate[int, T, ...]
6247 self.assertEqual(C1.__origin__, Concatenate)
6248 self.assertEqual(C1.__args__, (int, P))
6249 self.assertEqual(C2.__origin__, Concatenate)
6250 self.assertEqual(C2.__args__, (int, T, P))
6251 self.assertEqual(C3.__origin__, Concatenate)
6252 self.assertEqual(C3.__args__, (int, Ellipsis))
6253 self.assertEqual(C4.__origin__, Concatenate)
6254 self.assertEqual(C4.__args__, (int, T, Ellipsis))
6255
6256 def test_eq(self):
6257 P = ParamSpec('P')
6258 C1 = Concatenate[int, P]
6259 C2 = Concatenate[int, P]
6260 C3 = Concatenate[int, T, P]
6261 self.assertEqual(C1, C2)
6262 self.assertEqual(hash(C1), hash(C2))
6263 self.assertNotEqual(C1, C3)
6264
6265 C4 = Concatenate[int, ...]
6266 C5 = Concatenate[int, ...]
6267 C6 = Concatenate[int, T, ...]
6268 self.assertEqual(C4, C5)
6269 self.assertEqual(hash(C4), hash(C5))
6270 self.assertNotEqual(C4, C6)
6271
6272 def test_substitution(self):
6273 T = TypeVar('T')
6274 P = ParamSpec('P')
6275 Ts = TypeVarTuple("Ts")
6276
6277 C1 = Concatenate[str, T, ...]
6278 self.assertEqual(C1[int], Concatenate[str, int, ...])
6279
6280 C2 = Concatenate[str, P]
6281 self.assertEqual(C2[...], Concatenate[str, ...])
6282 self.assertEqual(C2[int], (str, int))
6283 U1 = Unpack[Tuple[int, str]]
6284 U2 = Unpack[Ts]
6285 self.assertEqual(C2[U1], (str, int, str))
6286 self.assertEqual(C2[U2], (str, Unpack[Ts]))
6287 self.assertEqual(C2["U2"], (str, EqualToForwardRef("U2")))
6288
6289 if (3, 12, 0) <= sys.version_info < (3, 12, 4):
6290 with self.assertRaises(AssertionError):
6291 C2[Unpack[U2]]
6292 else:
6293 with self.assertRaisesRegex(TypeError, "must be used with a tuple type"):
6294 C2[Unpack[U2]]
6295
6296 C3 = Concatenate[str, T, P]
6297 self.assertEqual(C3[int, [bool]], (str, int, bool))
6298
6299 @skipUnless(TYPING_3_10_0, "Concatenate not present before 3.10")
6300 def test_is_param_expr(self):
6301 P = ParamSpec('P')
6302 concat = Concatenate[str, P]
6303 typing_concat = typing.Concatenate[str, P]
6304 self.assertTrue(typing_extensions._is_param_expr(concat))
6305 self.assertTrue(typing_extensions._is_param_expr(typing_concat))
6306 if hasattr(typing, "_is_param_expr"):
6307 self.assertTrue(typing._is_param_expr(concat))
6308 self.assertTrue(typing._is_param_expr(typing_concat))
6309
6310 def test_isinstance_results_unaffected_by_presence_of_tracing_function(self):
6311 # See https://github.com/python/typing_extensions/issues/661
6312
6313 code = textwrap.dedent(
6314 """\
6315 import sys, typing
6316
6317 def trace_call(*args):
6318 return trace_call
6319
6320 def run():
6321 sys.modules.pop("typing_extensions", None)
6322 from typing_extensions import Concatenate
6323 return isinstance(Concatenate[...], typing._GenericAlias)
6324 isinstance_result_1 = run()
6325 sys.setprofile(trace_call)
6326 isinstance_result_2 = run()
6327 sys.stdout.write(f"{isinstance_result_1} {isinstance_result_2}")
6328 """
6329 )
6330
6331 # Run this in an isolated process or it pollutes the environment
6332 # and makes other tests fail:
6333 try:
6334 proc = subprocess.run(
6335 [sys.executable, "-c", code], check=True, capture_output=True, text=True,
6336 )
6337 except subprocess.CalledProcessError as exc:
6338 print("stdout", exc.stdout, sep="\n")
6339 print("stderr", exc.stderr, sep="\n")
6340 raise
6341
6342 # Sanity checks that assert the test is working as expected
6343 self.assertIsInstance(proc.stdout, str)
6344 result1, result2 = proc.stdout.split(" ")
6345 self.assertIn(result1, {"True", "False"})
6346 self.assertIn(result2, {"True", "False"})
6347
6348 # The actual test:
6349 self.assertEqual(result1, result2)
6350
6351 class TypeGuardTests(BaseTestCase):
6352 def test_basics(self):
6353 TypeGuard[int] # OK
6354 self.assertEqual(TypeGuard[int], TypeGuard[int])
6355
6356 def foo(arg) -> TypeGuard[int]: ...
6357 self.assertEqual(gth(foo), {'return': TypeGuard[int]})
6358
6359 def test_repr(self):
6360 if hasattr(typing, 'TypeGuard'):
6361 mod_name = 'typing'
6362 else:
6363 mod_name = 'typing_extensions'
6364 self.assertEqual(repr(TypeGuard), f'{mod_name}.TypeGuard')
6365 cv = TypeGuard[int]
6366 self.assertEqual(repr(cv), f'{mod_name}.TypeGuard[int]')
6367 cv = TypeGuard[Employee]
6368 self.assertEqual(repr(cv), f'{mod_name}.TypeGuard[{__name__}.Employee]')
6369 cv = TypeGuard[Tuple[int]]
6370 self.assertEqual(repr(cv), f'{mod_name}.TypeGuard[typing.Tuple[int]]')
6371
6372 def test_cannot_subclass(self):
6373 with self.assertRaises(TypeError):
6374 class C(type(TypeGuard)):
6375 pass
6376 with self.assertRaises(TypeError):
6377 class D(type(TypeGuard[int])):
6378 pass
6379
6380 def test_cannot_init(self):
6381 with self.assertRaises(TypeError):
6382 TypeGuard()
6383 with self.assertRaises(TypeError):
6384 type(TypeGuard)()
6385 with self.assertRaises(TypeError):
6386 type(TypeGuard[Optional[int]])()
6387
6388 def test_no_isinstance(self):
6389 with self.assertRaises(TypeError):
6390 isinstance(1, TypeGuard[int])
6391 with self.assertRaises(TypeError):
6392 issubclass(int, TypeGuard)
6393
6394
6395 class TypeIsTests(BaseTestCase):
6396 def test_basics(self):
6397 TypeIs[int] # OK
6398 self.assertEqual(TypeIs[int], TypeIs[int])
6399
6400 def foo(arg) -> TypeIs[int]: ...
6401 self.assertEqual(gth(foo), {'return': TypeIs[int]})
6402
6403 def test_repr(self):
6404 if hasattr(typing, 'TypeIs'):
6405 mod_name = 'typing'
6406 else:
6407 mod_name = 'typing_extensions'
6408 self.assertEqual(repr(TypeIs), f'{mod_name}.TypeIs')
6409 cv = TypeIs[int]
6410 self.assertEqual(repr(cv), f'{mod_name}.TypeIs[int]')
6411 cv = TypeIs[Employee]
6412 self.assertEqual(repr(cv), f'{mod_name}.TypeIs[{__name__}.Employee]')
6413 cv = TypeIs[Tuple[int]]
6414 self.assertEqual(repr(cv), f'{mod_name}.TypeIs[typing.Tuple[int]]')
6415
6416 def test_cannot_subclass(self):
6417 with self.assertRaises(TypeError):
6418 class C(type(TypeIs)):
6419 pass
6420 with self.assertRaises(TypeError):
6421 class D(type(TypeIs[int])):
6422 pass
6423
6424 def test_cannot_init(self):
6425 with self.assertRaises(TypeError):
6426 TypeIs()
6427 with self.assertRaises(TypeError):
6428 type(TypeIs)()
6429 with self.assertRaises(TypeError):
6430 type(TypeIs[Optional[int]])()
6431
6432 def test_no_isinstance(self):
6433 with self.assertRaises(TypeError):
6434 isinstance(1, TypeIs[int])
6435 with self.assertRaises(TypeError):
6436 issubclass(int, TypeIs)
6437
6438
6439 class TypeFormTests(BaseTestCase):
6440 def test_basics(self):
6441 TypeForm[int] # OK
6442 self.assertEqual(TypeForm[int], TypeForm[int])
6443
6444 def foo(arg) -> TypeForm[int]: ...
6445 self.assertEqual(gth(foo), {'return': TypeForm[int]})
6446
6447 def test_repr(self):
6448 if hasattr(typing, 'TypeForm'):
6449 mod_name = 'typing'
6450 else:
6451 mod_name = 'typing_extensions'
6452 self.assertEqual(repr(TypeForm), f'{mod_name}.TypeForm')
6453 cv = TypeForm[int]
6454 self.assertEqual(repr(cv), f'{mod_name}.TypeForm[int]')
6455 cv = TypeForm[Employee]
6456 self.assertEqual(repr(cv), f'{mod_name}.TypeForm[{__name__}.Employee]')
6457 cv = TypeForm[Tuple[int]]
6458 self.assertEqual(repr(cv), f'{mod_name}.TypeForm[typing.Tuple[int]]')
6459
6460 def test_cannot_subclass(self):
6461 with self.assertRaises(TypeError):
6462 class C(type(TypeForm)):
6463 pass
6464 with self.assertRaises(TypeError):
6465 class D(type(TypeForm[int])):
6466 pass
6467
6468 def test_call(self):
6469 objs = [
6470 1,
6471 "int",
6472 int,
6473 Tuple[int, str],
6474 ]
6475 for obj in objs:
6476 with self.subTest(obj=obj):
6477 self.assertIs(TypeForm(obj), obj)
6478
6479 with self.assertRaises(TypeError):
6480 TypeForm()
6481 with self.assertRaises(TypeError):
6482 TypeForm("too", "many")
6483
6484 def test_cannot_init_type(self):
6485 with self.assertRaises(TypeError):
6486 type(TypeForm)()
6487 with self.assertRaises(TypeError):
6488 type(TypeForm[Optional[int]])()
6489
6490 def test_no_isinstance(self):
6491 with self.assertRaises(TypeError):
6492 isinstance(1, TypeForm[int])
6493 with self.assertRaises(TypeError):
6494 issubclass(int, TypeForm)
6495
6496
6497 class LiteralStringTests(BaseTestCase):
6498 def test_basics(self):
6499 class Foo:
6500 def bar(self) -> LiteralString: ...
6501 def baz(self) -> "LiteralString": ...
6502
6503 self.assertEqual(gth(Foo.bar), {'return': LiteralString})
6504 self.assertEqual(gth(Foo.baz), {'return': LiteralString})
6505
6506 def test_get_origin(self):
6507 self.assertIsNone(get_origin(LiteralString))
6508
6509 def test_repr(self):
6510 if hasattr(typing, 'LiteralString'):
6511 mod_name = 'typing'
6512 else:
6513 mod_name = 'typing_extensions'
6514 self.assertEqual(repr(LiteralString), f'{mod_name}.LiteralString')
6515
6516 def test_cannot_subscript(self):
6517 with self.assertRaises(TypeError):
6518 LiteralString[int]
6519
6520 def test_cannot_subclass(self):
6521 with self.assertRaises(TypeError):
6522 class C(type(LiteralString)):
6523 pass
6524 with self.assertRaises(TypeError):
6525 class D(LiteralString):
6526 pass
6527
6528 def test_cannot_init(self):
6529 with self.assertRaises(TypeError):
6530 LiteralString()
6531 with self.assertRaises(TypeError):
6532 type(LiteralString)()
6533
6534 def test_no_isinstance(self):
6535 with self.assertRaises(TypeError):
6536 isinstance(1, LiteralString)
6537 with self.assertRaises(TypeError):
6538 issubclass(int, LiteralString)
6539
6540 def test_alias(self):
6541 StringTuple = Tuple[LiteralString, LiteralString]
6542 class Alias:
6543 def return_tuple(self) -> StringTuple:
6544 return ("foo", "pep" + "675") # pragma: no cover
6545
6546 def test_typevar(self):
6547 StrT = TypeVar("StrT", bound=LiteralString)
6548 self.assertIs(StrT.__bound__, LiteralString)
6549
6550 def test_pickle(self):
6551 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
6552 pickled = pickle.dumps(LiteralString, protocol=proto)
6553 self.assertIs(LiteralString, pickle.loads(pickled))
6554
6555 @skipUnless(TYPING_3_10_0, "PEP 604 has yet to be")
6556 def test_or(self):
6557 self.assertEqual(LiteralString | int, Union[LiteralString, int])
6558 self.assertEqual(int | LiteralString, Union[int, LiteralString])
6559
6560 self.assertEqual(get_args(LiteralString | int), (LiteralString, int))
6561 self.assertEqual(get_args(int | LiteralString), (int, LiteralString))
6562
6563
6564 class SelfTests(BaseTestCase):
6565 def test_basics(self):
6566 class Foo:
6567 def bar(self) -> Self: ...
6568
6569 self.assertEqual(gth(Foo.bar), {'return': Self})
6570
6571 def test_repr(self):
6572 if hasattr(typing, 'Self'):
6573 mod_name = 'typing'
6574 else:
6575 mod_name = 'typing_extensions'
6576 self.assertEqual(repr(Self), f'{mod_name}.Self')
6577
6578 def test_cannot_subscript(self):
6579 with self.assertRaises(TypeError):
6580 Self[int]
6581
6582 def test_cannot_subclass(self):
6583 with self.assertRaises(TypeError):
6584 class C(type(Self)):
6585 pass
6586
6587 def test_cannot_init(self):
6588 with self.assertRaises(TypeError):
6589 Self()
6590 with self.assertRaises(TypeError):
6591 type(Self)()
6592
6593 def test_no_isinstance(self):
6594 with self.assertRaises(TypeError):
6595 isinstance(1, Self)
6596 with self.assertRaises(TypeError):
6597 issubclass(int, Self)
6598
6599 def test_alias(self):
6600 TupleSelf = Tuple[Self, Self]
6601 class Alias:
6602 def return_tuple(self) -> TupleSelf:
6603 return (self, self) # pragma: no cover
6604
6605 def test_pickle(self):
6606 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
6607 pickled = pickle.dumps(Self, protocol=proto)
6608 self.assertIs(Self, pickle.loads(pickled))
6609
6610 @skipUnless(TYPING_3_10_0, "PEP 604 has yet to be")
6611 def test_or(self):
6612 self.assertEqual(Self | int, Union[Self, int])
6613 self.assertEqual(int | Self, Union[int, Self])
6614
6615 self.assertEqual(get_args(Self | int), (Self, int))
6616 self.assertEqual(get_args(int | Self), (int, Self))
6617
6618
6619 class UnpackTests(BaseTestCase):
6620 def test_basic_plain(self):
6621 Ts = TypeVarTuple('Ts')
6622 self.assertEqual(Unpack[Ts], Unpack[Ts])
6623 with self.assertRaises(TypeError):
6624 Unpack()
6625
6626 @skipIf(GOOD_TYPEVARTUPLE_REPR_EXPECTED, "TypeVarTuples have a bad repr on this version")
6627 def test_repr(self):
6628 Ts = TypeVarTuple('Ts')
6629 self.assertEqual(repr(Unpack[Ts]), f'{Unpack.__module__}.Unpack[Ts]')
6630
6631 @skipUnless(GOOD_TYPEVARTUPLE_REPR_EXPECTED, "TypeVarTuples have a bad repr on this version")
6632 def test_repr_py315(self):
6633 Ts = TypeVarTuple('Ts')
6634 self.assertEqual(repr(Unpack[Ts]), f'{Unpack.__module__}.Unpack[~Ts]')
6635
6636 def test_cannot_subclass_vars(self):
6637 with self.assertRaises(TypeError):
6638 class V(Unpack[TypeVarTuple('Ts')]):
6639 pass
6640
6641 def test_tuple(self):
6642 Ts = TypeVarTuple('Ts')
6643 Tuple[Unpack[Ts]]
6644
6645 def test_union(self):
6646 Xs = TypeVarTuple('Xs')
6647 Ys = TypeVarTuple('Ys')
6648 self.assertEqual(
6649 Union[Unpack[Xs]],
6650 Unpack[Xs]
6651 )
6652 self.assertNotEqual(
6653 Union[Unpack[Xs]],
6654 Union[Unpack[Xs], Unpack[Ys]]
6655 )
6656 self.assertEqual(
6657 Union[Unpack[Xs], Unpack[Xs]],
6658 Unpack[Xs]
6659 )
6660 self.assertNotEqual(
6661 Union[Unpack[Xs], int],
6662 Union[Unpack[Xs]]
6663 )
6664 self.assertNotEqual(
6665 Union[Unpack[Xs], int],
6666 Union[int]
6667 )
6668 self.assertEqual(
6669 Union[Unpack[Xs], int].__args__,
6670 (Unpack[Xs], int)
6671 )
6672 self.assertEqual(
6673 Union[Unpack[Xs], int].__parameters__,
6674 (Xs,)
6675 )
6676 self.assertIs(
6677 Union[Unpack[Xs], int].__origin__,
6678 Union
6679 )
6680
6681 def test_concatenation(self):
6682 Xs = TypeVarTuple('Xs')
6683 self.assertEqual(Tuple[int, Unpack[Xs]].__args__, (int, Unpack[Xs]))
6684 self.assertEqual(Tuple[Unpack[Xs], int].__args__, (Unpack[Xs], int))
6685 self.assertEqual(Tuple[int, Unpack[Xs], str].__args__,
6686 (int, Unpack[Xs], str))
6687 class C(Generic[Unpack[Xs]]): pass
6688 class D(Protocol[Unpack[Xs]]): pass
6689 for klass in C, D:
6690 with self.subTest(klass=klass.__name__):
6691 self.assertEqual(klass[int, Unpack[Xs]].__args__, (int, Unpack[Xs]))
6692 self.assertEqual(klass[Unpack[Xs], int].__args__, (Unpack[Xs], int))
6693 self.assertEqual(klass[int, Unpack[Xs], str].__args__,
6694 (int, Unpack[Xs], str))
6695
6696 def test_class(self):
6697 Ts = TypeVarTuple('Ts')
6698
6699 class C(Generic[Unpack[Ts]]): pass
6700 class D(Protocol[Unpack[Ts]]): pass
6701
6702 for klass in C, D:
6703 with self.subTest(klass=klass.__name__):
6704 self.assertEqual(klass[int].__args__, (int,))
6705 self.assertEqual(klass[int, str].__args__, (int, str))
6706
6707 with self.assertRaises(TypeError):
6708 class C(Generic[Unpack[Ts], int]): pass
6709
6710 with self.assertRaises(TypeError):
6711 class D(Protocol[Unpack[Ts], int]): pass
6712
6713 T1 = TypeVar('T')
6714 T2 = TypeVar('T')
6715 class C(Generic[T1, T2, Unpack[Ts]]): pass
6716 class D(Protocol[T1, T2, Unpack[Ts]]): pass
6717 for klass in C, D:
6718 with self.subTest(klass=klass.__name__):
6719 self.assertEqual(klass[int, str].__args__, (int, str))
6720 self.assertEqual(klass[int, str, float].__args__, (int, str, float))
6721 self.assertEqual(
6722 klass[int, str, float, bool].__args__, (int, str, float, bool)
6723 )
6724 # A bug was fixed in 3.11.1
6725 # (https://github.com/python/cpython/commit/74920aa27d0c57443dd7f704d6272cca9c507ab3)
6726 # That means this assertion doesn't pass on 3.11.0,
6727 # but it passes on all other Python versions
6728 if sys.version_info[:3] != (3, 11, 0):
6729 with self.assertRaises(TypeError):
6730 klass[int]
6731
6732 def test_substitution(self):
6733 Ts = TypeVarTuple("Ts")
6734 unpacked_str = Unpack[Ts][str] # This should not raise an error
6735 self.assertIs(unpacked_str, str)
6736
6737 @skipUnless(TYPING_3_11_0, "Needs Issue #103 for <3.11")
6738 def test_nested_unpack(self):
6739 Ts = TypeVarTuple("Ts")
6740 Variadic = Tuple[int, Unpack[Ts]]
6741 # Tuple[int, int, Tuple[str, int]]
6742 direct_subscription = Variadic[int, Tuple[str, int]]
6743 # Tuple[int, int, Tuple[*Ts, int]]
6744 TupleAliasTs = Variadic[int, Tuple[Unpack[Ts], int]]
6745
6746 # Tuple[int, int, Tuple[str, int]]
6747 recursive_unpack = TupleAliasTs[str]
6748 self.assertEqual(direct_subscription, recursive_unpack)
6749 self.assertEqual(get_args(recursive_unpack), (int, int, Tuple[str, int]))
6750
6751 # Test with Callable
6752 T = TypeVar("T")
6753 # Tuple[int, (*Ts) -> T]
6754 CallableAliasTsT = Variadic[Callable[[Unpack[Ts]], T]]
6755 # Tuple[int, (str, int) -> object]
6756 callable_fully_subscripted = CallableAliasTsT[Unpack[Tuple[str, int]], object]
6757 self.assertEqual(get_args(callable_fully_subscripted), (int, Callable[[str, int], object]))
6758
6759 @skipUnless(TYPING_3_11_0, "Needs Issue #103 for <3.11")
6760 def test_equivalent_nested_variadics(self):
6761 T = TypeVar("T")
6762 Ts = TypeVarTuple("Ts")
6763 Variadic = Tuple[int, Unpack[Ts]]
6764 TupleAliasTsT = Variadic[Tuple[Unpack[Ts], T]]
6765 nested_tuple_bare = TupleAliasTsT[str, int, object]
6766
6767 self.assertEqual(get_args(nested_tuple_bare), (int, Tuple[str, int, object]))
6768 # Variants
6769 self.assertEqual(nested_tuple_bare, TupleAliasTsT[Unpack[Tuple[str, int, object]]])
6770 self.assertEqual(nested_tuple_bare, TupleAliasTsT[Unpack[Tuple[str, int]], object])
6771 self.assertEqual(nested_tuple_bare, TupleAliasTsT[Unpack[Tuple[str]], Unpack[Tuple[int]], object])
6772
6773 @skipUnless(TYPING_3_11_0, "Needed for backport")
6774 def test_type_var_inheritance(self):
6775 Ts = TypeVarTuple("Ts")
6776 self.assertFalse(isinstance(Unpack[Ts], TypeVar))
6777 self.assertFalse(isinstance(Unpack[Ts], typing.TypeVar))
6778
6779 def test_isinstance_results_unaffected_by_presence_of_tracing_function(self):
6780 # See https://github.com/python/typing_extensions/issues/661
6781
6782 code = textwrap.dedent(
6783 """\
6784 import sys, typing
6785
6786 def trace_call(*args):
6787 return trace_call
6788
6789 def run():
6790 sys.modules.pop("typing_extensions", None)
6791 from typing_extensions import TypeVarTuple, Unpack
6792 return isinstance(Unpack[TypeVarTuple("Ts")], typing.TypeVar)
6793 isinstance_result_1 = run()
6794 sys.setprofile(trace_call)
6795 isinstance_result_2 = run()
6796 sys.stdout.write(f"{isinstance_result_1} {isinstance_result_2}")
6797 """
6798 )
6799
6800 # Run this in an isolated process or it pollutes the environment
6801 # and makes other tests fail:
6802 try:
6803 proc = subprocess.run(
6804 [sys.executable, "-c", code], check=True, capture_output=True, text=True,
6805 )
6806 except subprocess.CalledProcessError as exc:
6807 print("stdout", exc.stdout, sep="\n")
6808 print("stderr", exc.stderr, sep="\n")
6809 raise
6810
6811 # Sanity checks that assert the test is working as expected
6812 self.assertIsInstance(proc.stdout, str)
6813 result1, result2 = proc.stdout.split(" ")
6814 self.assertIn(result1, {"True", "False"})
6815 self.assertIn(result2, {"True", "False"})
6816
6817 # The actual test:
6818 self.assertEqual(result1, result2)
6819
6820 class TypeVarTupleTests(BaseTestCase):
6821
6822 def test_basic_plain(self):
6823 Ts = TypeVarTuple('Ts')
6824 self.assertEqual(Ts, Ts)
6825 self.assertIsInstance(Ts, TypeVarTuple)
6826 Xs = TypeVarTuple('Xs')
6827 Ys = TypeVarTuple('Ys')
6828 self.assertNotEqual(Xs, Ys)
6829
6830 @skipIf(GOOD_TYPEVARTUPLE_REPR_EXPECTED, "TypeVarTuples have a bad repr on this version")
6831 def test_repr(self):
6832 Ts = TypeVarTuple('Ts')
6833 Ts_co = TypeVarTuple('Ts_co', covariant=True)
6834 Ts_contra = TypeVarTuple('Ts_contra', contravariant=True)
6835 Ts_infer = TypeVarTuple('Ts_infer', infer_variance=True)
6836 Ts_2 = TypeVarTuple('Ts_2')
6837 self.assertEqual(repr(Ts), 'Ts')
6838 self.assertEqual(repr(Ts_2), 'Ts_2')
6839
6840 self.assertEqual(repr(Ts_co), 'Ts_co')
6841 self.assertEqual(repr(Ts_contra), 'Ts_contra')
6842 self.assertEqual(repr(Ts_infer), 'Ts_infer')
6843
6844 @skipUnless(GOOD_TYPEVARTUPLE_REPR_EXPECTED, "TypeVarTuples have a bad repr on this version")
6845 def test_repr_py315(self):
6846 Ts = TypeVarTuple('Ts')
6847 Ts_co = TypeVarTuple('Ts_co', covariant=True)
6848 Ts_contra = TypeVarTuple('Ts_contra', contravariant=True)
6849 Ts_infer = TypeVarTuple('Ts_infer', infer_variance=True)
6850 Ts_2 = TypeVarTuple('Ts_2')
6851 self.assertEqual(repr(Ts), '~Ts')
6852 self.assertEqual(repr(Ts_2), '~Ts_2')
6853
6854 self.assertEqual(repr(Ts_co), '+Ts_co')
6855 self.assertEqual(repr(Ts_contra), '-Ts_contra')
6856 self.assertEqual(repr(Ts_infer), 'Ts_infer')
6857
6858 def test_variance(self):
6859 Ts_co = TypeVarTuple('Ts_co', covariant=True)
6860 Ts_contra = TypeVarTuple('Ts_contra', contravariant=True)
6861 Ts_infer = TypeVarTuple('Ts_infer', infer_variance=True)
6862
6863 self.assertIs(Ts_co.__covariant__, True)
6864 self.assertIs(Ts_co.__contravariant__, False)
6865 self.assertIs(Ts_co.__infer_variance__, False)
6866
6867 self.assertIs(Ts_contra.__covariant__, False)
6868 self.assertIs(Ts_contra.__contravariant__, True)
6869 self.assertIs(Ts_contra.__infer_variance__, False)
6870
6871 self.assertIs(Ts_infer.__covariant__, False)
6872 self.assertIs(Ts_infer.__contravariant__, False)
6873 self.assertIs(Ts_infer.__infer_variance__, True)
6874
6875 def test_no_redefinition(self):
6876 self.assertNotEqual(TypeVarTuple('Ts'), TypeVarTuple('Ts'))
6877
6878 def test_cannot_subclass_vars(self):
6879 with self.assertRaises(TypeError):
6880 class V(TypeVarTuple('Ts')):
6881 pass
6882
6883 def test_cannot_subclass_var_itself(self):
6884 with self.assertRaises(TypeError):
6885 class V(TypeVarTuple):
6886 pass
6887
6888 def test_cannot_instantiate_vars(self):
6889 Ts = TypeVarTuple('Ts')
6890 with self.assertRaises(TypeError):
6891 Ts()
6892
6893 def test_tuple(self):
6894 Ts = TypeVarTuple('Ts')
6895 # Not legal at type checking time but we can't really check against it.
6896 Tuple[Ts]
6897
6898 def test_args_and_parameters(self):
6899 Ts = TypeVarTuple('Ts')
6900
6901 t = Tuple[tuple(Ts)]
6902 if sys.version_info >= (3, 11):
6903 self.assertEqual(t.__args__, (typing.Unpack[Ts],))
6904 else:
6905 self.assertEqual(t.__args__, (Unpack[Ts],))
6906 self.assertEqual(t.__parameters__, (Ts,))
6907
6908 def test_pickle(self):
6909 global Ts, Ts_default # pickle wants to reference the class by name
6910 Ts = TypeVarTuple('Ts')
6911 Ts_default = TypeVarTuple('Ts_default', default=Unpack[Tuple[int, str]])
6912
6913 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
6914 for typevartuple in (Ts, Ts_default):
6915 z = pickle.loads(pickle.dumps(typevartuple, proto))
6916 self.assertEqual(z.__name__, typevartuple.__name__)
6917 self.assertEqual(z.__default__, typevartuple.__default__)
6918
6919
6920 class FinalDecoratorTests(BaseTestCase):
6921 def test_final_unmodified(self):
6922 def func(x): ...
6923 self.assertIs(func, final(func))
6924
6925 def test_dunder_final(self):
6926 @final
6927 def func(): ...
6928 @final
6929 class Cls: ...
6930 self.assertIs(True, func.__final__)
6931 self.assertIs(True, Cls.__final__)
6932
6933 class Wrapper:
6934 __slots__ = ("func",)
6935 def __init__(self, func):
6936 self.func = func
6937 def __call__(self, *args, **kwargs):
6938 return self.func(*args, **kwargs) # pragma: no cover
6939
6940 # Check that no error is thrown if the attribute
6941 # is not writable.
6942 @final
6943 @Wrapper
6944 def wrapped(): ...
6945 self.assertIsInstance(wrapped, Wrapper)
6946 self.assertIs(False, hasattr(wrapped, "__final__"))
6947
6948 class Meta(type):
6949 @property
6950 def __final__(self): return "can't set me"
6951 @final
6952 class WithMeta(metaclass=Meta): ...
6953 self.assertEqual(WithMeta.__final__, "can't set me")
6954
6955 # Builtin classes throw TypeError if you try to set an
6956 # attribute.
6957 final(int)
6958 self.assertIs(False, hasattr(int, "__final__"))
6959
6960 # Make sure it works with common builtin decorators
6961 class Methods:
6962 @final
6963 @classmethod
6964 def clsmethod(cls): ...
6965
6966 @final
6967 @staticmethod
6968 def stmethod(): ...
6969
6970 # The other order doesn't work because property objects
6971 # don't allow attribute assignment.
6972 @property
6973 @final
6974 def prop(self): ...
6975
6976 @final
6977 @lru_cache # noqa: B019
6978 def cached(self): ...
6979
6980 # Use getattr_static because the descriptor returns the
6981 # underlying function, which doesn't have __final__.
6982 self.assertIs(
6983 True,
6984 inspect.getattr_static(Methods, "clsmethod").__final__
6985 )
6986 self.assertIs(
6987 True,
6988 inspect.getattr_static(Methods, "stmethod").__final__
6989 )
6990 self.assertIs(True, Methods.prop.fget.__final__)
6991 self.assertIs(True, Methods.cached.__final__)
6992
6993
6994 class DisjointBaseTests(BaseTestCase):
6995 def test_disjoint_base_unmodified(self):
6996 class C: ...
6997 self.assertIs(C, disjoint_base(C))
6998
6999 def test_dunder_disjoint_base(self):
7000 @disjoint_base
7001 class C: ...
7002
7003 self.assertIs(C.__disjoint_base__, True)
7004
7005
7006 class RevealTypeTests(BaseTestCase):
7007 def test_reveal_type(self):
7008 obj = object()
7009
7010 with contextlib.redirect_stderr(io.StringIO()) as stderr:
7011 self.assertIs(obj, reveal_type(obj))
7012 self.assertEqual("Runtime type is 'object'", stderr.getvalue().strip())
7013
7014
7015 class DataclassTransformTests(BaseTestCase):
7016 def test_decorator(self):
7017 def create_model(*, frozen: bool = False, kw_only: bool = True):
7018 return lambda cls: cls
7019
7020 decorated = dataclass_transform(kw_only_default=True, order_default=False)(create_model)
7021
7022 class CustomerModel:
7023 id: int
7024
7025 self.assertIs(decorated, create_model)
7026 self.assertEqual(
7027 decorated.__dataclass_transform__,
7028 {
7029 "eq_default": True,
7030 "order_default": False,
7031 "kw_only_default": True,
7032 "frozen_default": False,
7033 "field_specifiers": (),
7034 "kwargs": {},
7035 }
7036 )
7037 self.assertIs(
7038 decorated(frozen=True, kw_only=False)(CustomerModel),
7039 CustomerModel
7040 )
7041
7042 def test_base_class(self):
7043 class ModelBase:
7044 def __init_subclass__(cls, *, frozen: bool = False): ...
7045
7046 Decorated = dataclass_transform(
7047 eq_default=True,
7048 order_default=True,
7049 # Arbitrary unrecognized kwargs are accepted at runtime.
7050 make_everything_awesome=True,
7051 )(ModelBase)
7052
7053 class CustomerModel(Decorated, frozen=True):
7054 id: int
7055
7056 self.assertIs(Decorated, ModelBase)
7057 self.assertEqual(
7058 Decorated.__dataclass_transform__,
7059 {
7060 "eq_default": True,
7061 "order_default": True,
7062 "kw_only_default": False,
7063 "frozen_default": False,
7064 "field_specifiers": (),
7065 "kwargs": {"make_everything_awesome": True},
7066 }
7067 )
7068 self.assertIsSubclass(CustomerModel, Decorated)
7069
7070 def test_metaclass(self):
7071 class Field: ...
7072
7073 class ModelMeta(type):
7074 def __new__(
7075 cls, name, bases, namespace, *, init: bool = True,
7076 ):
7077 return super().__new__(cls, name, bases, namespace)
7078
7079 Decorated = dataclass_transform(
7080 order_default=True, field_specifiers=(Field,)
7081 )(ModelMeta)
7082
7083 class ModelBase(metaclass=Decorated): ...
7084
7085 class CustomerModel(ModelBase, init=False):
7086 id: int
7087
7088 self.assertIs(Decorated, ModelMeta)
7089 self.assertEqual(
7090 Decorated.__dataclass_transform__,
7091 {
7092 "eq_default": True,
7093 "order_default": True,
7094 "kw_only_default": False,
7095 "frozen_default": False,
7096 "field_specifiers": (Field,),
7097 "kwargs": {},
7098 }
7099 )
7100 self.assertIsInstance(CustomerModel, Decorated)
7101
7102
7103 class AllTests(BaseTestCase):
7104
7105 def test_drop_in_for_typing(self):
7106 # Check that the typing_extensions.__all__ is a superset of
7107 # typing.__all__.
7108 t_all = set(typing.__all__)
7109 te_all = set(typing_extensions.__all__)
7110 exceptions = {"ByteString"}
7111 self.assertGreaterEqual(te_all, t_all - exceptions)
7112 # Deprecated, to be removed in 3.14
7113 self.assertFalse(hasattr(typing_extensions, "ByteString"))
7114 # These were never included in `typing.__all__`,
7115 # and have been removed in Python 3.13
7116 self.assertNotIn('re', te_all)
7117 self.assertNotIn('io', te_all)
7118
7119 def test_typing_extensions_includes_standard(self):
7120 a = typing_extensions.__all__
7121 self.assertIn('ClassVar', a)
7122 self.assertIn('Type', a)
7123 self.assertIn('ChainMap', a)
7124 self.assertIn('ContextManager', a)
7125 self.assertIn('Counter', a)
7126 self.assertIn('DefaultDict', a)
7127 self.assertIn('Deque', a)
7128 self.assertIn('NewType', a)
7129 self.assertIn('overload', a)
7130 self.assertIn('Text', a)
7131 self.assertIn('TYPE_CHECKING', a)
7132 self.assertIn('TypeAlias', a)
7133 self.assertIn('ParamSpec', a)
7134 self.assertIn("Concatenate", a)
7135
7136 self.assertIn('Annotated', a)
7137 self.assertIn('get_type_hints', a)
7138
7139 self.assertIn('Awaitable', a)
7140 self.assertIn('AsyncIterator', a)
7141 self.assertIn('AsyncIterable', a)
7142 self.assertIn('Coroutine', a)
7143 self.assertIn('AsyncContextManager', a)
7144
7145 self.assertIn('AsyncGenerator', a)
7146
7147 self.assertIn('Protocol', a)
7148 self.assertIn('runtime', a)
7149
7150 # Check that all objects in `__all__` are present in the module
7151 for name in a:
7152 self.assertTrue(hasattr(typing_extensions, name))
7153
7154 def test_all_names_in___all__(self):
7155 exclude = {
7156 'GenericMeta',
7157 'KT',
7158 'PEP_560',
7159 'T',
7160 'T_co',
7161 'T_contra',
7162 'VT',
7163 }
7164 actual_names = {
7165 name for name in dir(typing_extensions)
7166 if not name.startswith("_")
7167 and not isinstance(getattr(typing_extensions, name), types.ModuleType)
7168 }
7169 # Make sure all public names are in __all__
7170 self.assertEqual({*exclude, *typing_extensions.__all__},
7171 actual_names)
7172 # Make sure all excluded names actually exist
7173 self.assertLessEqual(exclude, actual_names)
7174
7175 def test_typing_extensions_defers_when_possible(self):
7176 # These two are currently always different to `typing.TypedDict`
7177 # as PEP 764 has not yet been accepted/implemented upstream.
7178 exclude = {'TypedDict', 'is_typeddict'}
7179
7180 if sys.version_info < (3, 10):
7181 exclude |= {'get_args', 'get_origin'}
7182 if sys.version_info < (3, 10, 1):
7183 exclude |= {"Literal"}
7184 if sys.version_info < (3, 11):
7185 exclude |= {'final', 'Any', 'NewType', 'overload', 'Concatenate'}
7186 if sys.version_info < (3, 12):
7187 exclude |= {
7188 'SupportsAbs', 'SupportsBytes',
7189 'SupportsComplex', 'SupportsFloat', 'SupportsIndex', 'SupportsInt',
7190 'SupportsRound', 'Unpack', 'dataclass_transform',
7191 }
7192 if sys.version_info < (3, 13):
7193 exclude |= {
7194 'NamedTuple', 'runtime_checkable', 'Generator',
7195 'AsyncGenerator', 'ContextManager', 'AsyncContextManager',
7196 'ParamSpec', 'TypeVar', 'TypeVarTuple', 'get_type_hints',
7197 }
7198 if sys.version_info < (3, 15):
7199 exclude |= {
7200 'TypeAliasType', 'Protocol'
7201 }
7202 if sys.version_info < (3, 15):
7203 exclude |= {
7204 'TypeVarTuple'
7205 }
7206 for item in typing_extensions.__all__:
7207 if item not in exclude and hasattr(typing, item):
7208 self.assertIs(
7209 getattr(typing_extensions, item),
7210 getattr(typing, item))
7211
7212 def test_alias_names_still_exist(self):
7213 for name in typing_extensions._typing_names:
7214 # If this fails, change _typing_names to conditionally add the name
7215 # depending on the Python version.
7216 self.assertTrue(
7217 hasattr(typing_extensions, name),
7218 f"{name} no longer exists in typing",
7219 )
7220
7221 def test_typing_extensions_compiles_with_opt(self):
7222 file_path = typing_extensions.__file__
7223 try:
7224 subprocess.check_output(f'{sys.executable} -OO {file_path}',
7225 stderr=subprocess.STDOUT,
7226 shell=True)
7227 except subprocess.CalledProcessError: # pragma: no cover
7228 self.fail('Module does not compile with optimize=2 (-OO flag).')
7229
7230
7231 class CoolEmployee(NamedTuple):
7232 name: str
7233 cool: int
7234
7235
7236 class CoolEmployeeWithDefault(NamedTuple):
7237 name: str
7238 cool: int = 0
7239
7240
7241 class XMeth(NamedTuple):
7242 x: int
7243
7244 def double(self):
7245 return 2 * self.x
7246
7247
7248 class NamedTupleTests(BaseTestCase):
7249 class NestedEmployee(NamedTuple):
7250 name: str
7251 cool: int
7252
7253 def test_basics(self):
7254 Emp = NamedTuple('Emp', [('name', str), ('id', int)])
7255 self.assertIsSubclass(Emp, tuple)
7256 joe = Emp('Joe', 42)
7257 jim = Emp(name='Jim', id=1)
7258 self.assertIsInstance(joe, Emp)
7259 self.assertIsInstance(joe, tuple)
7260 self.assertEqual(joe.name, 'Joe')
7261 self.assertEqual(joe.id, 42)
7262 self.assertEqual(jim.name, 'Jim')
7263 self.assertEqual(jim.id, 1)
7264 self.assertEqual(Emp.__name__, 'Emp')
7265 self.assertEqual(Emp._fields, ('name', 'id'))
7266 self.assertEqual(Emp.__annotations__,
7267 collections.OrderedDict([('name', str), ('id', int)]))
7268
7269 def test_annotation_usage(self):
7270 tim = CoolEmployee('Tim', 9000)
7271 self.assertIsInstance(tim, CoolEmployee)
7272 self.assertIsInstance(tim, tuple)
7273 self.assertEqual(tim.name, 'Tim')
7274 self.assertEqual(tim.cool, 9000)
7275 self.assertEqual(CoolEmployee.__name__, 'CoolEmployee')
7276 self.assertEqual(CoolEmployee._fields, ('name', 'cool'))
7277 self.assertEqual(CoolEmployee.__annotations__,
7278 collections.OrderedDict(name=str, cool=int))
7279
7280 def test_annotation_usage_with_default(self):
7281 jelle = CoolEmployeeWithDefault('Jelle')
7282 self.assertIsInstance(jelle, CoolEmployeeWithDefault)
7283 self.assertIsInstance(jelle, tuple)
7284 self.assertEqual(jelle.name, 'Jelle')
7285 self.assertEqual(jelle.cool, 0)
7286 cooler_employee = CoolEmployeeWithDefault('Sjoerd', 1)
7287 self.assertEqual(cooler_employee.cool, 1)
7288
7289 self.assertEqual(CoolEmployeeWithDefault.__name__, 'CoolEmployeeWithDefault')
7290 self.assertEqual(CoolEmployeeWithDefault._fields, ('name', 'cool'))
7291 self.assertEqual(CoolEmployeeWithDefault.__annotations__,
7292 dict(name=str, cool=int))
7293
7294 with self.assertRaisesRegex(
7295 TypeError,
7296 'Non-default namedtuple field y cannot follow default field x'
7297 ):
7298 class NonDefaultAfterDefault(NamedTuple):
7299 x: int = 3
7300 y: int
7301
7302 def test_field_defaults(self):
7303 self.assertEqual(CoolEmployeeWithDefault._field_defaults, dict(cool=0))
7304
7305 def test_annotation_usage_with_methods(self):
7306 self.assertEqual(XMeth(1).double(), 2)
7307 self.assertEqual(XMeth(42).x, XMeth(42)[0])
7308 self.assertEqual(str(XRepr(42)), '42 -> 1')
7309 self.assertEqual(XRepr(1, 2) + XRepr(3), 0)
7310
7311 bad_overwrite_error_message = 'Cannot overwrite NamedTuple attribute'
7312
7313 with self.assertRaisesRegex(AttributeError, bad_overwrite_error_message):
7314 class XMethBad(NamedTuple):
7315 x: int
7316 def _fields(self):
7317 return 'no chance for this' # pragma: no cover
7318
7319 with self.assertRaisesRegex(AttributeError, bad_overwrite_error_message):
7320 class XMethBad2(NamedTuple):
7321 x: int
7322 def _source(self):
7323 return 'no chance for this as well' # pragma: no cover
7324
7325 def test_multiple_inheritance(self):
7326 class A:
7327 pass
7328 with self.assertRaisesRegex(
7329 TypeError,
7330 'can only inherit from a NamedTuple type and Generic'
7331 ):
7332 class X(NamedTuple, A):
7333 x: int
7334
7335 with self.assertRaisesRegex(
7336 TypeError,
7337 'can only inherit from a NamedTuple type and Generic'
7338 ):
7339 class Y(NamedTuple, tuple):
7340 x: int
7341
7342 with self.assertRaisesRegex(TypeError, 'duplicate base class'):
7343 class Z(NamedTuple, NamedTuple):
7344 x: int
7345
7346 class A(NamedTuple):
7347 x: int
7348 with self.assertRaisesRegex(
7349 TypeError,
7350 'can only inherit from a NamedTuple type and Generic'
7351 ):
7352 class XX(NamedTuple, A):
7353 y: str
7354
7355 def test_generic(self):
7356 class X(NamedTuple, Generic[T]):
7357 x: T
7358 self.assertEqual(X.__bases__, (tuple, Generic))
7359 self.assertEqual(X.__orig_bases__, (NamedTuple, Generic[T]))
7360 self.assertEqual(X.__mro__, (X, tuple, Generic, object))
7361
7362 class Y(Generic[T], NamedTuple):
7363 x: T
7364 self.assertEqual(Y.__bases__, (Generic, tuple))
7365 self.assertEqual(Y.__orig_bases__, (Generic[T], NamedTuple))
7366 self.assertEqual(Y.__mro__, (Y, Generic, tuple, object))
7367
7368 for G in X, Y:
7369 with self.subTest(type=G):
7370 self.assertEqual(G.__parameters__, (T,))
7371 A = G[int]
7372 self.assertIs(A.__origin__, G)
7373 self.assertEqual(A.__args__, (int,))
7374 self.assertEqual(A.__parameters__, ())
7375
7376 a = A(3)
7377 self.assertIs(type(a), G)
7378 self.assertIsInstance(a, G)
7379 self.assertEqual(a.x, 3)
7380
7381 things = "arguments" if sys.version_info >= (3, 10) else "parameters"
7382 with self.assertRaisesRegex(TypeError, f'Too many {things}'):
7383 G[int, str]
7384
7385 def test_non_generic_subscript_py39_plus(self):
7386 # For backward compatibility, subscription works
7387 # on arbitrary NamedTuple types.
7388 class Group(NamedTuple):
7389 key: T
7390 group: list[T]
7391 A = Group[int]
7392 self.assertEqual(A.__origin__, Group)
7393 self.assertEqual(A.__parameters__, ())
7394 self.assertEqual(A.__args__, (int,))
7395 a = A(1, [2])
7396 self.assertIs(type(a), Group)
7397 self.assertEqual(a, (1, [2]))
7398
7399 @skipUnless(sys.version_info <= (3, 15), "Behavior removed in 3.15")
7400 def test_namedtuple_keyword_usage(self):
7401 with self.assertWarnsRegex(
7402 DeprecationWarning,
7403 "Creating NamedTuple classes using keyword arguments is deprecated"
7404 ):
7405 LocalEmployee = NamedTuple("LocalEmployee", name=str, age=int)
7406
7407 nick = LocalEmployee('Nick', 25)
7408 self.assertIsInstance(nick, tuple)
7409 self.assertEqual(nick.name, 'Nick')
7410 self.assertEqual(LocalEmployee.__name__, 'LocalEmployee')
7411 self.assertEqual(LocalEmployee._fields, ('name', 'age'))
7412 self.assertEqual(LocalEmployee.__annotations__, dict(name=str, age=int))
7413
7414 with self.assertRaisesRegex(
7415 TypeError,
7416 "Either list of fields or keywords can be provided to NamedTuple, not both"
7417 ):
7418 NamedTuple('Name', [('x', int)], y=str)
7419
7420 with self.assertRaisesRegex(
7421 TypeError,
7422 "Either list of fields or keywords can be provided to NamedTuple, not both"
7423 ):
7424 NamedTuple('Name', [], y=str)
7425
7426 with self.assertRaisesRegex(
7427 TypeError,
7428 (
7429 r"Cannot pass `None` as the 'fields' parameter "
7430 r"and also specify fields using keyword arguments"
7431 )
7432 ):
7433 NamedTuple('Name', None, x=int)
7434
7435 @skipUnless(sys.version_info <= (3, 15), "Behavior removed in 3.15")
7436 def test_namedtuple_special_keyword_names(self):
7437 with self.assertWarnsRegex(
7438 DeprecationWarning,
7439 "Creating NamedTuple classes using keyword arguments is deprecated"
7440 ):
7441 NT = NamedTuple("NT", cls=type, self=object, typename=str, fields=list)
7442
7443 self.assertEqual(NT.__name__, 'NT')
7444 self.assertEqual(NT._fields, ('cls', 'self', 'typename', 'fields'))
7445 a = NT(cls=str, self=42, typename='foo', fields=[('bar', tuple)])
7446 self.assertEqual(a.cls, str)
7447 self.assertEqual(a.self, 42)
7448 self.assertEqual(a.typename, 'foo')
7449 self.assertEqual(a.fields, [('bar', tuple)])
7450
7451 @skipUnless(sys.version_info <= (3, 15), "Behavior removed in 3.15")
7452 def test_empty_namedtuple(self):
7453 expected_warning = re.escape(
7454 "Failing to pass a value for the 'fields' parameter is deprecated "
7455 "and will be disallowed in Python 3.15. "
7456 "To create a NamedTuple class with 0 fields "
7457 "using the functional syntax, "
7458 "pass an empty list, e.g. `NT1 = NamedTuple('NT1', [])`."
7459 )
7460 with self.assertWarnsRegex(DeprecationWarning, fr"^{expected_warning}$"):
7461 NT1 = NamedTuple('NT1')
7462
7463 expected_warning = re.escape(
7464 "Passing `None` as the 'fields' parameter is deprecated "
7465 "and will be disallowed in Python 3.15. "
7466 "To create a NamedTuple class with 0 fields "
7467 "using the functional syntax, "
7468 "pass an empty list, e.g. `NT2 = NamedTuple('NT2', [])`."
7469 )
7470 with self.assertWarnsRegex(DeprecationWarning, fr"^{expected_warning}$"):
7471 NT2 = NamedTuple('NT2', None)
7472
7473 NT3 = NamedTuple('NT2', [])
7474
7475 class CNT(NamedTuple):
7476 pass # empty body
7477
7478 for struct in NT1, NT2, NT3, CNT:
7479 with self.subTest(struct=struct):
7480 self.assertEqual(struct._fields, ())
7481 self.assertEqual(struct.__annotations__, {})
7482 self.assertIsInstance(struct(), struct)
7483 self.assertEqual(struct._field_defaults, {})
7484
7485 def test_namedtuple_errors(self):
7486 with self.assertRaises(TypeError):
7487 NamedTuple.__new__()
7488 with self.assertRaises(TypeError):
7489 NamedTuple()
7490 with self.assertRaises(TypeError):
7491 NamedTuple('Emp', [('name', str)], None)
7492 with self.assertRaisesRegex(ValueError, 'cannot start with an underscore'):
7493 NamedTuple('Emp', [('_name', str)])
7494 with self.assertRaises(TypeError):
7495 NamedTuple(typename='Emp', name=str, id=int)
7496
7497 def test_copy_and_pickle(self):
7498 global Emp # pickle wants to reference the class by name
7499 Emp = NamedTuple('Emp', [('name', str), ('cool', int)])
7500 for cls in Emp, CoolEmployee, self.NestedEmployee:
7501 with self.subTest(cls=cls):
7502 jane = cls('jane', 37)
7503 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
7504 z = pickle.dumps(jane, proto)
7505 jane2 = pickle.loads(z)
7506 self.assertEqual(jane2, jane)
7507 self.assertIsInstance(jane2, cls)
7508
7509 jane2 = copy.copy(jane)
7510 self.assertEqual(jane2, jane)
7511 self.assertIsInstance(jane2, cls)
7512
7513 jane2 = copy.deepcopy(jane)
7514 self.assertEqual(jane2, jane)
7515 self.assertIsInstance(jane2, cls)
7516
7517 def test_docstring(self):
7518 self.assertIsInstance(NamedTuple.__doc__, str)
7519
7520 def test_same_as_typing_NamedTuple(self):
7521 self.assertEqual(
7522 set(dir(NamedTuple)),
7523 set(dir(typing.NamedTuple))
7524 )
7525 self.assertIs(type(NamedTuple), type(typing.NamedTuple))
7526
7527 def test_orig_bases(self):
7528 T = TypeVar('T')
7529
7530 class SimpleNamedTuple(NamedTuple):
7531 pass
7532
7533 class GenericNamedTuple(NamedTuple, Generic[T]):
7534 pass
7535
7536 self.assertEqual(SimpleNamedTuple.__orig_bases__, (NamedTuple,))
7537 self.assertEqual(GenericNamedTuple.__orig_bases__, (NamedTuple, Generic[T]))
7538
7539 CallNamedTuple = NamedTuple('CallNamedTuple', [])
7540
7541 self.assertEqual(CallNamedTuple.__orig_bases__, (NamedTuple,))
7542
7543 def test_setname_called_on_values_in_class_dictionary(self):
7544 class Vanilla:
7545 def __set_name__(self, owner, name):
7546 self.name = name
7547
7548 class Foo(NamedTuple):
7549 attr = Vanilla()
7550
7551 foo = Foo()
7552 self.assertEqual(len(foo), 0)
7553 self.assertNotIn('attr', Foo._fields)
7554 self.assertIsInstance(foo.attr, Vanilla)
7555 self.assertEqual(foo.attr.name, "attr")
7556
7557 class Bar(NamedTuple):
7558 attr: Vanilla = Vanilla()
7559
7560 bar = Bar()
7561 self.assertEqual(len(bar), 1)
7562 self.assertIn('attr', Bar._fields)
7563 self.assertIsInstance(bar.attr, Vanilla)
7564 self.assertEqual(bar.attr.name, "attr")
7565
7566 @skipIf(
7567 TYPING_3_12_0,
7568 "__set_name__ behaviour changed on py312+ to use BaseException.add_note()"
7569 )
7570 def test_setname_raises_the_same_as_on_other_classes_py311_minus(self):
7571 class CustomException(BaseException): pass
7572
7573 class Annoying:
7574 def __set_name__(self, owner, name):
7575 raise CustomException
7576
7577 annoying = Annoying()
7578
7579 with self.assertRaises(RuntimeError) as cm:
7580 class NormalClass:
7581 attr = annoying
7582 normal_exception = cm.exception
7583
7584 with self.assertRaises(RuntimeError) as cm:
7585 class NamedTupleClass(NamedTuple):
7586 attr = annoying
7587 namedtuple_exception = cm.exception
7588
7589 self.assertIs(type(namedtuple_exception), RuntimeError)
7590 self.assertIs(type(namedtuple_exception), type(normal_exception))
7591 self.assertEqual(len(namedtuple_exception.args), len(normal_exception.args))
7592 self.assertEqual(
7593 namedtuple_exception.args[0],
7594 normal_exception.args[0].replace("NormalClass", "NamedTupleClass")
7595 )
7596
7597 self.assertIs(type(namedtuple_exception.__cause__), CustomException)
7598 self.assertIs(
7599 type(namedtuple_exception.__cause__), type(normal_exception.__cause__)
7600 )
7601 self.assertEqual(
7602 namedtuple_exception.__cause__.args, normal_exception.__cause__.args
7603 )
7604
7605 @skipUnless(
7606 TYPING_3_12_0,
7607 "__set_name__ behaviour changed on py312+ to use BaseException.add_note()"
7608 )
7609 def test_setname_raises_the_same_as_on_other_classes_py312_plus(self):
7610 class CustomException(BaseException): pass
7611
7612 class Annoying:
7613 def __set_name__(self, owner, name):
7614 raise CustomException
7615
7616 annoying = Annoying()
7617
7618 with self.assertRaises(CustomException) as cm:
7619 class NormalClass:
7620 attr = annoying
7621 normal_exception = cm.exception
7622
7623 with self.assertRaises(CustomException) as cm:
7624 class NamedTupleClass(NamedTuple):
7625 attr = annoying
7626 namedtuple_exception = cm.exception
7627
7628 expected_note = (
7629 "Error calling __set_name__ on 'Annoying' instance "
7630 "'attr' in 'NamedTupleClass'"
7631 )
7632
7633 self.assertIs(type(namedtuple_exception), CustomException)
7634 self.assertIs(type(namedtuple_exception), type(normal_exception))
7635 self.assertEqual(namedtuple_exception.args, normal_exception.args)
7636
7637 self.assertEqual(len(namedtuple_exception.__notes__), 1)
7638 self.assertEqual(
7639 len(namedtuple_exception.__notes__), len(normal_exception.__notes__)
7640 )
7641
7642 self.assertEqual(namedtuple_exception.__notes__[0], expected_note)
7643 self.assertEqual(
7644 namedtuple_exception.__notes__[0],
7645 normal_exception.__notes__[0].replace("NormalClass", "NamedTupleClass")
7646 )
7647
7648 def test_strange_errors_when_accessing_set_name_itself(self):
7649 class CustomException(Exception): pass
7650
7651 class Meta(type):
7652 def __getattribute__(self, attr):
7653 if attr == "__set_name__":
7654 raise CustomException
7655 return object.__getattribute__(self, attr)
7656
7657 class VeryAnnoying(metaclass=Meta): pass
7658
7659 very_annoying = VeryAnnoying()
7660
7661 with self.assertRaises(CustomException):
7662 class Foo(NamedTuple):
7663 attr = very_annoying
7664
7665
7666 class TypeVarTests(BaseTestCase):
7667 def test_basic_plain(self):
7668 T = TypeVar('T')
7669 # T equals itself.
7670 self.assertEqual(T, T)
7671 # T is an instance of TypeVar
7672 self.assertIsInstance(T, TypeVar)
7673 self.assertEqual(T.__name__, 'T')
7674 self.assertEqual(T.__constraints__, ())
7675 self.assertIs(T.__bound__, None)
7676 self.assertIs(T.__covariant__, False)
7677 self.assertIs(T.__contravariant__, False)
7678 self.assertIs(T.__infer_variance__, False)
7679
7680 def test_attributes(self):
7681 T_bound = TypeVar('T_bound', bound=int)
7682 self.assertEqual(T_bound.__name__, 'T_bound')
7683 self.assertEqual(T_bound.__constraints__, ())
7684 self.assertIs(T_bound.__bound__, int)
7685
7686 T_constraints = TypeVar('T_constraints', int, str)
7687 self.assertEqual(T_constraints.__name__, 'T_constraints')
7688 self.assertEqual(T_constraints.__constraints__, (int, str))
7689 self.assertIs(T_constraints.__bound__, None)
7690
7691 T_co = TypeVar('T_co', covariant=True)
7692 self.assertEqual(T_co.__name__, 'T_co')
7693 self.assertIs(T_co.__covariant__, True)
7694 self.assertIs(T_co.__contravariant__, False)
7695 self.assertIs(T_co.__infer_variance__, False)
7696
7697 T_contra = TypeVar('T_contra', contravariant=True)
7698 self.assertEqual(T_contra.__name__, 'T_contra')
7699 self.assertIs(T_contra.__covariant__, False)
7700 self.assertIs(T_contra.__contravariant__, True)
7701 self.assertIs(T_contra.__infer_variance__, False)
7702
7703 T_infer = TypeVar('T_infer', infer_variance=True)
7704 self.assertEqual(T_infer.__name__, 'T_infer')
7705 self.assertIs(T_infer.__covariant__, False)
7706 self.assertIs(T_infer.__contravariant__, False)
7707 self.assertIs(T_infer.__infer_variance__, True)
7708
7709 def test_typevar_instance_type_error(self):
7710 T = TypeVar('T')
7711 with self.assertRaises(TypeError):
7712 isinstance(42, T)
7713
7714 def test_typevar_subclass_type_error(self):
7715 T = TypeVar('T')
7716 with self.assertRaises(TypeError):
7717 issubclass(int, T)
7718 with self.assertRaises(TypeError):
7719 issubclass(T, int)
7720
7721 def test_constrained_error(self):
7722 with self.assertRaises(TypeError):
7723 X = TypeVar('X', int)
7724 X
7725
7726 def test_union_unique(self):
7727 X = TypeVar('X')
7728 Y = TypeVar('Y')
7729 self.assertNotEqual(X, Y)
7730 self.assertEqual(Union[X], X)
7731 self.assertNotEqual(Union[X], Union[X, Y])
7732 self.assertEqual(Union[X, X], X)
7733 self.assertNotEqual(Union[X, int], Union[X])
7734 self.assertNotEqual(Union[X, int], Union[int])
7735 self.assertEqual(Union[X, int].__args__, (X, int))
7736 self.assertEqual(Union[X, int].__parameters__, (X,))
7737 self.assertIs(Union[X, int].__origin__, Union)
7738
7739 if hasattr(types, "UnionType"):
7740 def test_or(self):
7741 X = TypeVar('X')
7742 # use a string because str doesn't implement
7743 # __or__/__ror__ itself
7744 self.assertEqual(X | "x", Union[X, "x"])
7745 self.assertEqual("x" | X, Union["x", X])
7746 # make sure the order is correct
7747 self.assertEqual(get_args(X | "x"), (X, EqualToForwardRef("x")))
7748 self.assertEqual(get_args("x" | X), (EqualToForwardRef("x"), X))
7749
7750 def test_union_constrained(self):
7751 A = TypeVar('A', str, bytes)
7752 self.assertNotEqual(Union[A, str], Union[A])
7753
7754 def test_repr(self):
7755 self.assertEqual(repr(T), '~T')
7756 self.assertEqual(repr(KT), '~KT')
7757 self.assertEqual(repr(VT), '~VT')
7758 self.assertEqual(repr(AnyStr), '~AnyStr')
7759 T_co = TypeVar('T_co', covariant=True)
7760 self.assertEqual(repr(T_co), '+T_co')
7761 T_contra = TypeVar('T_contra', contravariant=True)
7762 self.assertEqual(repr(T_contra), '-T_contra')
7763
7764 def test_no_redefinition(self):
7765 self.assertNotEqual(TypeVar('T'), TypeVar('T'))
7766 self.assertNotEqual(TypeVar('T', int, str), TypeVar('T', int, str))
7767
7768 def test_cannot_subclass(self):
7769 with self.assertRaises(TypeError):
7770 class V(TypeVar): pass
7771 T = TypeVar("T")
7772 with self.assertRaises(TypeError):
7773 class W(T): pass
7774
7775 def test_cannot_instantiate_vars(self):
7776 with self.assertRaises(TypeError):
7777 TypeVar('A')()
7778
7779 def test_bound_errors(self):
7780 with self.assertRaises(TypeError):
7781 TypeVar('X', bound=Optional)
7782 with self.assertRaises(TypeError):
7783 TypeVar('X', str, float, bound=Employee)
7784 with self.assertRaisesRegex(TypeError,
7785 r"Bound must be a type\. Got \(1, 2\)\."):
7786 TypeVar('X', bound=(1, 2))
7787
7788 def test_missing__name__(self):
7789 # See https://github.com/python/cpython/issues/84123
7790 code = ("import typing\n"
7791 "T = typing.TypeVar('T')\n"
7792 )
7793 exec(code, {})
7794
7795 def test_no_bivariant(self):
7796 with self.assertRaises(ValueError):
7797 TypeVar('T', covariant=True, contravariant=True)
7798
7799 def test_cannot_combine_explicit_and_infer(self):
7800 with self.assertRaises(ValueError):
7801 TypeVar('T', covariant=True, infer_variance=True)
7802 with self.assertRaises(ValueError):
7803 TypeVar('T', contravariant=True, infer_variance=True)
7804
7805
7806 class TypeVarLikeDefaultsTests(BaseTestCase):
7807 def test_typevar(self):
7808 T = typing_extensions.TypeVar('T', default=int)
7809 typing_T = typing.TypeVar('T')
7810 self.assertEqual(T.__default__, int)
7811 self.assertIsInstance(T, typing_extensions.TypeVar)
7812 self.assertIsInstance(T, typing.TypeVar)
7813 self.assertIsInstance(typing_T, typing.TypeVar)
7814 self.assertIsInstance(typing_T, typing_extensions.TypeVar)
7815
7816 class A(Generic[T]): ...
7817 self.assertEqual(Optional[T].__args__, (T, type(None)))
7818
7819 def test_typevar_none(self):
7820 U = typing_extensions.TypeVar('U')
7821 U_None = typing_extensions.TypeVar('U_None', default=None)
7822 self.assertIs(U.__default__, NoDefault)
7823 self.assertFalse(U.has_default())
7824 self.assertEqual(U_None.__default__, None)
7825 self.assertTrue(U_None.has_default())
7826
7827 def test_paramspec(self):
7828 P = ParamSpec('P', default=[str, int])
7829 self.assertEqual(P.__default__, [str, int])
7830 self.assertTrue(P.has_default())
7831 self.assertIsInstance(P, ParamSpec)
7832 if hasattr(typing, "ParamSpec"):
7833 self.assertIsInstance(P, typing.ParamSpec)
7834 typing_P = typing.ParamSpec('P')
7835 self.assertIsInstance(typing_P, typing.ParamSpec)
7836 self.assertIsInstance(typing_P, ParamSpec)
7837
7838 class A(Generic[P]): ...
7839 self.assertEqual(typing.Callable[P, None].__args__, (P, type(None)))
7840
7841 P_default = ParamSpec('P_default', default=...)
7842 self.assertIs(P_default.__default__, ...)
7843 self.assertTrue(P_default.has_default())
7844
7845 def test_paramspec_none(self):
7846 U = ParamSpec('U')
7847 U_None = ParamSpec('U_None', default=None)
7848 self.assertIs(U.__default__, NoDefault)
7849 self.assertFalse(U.has_default())
7850 self.assertIs(U_None.__default__, None)
7851 self.assertTrue(U_None.has_default())
7852
7853 def test_typevartuple(self):
7854 Ts = TypeVarTuple('Ts', default=Unpack[Tuple[str, int]])
7855 self.assertEqual(Ts.__default__, Unpack[Tuple[str, int]])
7856 self.assertIsInstance(Ts, TypeVarTuple)
7857 self.assertTrue(Ts.has_default())
7858 if hasattr(typing, "TypeVarTuple"):
7859 self.assertIsInstance(Ts, typing.TypeVarTuple)
7860 typing_Ts = typing.TypeVarTuple('Ts')
7861 self.assertIsInstance(typing_Ts, typing.TypeVarTuple)
7862 self.assertIsInstance(typing_Ts, TypeVarTuple)
7863
7864 class A(Generic[Unpack[Ts]]): ...
7865 self.assertEqual(Optional[Unpack[Ts]].__args__, (Unpack[Ts], type(None)))
7866
7867 @skipIf(
7868 sys.version_info < (3, 11, 1),
7869 "Not yet backported for older versions of Python"
7870 )
7871 def test_typevartuple_specialization(self):
7872 T = TypeVar("T")
7873 Ts = TypeVarTuple('Ts', default=Unpack[Tuple[str, int]])
7874 self.assertEqual(Ts.__default__, Unpack[Tuple[str, int]])
7875 class A(Generic[T, Unpack[Ts]]): ...
7876 self.assertEqual(A[float].__args__, (float, str, int))
7877 self.assertEqual(A[float, range].__args__, (float, range))
7878 self.assertEqual(A[float, Unpack[tuple[int, ...]]].__args__, (float, Unpack[tuple[int, ...]]))
7879
7880 @skipIf(
7881 sys.version_info < (3, 11, 1),
7882 "Not yet backported for older versions of Python"
7883 )
7884 def test_typevar_and_typevartuple_specialization(self):
7885 T = TypeVar("T")
7886 U = TypeVar("U", default=float)
7887 Ts = TypeVarTuple('Ts', default=Unpack[Tuple[str, int]])
7888 self.assertEqual(Ts.__default__, Unpack[Tuple[str, int]])
7889 class A(Generic[T, U, Unpack[Ts]]): ...
7890 self.assertEqual(A[int].__args__, (int, float, str, int))
7891 self.assertEqual(A[int, str].__args__, (int, str, str, int))
7892 self.assertEqual(A[int, str, range].__args__, (int, str, range))
7893 self.assertEqual(A[int, str, Unpack[tuple[int, ...]]].__args__, (int, str, Unpack[tuple[int, ...]]))
7894
7895 def test_no_default_after_typevar_tuple(self):
7896 T = TypeVar("T", default=int)
7897 Ts = TypeVarTuple("Ts")
7898 Ts_default = TypeVarTuple("Ts_default", default=Unpack[Tuple[str, int]])
7899
7900 with self.assertRaises(TypeError):
7901 class X(Generic[Unpack[Ts], T]): ...
7902
7903 with self.assertRaises(TypeError):
7904 class Y(Generic[Unpack[Ts_default], T]): ...
7905
7906 def test_typevartuple_none(self):
7907 U = TypeVarTuple('U')
7908 U_None = TypeVarTuple('U_None', default=None)
7909 self.assertIs(U.__default__, NoDefault)
7910 self.assertFalse(U.has_default())
7911 self.assertIs(U_None.__default__, None)
7912 self.assertTrue(U_None.has_default())
7913
7914 def test_no_default_after_non_default(self):
7915 DefaultStrT = typing_extensions.TypeVar('DefaultStrT', default=str)
7916 T = TypeVar('T')
7917
7918 with self.assertRaises(TypeError):
7919 Generic[DefaultStrT, T]
7920
7921 def test_need_more_params(self):
7922 DefaultStrT = typing_extensions.TypeVar('DefaultStrT', default=str)
7923 T = typing_extensions.TypeVar('T')
7924 U = typing_extensions.TypeVar('U')
7925
7926 class A(Generic[T, U, DefaultStrT]): ...
7927 A[int, bool]
7928 A[int, bool, str]
7929
7930 with self.assertRaises(
7931 TypeError, msg="Too few arguments for .+; actual 1, expected at least 2"
7932 ):
7933 A[int]
7934
7935 def test_pickle(self):
7936 global U, U_co, U_contra, U_default # pickle wants to reference the class by name
7937 U = typing_extensions.TypeVar('U')
7938 U_co = typing_extensions.TypeVar('U_co', covariant=True)
7939 U_contra = typing_extensions.TypeVar('U_contra', contravariant=True)
7940 U_default = typing_extensions.TypeVar('U_default', default=int)
7941 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
7942 for typevar in (U, U_co, U_contra, U_default):
7943 z = pickle.loads(pickle.dumps(typevar, proto))
7944 self.assertEqual(z.__name__, typevar.__name__)
7945 self.assertEqual(z.__covariant__, typevar.__covariant__)
7946 self.assertEqual(z.__contravariant__, typevar.__contravariant__)
7947 self.assertEqual(z.__bound__, typevar.__bound__)
7948 self.assertEqual(z.__default__, typevar.__default__)
7949
7950 def test_strange_defaults_are_allowed(self):
7951 # Leave it to type checkers to check whether strange default values
7952 # should be allowed or disallowed
7953 def not_a_type(): ...
7954
7955 for typevarlike_cls in TypeVar, ParamSpec, TypeVarTuple:
7956 for default in not_a_type, 42, bytearray(), (int, not_a_type, 42):
7957 with self.subTest(typevarlike_cls=typevarlike_cls, default=default):
7958 T = typevarlike_cls("T", default=default)
7959 self.assertEqual(T.__default__, default)
7960
7961 @skip_if_py313_beta_1
7962 def test_allow_default_after_non_default_in_alias(self):
7963 T_default = TypeVar('T_default', default=int)
7964 T = TypeVar('T')
7965 Ts = TypeVarTuple('Ts')
7966
7967 a1 = Callable[[T_default], T]
7968 self.assertEqual(a1.__args__, (T_default, T))
7969
7970 a2 = dict[T_default, T]
7971 self.assertEqual(a2.__args__, (T_default, T))
7972
7973 a3 = typing.Dict[T_default, T]
7974 self.assertEqual(a3.__args__, (T_default, T))
7975
7976 a4 = Callable[[Unpack[Ts]], T]
7977 self.assertEqual(a4.__args__, (Unpack[Ts], T))
7978
7979 @skipIf(
7980 typing_extensions.Protocol is typing.Protocol,
7981 "Test currently fails with the CPython version of Protocol and that's not our fault"
7982 )
7983 def test_generic_with_broken_eq(self):
7984 # See https://github.com/python/typing_extensions/pull/422 for context
7985 class BrokenEq(type):
7986 def __eq__(self, other):
7987 if other is typing_extensions.Protocol:
7988 raise TypeError("I'm broken") # pragma: no cover
7989 return False
7990
7991 class G(Generic[T], metaclass=BrokenEq):
7992 pass
7993
7994 alias = G[int]
7995 self.assertIs(get_origin(alias), G)
7996 self.assertEqual(get_args(alias), (int,))
7997
7998 @skipIf(
7999 sys.version_info < (3, 11, 1),
8000 "Not yet backported for older versions of Python"
8001 )
8002 def test_paramspec_specialization(self):
8003 T = TypeVar("T")
8004 P = ParamSpec('P', default=[str, int])
8005 self.assertEqual(P.__default__, [str, int])
8006 class A(Generic[T, P]): ...
8007 self.assertEqual(A[float].__args__, (float, (str, int)))
8008 self.assertEqual(A[float, [range]].__args__, (float, (range,)))
8009
8010 @skipIf(
8011 sys.version_info < (3, 11, 1),
8012 "Not yet backported for older versions of Python"
8013 )
8014 def test_typevar_and_paramspec_specialization(self):
8015 T = TypeVar("T")
8016 U = TypeVar("U", default=float)
8017 P = ParamSpec('P', default=[str, int])
8018 self.assertEqual(P.__default__, [str, int])
8019 class A(Generic[T, U, P]): ...
8020 self.assertEqual(A[float].__args__, (float, float, (str, int)))
8021 self.assertEqual(A[float, int].__args__, (float, int, (str, int)))
8022 self.assertEqual(A[float, int, [range]].__args__, (float, int, (range,)))
8023
8024 @skipIf(
8025 sys.version_info < (3, 11, 1),
8026 "Not yet backported for older versions of Python"
8027 )
8028 def test_paramspec_and_typevar_specialization(self):
8029 T = TypeVar("T")
8030 P = ParamSpec('P', default=[str, int])
8031 U = TypeVar("U", default=float)
8032 self.assertEqual(P.__default__, [str, int])
8033 class A(Generic[T, P, U]): ...
8034 self.assertEqual(A[float].__args__, (float, (str, int), float))
8035 self.assertEqual(A[float, [range]].__args__, (float, (range,), float))
8036 self.assertEqual(A[float, [range], int].__args__, (float, (range,), int))
8037
8038
8039 class SentinelTestsMixin:
8040 @skip_if_py313_beta_1
8041 def test_pickling(self):
8042 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
8043 s = pickle.dumps(self.sentinel_type, proto)
8044 loaded = pickle.loads(s)
8045 self.assertIs(self.sentinel_type, loaded)
8046
8047 @skip_if_py313_beta_1
8048 def test_doc(self):
8049 self.assertIsInstance(self.sentinel_type.__doc__, str)
8050
8051 def test_constructor(self):
8052 with self.assertRaises(TypeError):
8053 type(self.sentinel_type)(1)
8054
8055 def test_no_call(self):
8056 with self.assertRaises(TypeError):
8057 self.sentinel_type()
8058
8059 @skip_if_py313_beta_1
8060 def test_immutable(self):
8061 with self.assertRaises(AttributeError):
8062 self.sentinel_type.foo = 'bar'
8063 with self.assertRaises(AttributeError):
8064 self.sentinel_type.foo
8065
8066 # TypeError is consistent with the behavior of NoneType
8067 with self.assertRaises(TypeError):
8068 type(self.sentinel_type).foo = 3
8069 with self.assertRaises(AttributeError):
8070 type(self.sentinel_type).foo
8071
8072
8073 class NoDefaultTests(SentinelTestsMixin, BaseTestCase):
8074 sentinel_type = NoDefault
8075
8076 def test_repr(self):
8077 if hasattr(typing, 'NoDefault'):
8078 mod_name = 'typing'
8079 else:
8080 mod_name = "typing_extensions"
8081 self.assertEqual(repr(NoDefault), f"{mod_name}.NoDefault")
8082
8083
8084 class NoExtraItemsTests(SentinelTestsMixin, BaseTestCase):
8085 sentinel_type = NoExtraItems
8086
8087 @skipIf(TYPING_3_15_0, "repr changed in 3.15")
8088 def test_repr(self):
8089 self.assertEqual(repr(NoExtraItems), "typing_extensions.NoExtraItems")
8090
8091 @skipUnless(TYPING_3_15_0, "repr changed in 3.15")
8092 def test_repr_py315(self):
8093 self.assertEqual(repr(NoExtraItems), "NoExtraItems")
8094
8095
8096 class TypeVarInferVarianceTests(BaseTestCase):
8097 def test_typevar(self):
8098 T = typing_extensions.TypeVar('T')
8099 self.assertFalse(T.__infer_variance__)
8100 T_infer = typing_extensions.TypeVar('T_infer', infer_variance=True)
8101 self.assertTrue(T_infer.__infer_variance__)
8102 T_noinfer = typing_extensions.TypeVar('T_noinfer', infer_variance=False)
8103 self.assertFalse(T_noinfer.__infer_variance__)
8104
8105 def test_pickle(self):
8106 global U, U_infer # pickle wants to reference the class by name
8107 U = typing_extensions.TypeVar('U')
8108 U_infer = typing_extensions.TypeVar('U_infer', infer_variance=True)
8109 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
8110 for typevar in (U, U_infer):
8111 z = pickle.loads(pickle.dumps(typevar, proto))
8112 self.assertEqual(z.__name__, typevar.__name__)
8113 self.assertEqual(z.__covariant__, typevar.__covariant__)
8114 self.assertEqual(z.__contravariant__, typevar.__contravariant__)
8115 self.assertEqual(z.__bound__, typevar.__bound__)
8116 self.assertEqual(z.__infer_variance__, typevar.__infer_variance__)
8117
8118
8119 class BufferTests(BaseTestCase):
8120 def test(self):
8121 self.assertIsInstance(memoryview(b''), Buffer)
8122 self.assertIsInstance(bytearray(), Buffer)
8123 self.assertIsInstance(b"x", Buffer)
8124 self.assertNotIsInstance(1, Buffer)
8125
8126 self.assertIsSubclass(bytearray, Buffer)
8127 self.assertIsSubclass(memoryview, Buffer)
8128 self.assertIsSubclass(bytes, Buffer)
8129 self.assertNotIsSubclass(int, Buffer)
8130
8131 class MyRegisteredBuffer:
8132 def __buffer__(self, flags: int) -> memoryview:
8133 return memoryview(b'') # pragma: no cover
8134
8135 # On 3.12, collections.abc.Buffer does a structural compatibility check
8136 if TYPING_3_12_0:
8137 self.assertIsInstance(MyRegisteredBuffer(), Buffer)
8138 self.assertIsSubclass(MyRegisteredBuffer, Buffer)
8139 else:
8140 self.assertNotIsInstance(MyRegisteredBuffer(), Buffer)
8141 self.assertNotIsSubclass(MyRegisteredBuffer, Buffer)
8142 Buffer.register(MyRegisteredBuffer)
8143 self.assertIsInstance(MyRegisteredBuffer(), Buffer)
8144 self.assertIsSubclass(MyRegisteredBuffer, Buffer)
8145
8146 class MySubclassedBuffer(Buffer):
8147 def __buffer__(self, flags: int) -> memoryview:
8148 return memoryview(b'') # pragma: no cover
8149
8150 self.assertIsInstance(MySubclassedBuffer(), Buffer)
8151 self.assertIsSubclass(MySubclassedBuffer, Buffer)
8152
8153
8154 class GetOriginalBasesTests(BaseTestCase):
8155 def test_basics(self):
8156 T = TypeVar('T')
8157 class A: pass
8158 class B(Generic[T]): pass
8159 class C(B[int]): pass
8160 class D(B[str], float): pass
8161 self.assertEqual(get_original_bases(A), (object,))
8162 self.assertEqual(get_original_bases(B), (Generic[T],))
8163 self.assertEqual(get_original_bases(C), (B[int],))
8164 self.assertEqual(get_original_bases(int), (object,))
8165 self.assertEqual(get_original_bases(D), (B[str], float))
8166
8167 with self.assertRaisesRegex(TypeError, "Expected an instance of type"):
8168 get_original_bases(object())
8169
8170 def test_builtin_generics(self):
8171 class E(list[T]): pass
8172 class F(list[int]): pass
8173
8174 self.assertEqual(get_original_bases(E), (list[T],))
8175 self.assertEqual(get_original_bases(F), (list[int],))
8176
8177 @skipIf(
8178 sys.version_info[:3] == (3, 12, 0) and sys.version_info[3] in {"alpha", "beta"},
8179 "Early versions of py312 had a bug"
8180 )
8181 def test_concrete_subclasses_of_generic_classes(self):
8182 T = TypeVar("T")
8183
8184 class FirstBase(Generic[T]): pass
8185 class SecondBase(Generic[T]): pass
8186 class First(FirstBase[int]): pass
8187 class Second(SecondBase[int]): pass
8188 class G(First, Second): pass
8189 self.assertEqual(get_original_bases(G), (First, Second))
8190
8191 class First_(Generic[T]): pass
8192 class Second_(Generic[T]): pass
8193 class H(First_, Second_): pass
8194 self.assertEqual(get_original_bases(H), (First_, Second_))
8195
8196 def test_namedtuples(self):
8197 # On 3.12, this should work well with typing.NamedTuple and typing_extensions.NamedTuple
8198 # On lower versions, it will only work fully with typing_extensions.NamedTuple
8199 if sys.version_info >= (3, 12):
8200 namedtuple_classes = (typing.NamedTuple, typing_extensions.NamedTuple)
8201 else:
8202 namedtuple_classes = (typing_extensions.NamedTuple,)
8203
8204 for NamedTuple in namedtuple_classes: # noqa: F402
8205 with self.subTest(cls=NamedTuple):
8206 class ClassBasedNamedTuple(NamedTuple):
8207 x: int
8208
8209 class GenericNamedTuple(NamedTuple, Generic[T]):
8210 x: T
8211
8212 CallBasedNamedTuple = NamedTuple("CallBasedNamedTuple", [("x", int)])
8213
8214 self.assertIs(
8215 get_original_bases(ClassBasedNamedTuple)[0], NamedTuple
8216 )
8217 self.assertEqual(
8218 get_original_bases(GenericNamedTuple),
8219 (NamedTuple, Generic[T])
8220 )
8221 self.assertIs(
8222 get_original_bases(CallBasedNamedTuple)[0], NamedTuple
8223 )
8224
8225 def test_typeddicts(self):
8226 # On 3.12, this should work well with typing.TypedDict and typing_extensions.TypedDict
8227 # On lower versions, it will only work fully with typing_extensions.TypedDict
8228 if sys.version_info >= (3, 12):
8229 typeddict_classes = (typing.TypedDict, typing_extensions.TypedDict)
8230 else:
8231 typeddict_classes = (typing_extensions.TypedDict,)
8232
8233 for TypedDict in typeddict_classes: # noqa: F402
8234 with self.subTest(cls=TypedDict):
8235 class ClassBasedTypedDict(TypedDict):
8236 x: int
8237
8238 class GenericTypedDict(TypedDict, Generic[T]):
8239 x: T
8240
8241 CallBasedTypedDict = TypedDict("CallBasedTypedDict", {"x": int})
8242
8243 self.assertIs(
8244 get_original_bases(ClassBasedTypedDict)[0],
8245 TypedDict
8246 )
8247 self.assertEqual(
8248 get_original_bases(GenericTypedDict),
8249 (TypedDict, Generic[T])
8250 )
8251 self.assertIs(
8252 get_original_bases(CallBasedTypedDict)[0],
8253 TypedDict
8254 )
8255
8256
8257 class TypeAliasTypeTests(BaseTestCase):
8258 def test_attributes(self):
8259 Simple = TypeAliasType("Simple", int)
8260 self.assertEqual(Simple.__name__, "Simple")
8261 self.assertIs(Simple.__value__, int)
8262 self.assertEqual(Simple.__type_params__, ())
8263 self.assertEqual(Simple.__parameters__, ())
8264
8265 T = TypeVar("T")
8266 ListOrSetT = TypeAliasType("ListOrSetT", Union[List[T], Set[T]], type_params=(T,))
8267 self.assertEqual(ListOrSetT.__name__, "ListOrSetT")
8268 self.assertEqual(ListOrSetT.__value__, Union[List[T], Set[T]])
8269 self.assertEqual(ListOrSetT.__type_params__, (T,))
8270 self.assertEqual(ListOrSetT.__parameters__, (T,))
8271
8272 Ts = TypeVarTuple("Ts")
8273 Variadic = TypeAliasType("Variadic", Tuple[int, Unpack[Ts]], type_params=(Ts,))
8274 self.assertEqual(Variadic.__name__, "Variadic")
8275 self.assertEqual(Variadic.__value__, Tuple[int, Unpack[Ts]])
8276 self.assertEqual(Variadic.__type_params__, (Ts,))
8277 self.assertEqual(Variadic.__parameters__, tuple(iter(Ts)))
8278
8279 P = ParamSpec('P')
8280 CallableP = TypeAliasType("CallableP", Callable[P, Any], type_params=(P, ))
8281 self.assertEqual(CallableP.__name__, "CallableP")
8282 self.assertEqual(CallableP.__value__, Callable[P, Any])
8283 self.assertEqual(CallableP.__type_params__, (P,))
8284 self.assertEqual(CallableP.__parameters__, (P,))
8285
8286 def test_alias_types_and_substitutions(self):
8287 T = TypeVar('T')
8288 T2 = TypeVar('T2')
8289 T_default = TypeVar("T_default", default=int)
8290 Ts = TypeVarTuple("Ts")
8291 P = ParamSpec('P')
8292
8293 test_argument_cases = {
8294 # arguments : expected parameters
8295 int : (),
8296 ... : (),
8297 None : (),
8298 T2 : (T2,),
8299 Union[int, List[T2]] : (T2,),
8300 Tuple[int, str] : (),
8301 Tuple[T, T_default, T2] : (T, T_default, T2),
8302 Tuple[Unpack[Ts]] : (Ts,),
8303 Callable[[Unpack[Ts]], T2] : (Ts, T2),
8304 Callable[P, T2] : (P, T2),
8305 Callable[Concatenate[T2, P], T_default] : (T2, P, T_default),
8306 TypeAliasType("NestedAlias", List[T], type_params=(T,))[T2] : (T2,),
8307 Unpack[Ts] : (Ts,),
8308 Unpack[Tuple[int, T2]] : (T2,),
8309 Concatenate[int, P] : (P,),
8310 # Not tested usage of bare TypeVarTuple, would need 3.11+
8311 # Ts : (Ts,), # invalid case
8312 }
8313
8314 test_alias_cases = [
8315 # Simple cases
8316 TypeAliasType("ListT", List[T], type_params=(T,)),
8317 TypeAliasType("UnionT", Union[int, List[T]], type_params=(T,)),
8318 # Value has no parameter but in type_param
8319 TypeAliasType("ValueWithoutT", int, type_params=(T,)),
8320 # Callable
8321 TypeAliasType("CallableP", Callable[P, Any], type_params=(P, )),
8322 TypeAliasType("CallableT", Callable[..., T], type_params=(T, )),
8323 TypeAliasType("CallableTs", Callable[[Unpack[Ts]], Any], type_params=(Ts, )),
8324 # TypeVarTuple
8325 TypeAliasType("Variadic", Tuple[int, Unpack[Ts]], type_params=(Ts,)),
8326 # TypeVar with default
8327 TypeAliasType("TupleT_default", Tuple[T_default, T], type_params=(T, T_default)),
8328 TypeAliasType("CallableT_default", Callable[[T], T_default], type_params=(T, T_default)),
8329 ]
8330
8331 for alias in test_alias_cases:
8332 with self.subTest(alias=alias, args=[]):
8333 subscripted = alias[[]]
8334 self.assertEqual(get_args(subscripted), ([],))
8335 self.assertEqual(subscripted.__parameters__, ())
8336 with self.subTest(alias=alias, args=()):
8337 subscripted = alias[()]
8338 self.assertEqual(get_args(subscripted), ())
8339 self.assertEqual(subscripted.__parameters__, ())
8340 with self.subTest(alias=alias, args=(int, float)):
8341 subscripted = alias[int, float]
8342 self.assertEqual(get_args(subscripted), (int, float))
8343 self.assertEqual(subscripted.__parameters__, ())
8344 with self.subTest(alias=alias, args=[int, float]):
8345 subscripted = alias[[int, float]]
8346 self.assertEqual(get_args(subscripted), ([int, float],))
8347 self.assertEqual(subscripted.__parameters__, ())
8348 for expected_args, expected_parameters in test_argument_cases.items():
8349 with self.subTest(alias=alias, args=expected_args):
8350 self.assertEqual(get_args(alias[expected_args]), (expected_args,))
8351 self.assertEqual(alias[expected_args].__parameters__, expected_parameters)
8352
8353 def test_cannot_set_attributes(self):
8354 Simple = TypeAliasType("Simple", int)
8355 with self.assertRaisesRegex(AttributeError, "readonly attribute"):
8356 Simple.__name__ = "NewName"
8357 with self.assertRaisesRegex(
8358 AttributeError,
8359 "attribute '__value__' of 'typing.TypeAliasType' objects is not writable",
8360 ):
8361 Simple.__value__ = str
8362 with self.assertRaisesRegex(
8363 AttributeError,
8364 "attribute '__type_params__' of 'typing.TypeAliasType' objects is not writable",
8365 ):
8366 Simple.__type_params__ = (T,)
8367 with self.assertRaisesRegex(
8368 AttributeError,
8369 "attribute '__parameters__' of 'typing.TypeAliasType' objects is not writable",
8370 ):
8371 Simple.__parameters__ = (T,)
8372
8373 # __module__ is the exception---it's assignable
8374 module_sentinel = object()
8375 Simple.__module__ = module_sentinel
8376 self.assertIs(Simple.__module__, module_sentinel)
8377
8378 with self.assertRaisesRegex(
8379 AttributeError,
8380 "'typing.TypeAliasType' object has no attribute 'some_attribute'",
8381 ):
8382 Simple.some_attribute = "not allowed"
8383
8384 def test_cannot_delete_attributes(self):
8385 Simple = TypeAliasType("Simple", int)
8386 with self.assertRaisesRegex(AttributeError, "readonly attribute"):
8387 del Simple.__name__
8388 with self.assertRaisesRegex(
8389 AttributeError,
8390 "attribute '__value__' of 'typing.TypeAliasType' objects is not writable",
8391 ):
8392 del Simple.__value__
8393 with self.assertRaisesRegex(
8394 AttributeError,
8395 "'typing.TypeAliasType' object has no attribute 'some_attribute'",
8396 ):
8397 del Simple.some_attribute
8398
8399 def test_or(self):
8400 Alias = TypeAliasType("Alias", int)
8401 if sys.version_info >= (3, 10):
8402 self.assertEqual(Alias | int, Union[Alias, int])
8403 self.assertEqual(Alias | None, Union[Alias, None])
8404 self.assertEqual(Alias | (int | str), Union[Alias, int | str])
8405 self.assertEqual(Alias | list[float], Union[Alias, list[float]])
8406
8407 if sys.version_info >= (3, 12):
8408 Alias2 = typing.TypeAliasType("Alias2", str)
8409 self.assertEqual(Alias | Alias2, Union[Alias, Alias2])
8410 else:
8411 with self.assertRaises(TypeError):
8412 Alias | int
8413 # Rejected on all versions
8414 with self.assertRaises(TypeError):
8415 Alias | "Ref"
8416
8417 def test_getitem(self):
8418 T = TypeVar('T')
8419 ListOrSetT = TypeAliasType("ListOrSetT", Union[List[T], Set[T]], type_params=(T,))
8420 subscripted = ListOrSetT[int]
8421 self.assertEqual(get_args(subscripted), (int,))
8422 self.assertIs(get_origin(subscripted), ListOrSetT)
8423 with self.assertRaisesRegex(TypeError,
8424 "not a generic class"
8425 # types.GenericAlias raises a different error in 3.10
8426 if sys.version_info[:2] != (3, 10)
8427 else "There are no type variables left in ListOrSetT"
8428 ):
8429 subscripted[int]
8430
8431
8432 still_generic = ListOrSetT[Iterable[T]]
8433 self.assertEqual(get_args(still_generic), (Iterable[T],))
8434 self.assertIs(get_origin(still_generic), ListOrSetT)
8435 fully_subscripted = still_generic[float]
8436 self.assertEqual(get_args(fully_subscripted), (Iterable[float],))
8437 self.assertIs(get_origin(fully_subscripted), ListOrSetT)
8438
8439 ValueWithoutTypeVar = TypeAliasType("ValueWithoutTypeVar", int, type_params=(T,))
8440 still_subscripted = ValueWithoutTypeVar[str]
8441 self.assertEqual(get_args(still_subscripted), (str,))
8442
8443 def test_callable_without_concatenate(self):
8444 P = ParamSpec('P')
8445 CallableP = TypeAliasType("CallableP", Callable[P, Any], type_params=(P,))
8446 get_args_test_cases = [
8447 # List of (alias, expected_args)
8448 # () -> Any
8449 (CallableP[()], ()),
8450 (CallableP[[]], ([],)),
8451 # (int) -> Any
8452 (CallableP[int], (int,)),
8453 (CallableP[[int]], ([int],)),
8454 # (int, int) -> Any
8455 (CallableP[int, int], (int, int)),
8456 (CallableP[[int, int]], ([int, int],)),
8457 # (...) -> Any
8458 (CallableP[...], (...,)),
8459 # (int, ...) -> Any
8460 (CallableP[[int, ...]], ([int, ...],)),
8461 ]
8462
8463 for index, (expression, expected_args) in enumerate(get_args_test_cases):
8464 with self.subTest(index=index, expression=expression):
8465 self.assertEqual(get_args(expression), expected_args)
8466
8467 self.assertEqual(CallableP[...], CallableP[(...,)])
8468 # (T) -> Any
8469 CallableT = CallableP[T]
8470 self.assertEqual(get_args(CallableT), (T,))
8471 self.assertEqual(CallableT.__parameters__, (T,))
8472
8473 def test_callable_with_concatenate(self):
8474 P = ParamSpec('P')
8475 P2 = ParamSpec('P2')
8476 CallableP = TypeAliasType("CallableP", Callable[P, Any], type_params=(P,))
8477
8478 callable_concat = CallableP[Concatenate[int, P2]]
8479 self.assertEqual(callable_concat.__parameters__, (P2,))
8480 concat_usage = callable_concat[str]
8481 with self.subTest("get_args of Concatenate in TypeAliasType"):
8482 if not TYPING_3_10_0:
8483 # args are: ([<class 'int'>, ~P2],)
8484 self.skipTest("Nested ParamSpec is not substituted")
8485 self.assertEqual(get_args(concat_usage), ((int, str),))
8486 with self.subTest("Equality of parameter_expression without []"):
8487 if not TYPING_3_10_0:
8488 self.skipTest("Nested list is invalid type form")
8489 self.assertEqual(concat_usage, callable_concat[[str]])
8490
8491 def test_substitution(self):
8492 T = TypeVar('T')
8493 Ts = TypeVarTuple("Ts")
8494
8495 CallableTs = TypeAliasType("CallableTs", Callable[[Unpack[Ts]], Any], type_params=(Ts, ))
8496 unpack_callable = CallableTs[Unpack[Tuple[int, T]]]
8497 self.assertEqual(get_args(unpack_callable), (Unpack[Tuple[int, T]],))
8498
8499 P = ParamSpec('P')
8500 CallableP = TypeAliasType("CallableP", Callable[P, T], type_params=(P, T))
8501 callable_concat = CallableP[Concatenate[int, P], Any]
8502 self.assertEqual(get_args(callable_concat), (Concatenate[int, P], Any))
8503
8504 def test_wrong_amount_of_parameters(self):
8505 T = TypeVar('T')
8506 T2 = TypeVar("T2")
8507 P = ParamSpec('P')
8508 ListOrSetT = TypeAliasType("ListOrSetT", Union[List[T], Set[T]], type_params=(T,))
8509 TwoT = TypeAliasType("TwoT", Union[List[T], Set[T2]], type_params=(T, T2))
8510 CallablePT = TypeAliasType("CallablePT", Callable[P, T], type_params=(P, T))
8511
8512 # Not enough parameters
8513 test_cases = [
8514 # not_enough
8515 (TwoT[int], [(int,), ()]),
8516 (TwoT[T], [(T,), (T,)]),
8517 # callable and not enough
8518 (CallablePT[int], [(int,), ()]),
8519 # too many
8520 (ListOrSetT[int, bool], [(int, bool), ()]),
8521 # callable and too many
8522 (CallablePT[str, float, int], [(str, float, int), ()]),
8523 # Check if TypeVar is still present even if over substituted
8524 (ListOrSetT[int, T], [(int, T), (T,)]),
8525 # With and without list for ParamSpec
8526 (CallablePT[str, float, T], [(str, float, T), (T,)]),
8527 (CallablePT[[str], float, int, T2], [([str], float, int, T2), (T2,)]),
8528 ]
8529
8530 for index, (alias, [expected_args, expected_params]) in enumerate(test_cases):
8531 with self.subTest(index=index, alias=alias):
8532 self.assertEqual(get_args(alias), expected_args)
8533 self.assertEqual(alias.__parameters__, expected_params)
8534
8535 # The condition should align with the version of GeneriAlias usage in __getitem__ or be 3.11+
8536 @skipIf(TYPING_3_10_0, "Most arguments are allowed in 3.11+ or with GenericAlias")
8537 def test_invalid_cases_before_3_10(self):
8538 T = TypeVar('T')
8539 ListOrSetT = TypeAliasType("ListOrSetT", Union[List[T], Set[T]], type_params=(T,))
8540 with self.assertRaises(TypeError):
8541 ListOrSetT[Generic[T]]
8542 with self.assertRaises(TypeError):
8543 ListOrSetT[(Generic[T], )]
8544
8545 def test_unpack_parameter_collection(self):
8546 Ts = TypeVarTuple("Ts")
8547
8548 class Foo(Generic[Unpack[Ts]]):
8549 bar: Tuple[Unpack[Ts]]
8550
8551 FooAlias = TypeAliasType("FooAlias", Foo[Unpack[Ts]], type_params=(Ts,))
8552 self.assertEqual(FooAlias[Unpack[Tuple[str]]].__parameters__, ())
8553 self.assertEqual(FooAlias[Unpack[Tuple[T]]].__parameters__, (T,))
8554
8555 P = ParamSpec("P")
8556 CallableP = TypeAliasType("CallableP", Callable[P, Any], type_params=(P,))
8557 call_int_T = CallableP[Unpack[Tuple[int, T]]]
8558 self.assertEqual(call_int_T.__parameters__, (T,))
8559
8560 def test_alias_attributes(self):
8561 T = TypeVar('T')
8562 T2 = TypeVar('T2')
8563 ListOrSetT = TypeAliasType("ListOrSetT", Union[List[T], Set[T]], type_params=(T,))
8564
8565 subscripted = ListOrSetT[int]
8566 self.assertEqual(subscripted.__module__, ListOrSetT.__module__)
8567 self.assertEqual(subscripted.__name__, "ListOrSetT")
8568 self.assertEqual(subscripted.__value__, Union[List[T], Set[T]])
8569 self.assertEqual(subscripted.__type_params__, (T,))
8570
8571 still_generic = ListOrSetT[Iterable[T2]]
8572 self.assertEqual(still_generic.__module__, ListOrSetT.__module__)
8573 self.assertEqual(still_generic.__name__, "ListOrSetT")
8574 self.assertEqual(still_generic.__value__, Union[List[T], Set[T]])
8575 self.assertEqual(still_generic.__type_params__, (T,))
8576
8577 fully_subscripted = still_generic[float]
8578 self.assertEqual(fully_subscripted.__module__, ListOrSetT.__module__)
8579 self.assertEqual(fully_subscripted.__name__, "ListOrSetT")
8580 self.assertEqual(fully_subscripted.__value__, Union[List[T], Set[T]])
8581 self.assertEqual(fully_subscripted.__type_params__, (T,))
8582
8583 def test_subscription_without_type_params(self):
8584 Simple = TypeAliasType("Simple", int)
8585 with self.assertRaises(TypeError, msg="Only generic type aliases are subscriptable"):
8586 Simple[int]
8587
8588 # A TypeVar in the value does not allow subscription
8589 T = TypeVar('T')
8590 MissingTypeParamsErr = TypeAliasType("MissingTypeParamsErr", List[T])
8591 self.assertEqual(MissingTypeParamsErr.__type_params__, ())
8592 self.assertEqual(MissingTypeParamsErr.__parameters__, ())
8593 with self.assertRaises(TypeError, msg="Only generic type aliases are subscriptable"):
8594 MissingTypeParamsErr[int]
8595
8596 def test_pickle(self):
8597 global Alias
8598 Alias = TypeAliasType("Alias", int)
8599 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
8600 with self.subTest(proto=proto):
8601 pickled = pickle.dumps(Alias, proto)
8602 unpickled = pickle.loads(pickled)
8603 self.assertIs(unpickled, Alias)
8604
8605 def test_no_instance_subclassing(self):
8606 with self.assertRaises(TypeError):
8607 class MyAlias(TypeAliasType):
8608 pass
8609
8610 def test_type_var_compatibility(self):
8611 # Regression test to assure compatibility with typing variants
8612 typingT = typing.TypeVar('typingT')
8613 T1 = TypeAliasType("TypingTypeVar", ..., type_params=(typingT,))
8614 self.assertEqual(T1.__type_params__, (typingT,))
8615
8616 # Test typing_extensions backports
8617 textT = TypeVar('textT')
8618 T2 = TypeAliasType("TypingExtTypeVar", ..., type_params=(textT,))
8619 self.assertEqual(T2.__type_params__, (textT,))
8620
8621 textP = ParamSpec("textP")
8622 T3 = TypeAliasType("TypingExtParamSpec", ..., type_params=(textP,))
8623 self.assertEqual(T3.__type_params__, (textP,))
8624
8625 textTs = TypeVarTuple("textTs")
8626 T4 = TypeAliasType("TypingExtTypeVarTuple", ..., type_params=(textTs,))
8627 self.assertEqual(T4.__type_params__, (textTs,))
8628
8629 @skipUnless(TYPING_3_10_0, "typing.ParamSpec is not available before 3.10")
8630 def test_param_spec_compatibility(self):
8631 # Regression test to assure compatibility with typing variant
8632 typingP = typing.ParamSpec("typingP")
8633 T5 = TypeAliasType("TypingParamSpec", ..., type_params=(typingP,))
8634 self.assertEqual(T5.__type_params__, (typingP,))
8635
8636 @skipUnless(TYPING_3_12_0, "typing.TypeVarTuple is not available before 3.12")
8637 def test_type_var_tuple_compatibility(self):
8638 # Regression test to assure compatibility with typing variant
8639 typingTs = typing.TypeVarTuple("typingTs")
8640 T6 = TypeAliasType("TypingTypeVarTuple", ..., type_params=(typingTs,))
8641 self.assertEqual(T6.__type_params__, (typingTs,))
8642
8643 def test_type_params_possibilities(self):
8644 T = TypeVar('T')
8645 # Test not a tuple
8646 with self.assertRaisesRegex(TypeError, "type_params must be a tuple"):
8647 TypeAliasType("InvalidTypeParams", List[T], type_params=[T])
8648
8649 # Test default order and other invalid inputs
8650 T_default = TypeVar('T_default', default=int)
8651 Ts = TypeVarTuple('Ts')
8652 Ts_default = TypeVarTuple('Ts_default', default=Unpack[Tuple[str, int]])
8653 P = ParamSpec('P')
8654 P_default = ParamSpec('P_default', default=[str, int])
8655
8656 # NOTE: PEP 696 states: "TypeVars with defaults cannot immediately follow TypeVarTuples"
8657 # this is currently not enforced for the type statement and is not tested.
8658 # PEP 695: Double usage of the same name is also not enforced and not tested.
8659 valid_cases = [
8660 (T, P, Ts),
8661 (T, Ts_default),
8662 (P_default, T_default),
8663 (P, T_default, Ts_default),
8664 (T_default, P_default, Ts_default),
8665 ]
8666 invalid_cases = [
8667 ((T_default, T), f"non-default type parameter '{T!r}' follows default"),
8668 ((P_default, P), f"non-default type parameter '{P!r}' follows default"),
8669 ((Ts_default, T), f"non-default type parameter '{T!r}' follows default"),
8670 # Only type params are accepted
8671 ((1,), "Expected a type param, got 1"),
8672 ((str,), f"Expected a type param, got {str!r}"),
8673 # Unpack is not a TypeVar but isinstance(Unpack[Ts], TypeVar) is True in Python < 3.12
8674 ((Unpack[Ts],), f"Expected a type param, got {re.escape(repr(Unpack[Ts]))}"),
8675 ]
8676
8677 for case in valid_cases:
8678 with self.subTest(type_params=case):
8679 TypeAliasType("OkCase", List[T], type_params=case)
8680 for case, msg in invalid_cases:
8681 with self.subTest(type_params=case):
8682 with self.assertRaisesRegex(TypeError, msg):
8683 TypeAliasType("InvalidCase", List[T], type_params=case)
8684
8685 class DocTests(BaseTestCase):
8686 def test_annotation(self):
8687
8688 def hi(to: Annotated[str, Doc("Who to say hi to")]) -> None: pass
8689
8690 hints = get_type_hints(hi, include_extras=True)
8691 doc_info = hints["to"].__metadata__[0]
8692 self.assertEqual(doc_info.documentation, "Who to say hi to")
8693 self.assertIsInstance(doc_info, Doc)
8694
8695 def test_repr(self):
8696 doc_info = Doc("Who to say hi to")
8697 self.assertEqual(repr(doc_info), "Doc('Who to say hi to')")
8698
8699 def test_hashability(self):
8700 doc_info = Doc("Who to say hi to")
8701 self.assertIsInstance(hash(doc_info), int)
8702 self.assertNotEqual(hash(doc_info), hash(Doc("Who not to say hi to")))
8703
8704 def test_equality(self):
8705 doc_info = Doc("Who to say hi to")
8706 # Equal to itself
8707 self.assertEqual(doc_info, doc_info)
8708 # Equal to another instance with the same string
8709 self.assertEqual(doc_info, Doc("Who to say hi to"))
8710 # Not equal to another instance with a different string
8711 self.assertNotEqual(doc_info, Doc("Who not to say hi to"))
8712
8713 def test_pickle(self):
8714 doc_info = Doc("Who to say hi to")
8715 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
8716 pickled = pickle.dumps(doc_info, protocol=proto)
8717 self.assertEqual(doc_info, pickle.loads(pickled))
8718
8719
8720 @skipUnless(
8721 hasattr(typing_extensions, "CapsuleType"),
8722 "CapsuleType is not available on all Python implementations"
8723 )
8724 class CapsuleTypeTests(BaseTestCase):
8725 def test_capsule_type(self):
8726 import _datetime
8727 self.assertIsInstance(_datetime.datetime_CAPI, typing_extensions.CapsuleType)
8728
8729
8730 class MyClass:
8731 def __repr__(self):
8732 return "my repr"
8733
8734
8735 class TestTypeRepr(BaseTestCase):
8736 def test_custom_types(self):
8737
8738 class Nested:
8739 pass
8740
8741 def nested():
8742 pass
8743
8744 self.assertEqual(type_repr(MyClass), f"{__name__}.MyClass")
8745 self.assertEqual(
8746 type_repr(Nested),
8747 f"{__name__}.TestTypeRepr.test_custom_types.<locals>.Nested",
8748 )
8749 self.assertEqual(
8750 type_repr(nested),
8751 f"{__name__}.TestTypeRepr.test_custom_types.<locals>.nested",
8752 )
8753 self.assertEqual(type_repr(times_three), f"{__name__}.times_three")
8754 self.assertEqual(type_repr(Format.VALUE), repr(Format.VALUE))
8755 self.assertEqual(type_repr(MyClass()), "my repr")
8756
8757 def test_builtin_types(self):
8758 self.assertEqual(type_repr(int), "int")
8759 self.assertEqual(type_repr(object), "object")
8760 self.assertEqual(type_repr(None), "None")
8761 self.assertEqual(type_repr(len), "len")
8762 self.assertEqual(type_repr(1), "1")
8763 self.assertEqual(type_repr("1"), "'1'")
8764 self.assertEqual(type_repr(''), "''")
8765 self.assertEqual(type_repr(...), "...")
8766
8767
8768 def times_three(fn):
8769 @functools.wraps(fn)
8770 def wrapper(a, b):
8771 return fn(a * 3, b * 3)
8772
8773 return wrapper
8774
8775
8776 class TestGetAnnotations(BaseTestCase):
8777 @classmethod
8778 def setUpClass(cls):
8779 with tempfile.TemporaryDirectory() as tempdir:
8780 sys.path.append(tempdir)
8781 Path(tempdir, "inspect_stock_annotations.py").write_text(STOCK_ANNOTATIONS)
8782 Path(tempdir, "inspect_stringized_annotations.py").write_text(STRINGIZED_ANNOTATIONS)
8783 Path(tempdir, "inspect_stringized_annotations_2.py").write_text(STRINGIZED_ANNOTATIONS_2)
8784 cls.inspect_stock_annotations = importlib.import_module("inspect_stock_annotations")
8785 cls.inspect_stringized_annotations = importlib.import_module("inspect_stringized_annotations")
8786 cls.inspect_stringized_annotations_2 = importlib.import_module("inspect_stringized_annotations_2")
8787 sys.path.pop()
8788
8789 @classmethod
8790 def tearDownClass(cls):
8791 for modname in (
8792 "inspect_stock_annotations",
8793 "inspect_stringized_annotations",
8794 "inspect_stringized_annotations_2",
8795 ):
8796 delattr(cls, modname)
8797 del sys.modules[modname]
8798
8799 def test_builtin_type(self):
8800 self.assertEqual(get_annotations(int), {})
8801 self.assertEqual(get_annotations(object), {})
8802
8803 def test_format(self):
8804 def f1(a: int):
8805 pass
8806
8807 def f2(a: "undefined"): # noqa: F821
8808 pass # pragma: no cover
8809
8810 self.assertEqual(
8811 get_annotations(f1, format=Format.VALUE), {"a": int}
8812 )
8813 self.assertEqual(get_annotations(f1, format=1), {"a": int})
8814
8815 self.assertEqual(
8816 get_annotations(f2, format=Format.FORWARDREF),
8817 {"a": "undefined"},
8818 )
8819 # Test that the raw int also works
8820 self.assertEqual(
8821 get_annotations(f2, format=Format.FORWARDREF.value),
8822 {"a": "undefined"},
8823 )
8824
8825 self.assertEqual(
8826 get_annotations(f1, format=Format.STRING),
8827 {"a": "int"},
8828 )
8829 self.assertEqual(
8830 get_annotations(f1, format=Format.STRING.value),
8831 {"a": "int"},
8832 )
8833
8834 with self.assertRaises(ValueError):
8835 get_annotations(f1, format=0)
8836
8837 with self.assertRaises(ValueError):
8838 get_annotations(f1, format=42)
8839
8840 def test_custom_object_with_annotations(self):
8841 class C:
8842 def __init__(self, x: int = 0, y: str = ""):
8843 self.__annotations__ = {"x": int, "y": str}
8844
8845 self.assertEqual(get_annotations(C()), {"x": int, "y": str})
8846
8847 def test_custom_format_eval_str(self):
8848 def foo():
8849 pass
8850
8851 with self.assertRaises(ValueError):
8852 get_annotations(
8853 foo, format=Format.FORWARDREF, eval_str=True
8854 )
8855 get_annotations(
8856 foo, format=Format.STRING, eval_str=True
8857 )
8858
8859 def test_stock_annotations(self):
8860 def foo(a: int, b: str):
8861 pass
8862
8863 for format in (Format.VALUE, Format.FORWARDREF):
8864 with self.subTest(format=format):
8865 self.assertEqual(
8866 get_annotations(foo, format=format),
8867 {"a": int, "b": str},
8868 )
8869 self.assertEqual(
8870 get_annotations(foo, format=Format.STRING),
8871 {"a": "int", "b": "str"},
8872 )
8873
8874 foo.__annotations__ = {"a": "foo", "b": "str"}
8875 for format in Format:
8876 with self.subTest(format=format):
8877 if format is Format.VALUE_WITH_FAKE_GLOBALS:
8878 with self.assertRaisesRegex(
8879 ValueError,
8880 "The VALUE_WITH_FAKE_GLOBALS format is for internal use only"
8881 ):
8882 get_annotations(foo, format=format)
8883 else:
8884 self.assertEqual(
8885 get_annotations(foo, format=format),
8886 {"a": "foo", "b": "str"},
8887 )
8888
8889 self.assertEqual(
8890 get_annotations(foo, eval_str=True, locals=locals()),
8891 {"a": foo, "b": str},
8892 )
8893 self.assertEqual(
8894 get_annotations(foo, eval_str=True, globals=locals()),
8895 {"a": foo, "b": str},
8896 )
8897
8898 def test_stock_annotations_in_module(self):
8899 isa = self.inspect_stock_annotations
8900
8901 for kwargs in [
8902 {},
8903 {"eval_str": False},
8904 {"format": Format.VALUE},
8905 {"format": Format.FORWARDREF},
8906 {"format": Format.VALUE, "eval_str": False},
8907 {"format": Format.FORWARDREF, "eval_str": False},
8908 ]:
8909 with self.subTest(**kwargs):
8910 self.assertEqual(
8911 get_annotations(isa, **kwargs), {"a": int, "b": str}
8912 )
8913 self.assertEqual(
8914 get_annotations(isa.MyClass, **kwargs),
8915 {"a": int, "b": str},
8916 )
8917 self.assertEqual(
8918 get_annotations(isa.function, **kwargs),
8919 {"a": int, "b": str, "return": isa.MyClass},
8920 )
8921 self.assertEqual(
8922 get_annotations(isa.function2, **kwargs),
8923 {"a": int, "b": "str", "c": isa.MyClass, "return": isa.MyClass},
8924 )
8925 self.assertEqual(
8926 get_annotations(isa.function3, **kwargs),
8927 {"a": "int", "b": "str", "c": "MyClass"},
8928 )
8929 self.assertEqual(
8930 get_annotations(inspect, **kwargs), {}
8931 ) # inspect module has no annotations
8932 self.assertEqual(
8933 get_annotations(isa.UnannotatedClass, **kwargs), {}
8934 )
8935 self.assertEqual(
8936 get_annotations(isa.unannotated_function, **kwargs), {}
8937 )
8938
8939 for kwargs in [
8940 {"eval_str": True},
8941 {"format": Format.VALUE, "eval_str": True},
8942 ]:
8943 with self.subTest(**kwargs):
8944 self.assertEqual(
8945 get_annotations(isa, **kwargs), {"a": int, "b": str}
8946 )
8947 self.assertEqual(
8948 get_annotations(isa.MyClass, **kwargs),
8949 {"a": int, "b": str},
8950 )
8951 self.assertEqual(
8952 get_annotations(isa.function, **kwargs),
8953 {"a": int, "b": str, "return": isa.MyClass},
8954 )
8955 self.assertEqual(
8956 get_annotations(isa.function2, **kwargs),
8957 {"a": int, "b": str, "c": isa.MyClass, "return": isa.MyClass},
8958 )
8959 self.assertEqual(
8960 get_annotations(isa.function3, **kwargs),
8961 {"a": int, "b": str, "c": isa.MyClass},
8962 )
8963 self.assertEqual(get_annotations(inspect, **kwargs), {})
8964 self.assertEqual(
8965 get_annotations(isa.UnannotatedClass, **kwargs), {}
8966 )
8967 self.assertEqual(
8968 get_annotations(isa.unannotated_function, **kwargs), {}
8969 )
8970
8971 self.assertEqual(
8972 get_annotations(isa, format=Format.STRING),
8973 {"a": "int", "b": "str"},
8974 )
8975 self.assertEqual(
8976 get_annotations(isa.MyClass, format=Format.STRING),
8977 {"a": "int", "b": "str"},
8978 )
8979 mycls = "MyClass" if sys.version_info >= (3, 14) else "inspect_stock_annotations.MyClass"
8980 self.assertEqual(
8981 get_annotations(isa.function, format=Format.STRING),
8982 {"a": "int", "b": "str", "return": mycls},
8983 )
8984 self.assertEqual(
8985 get_annotations(
8986 isa.function2, format=Format.STRING
8987 ),
8988 {"a": "int", "b": "str", "c": mycls, "return": mycls},
8989 )
8990 self.assertEqual(
8991 get_annotations(
8992 isa.function3, format=Format.STRING
8993 ),
8994 {"a": "int", "b": "str", "c": "MyClass"},
8995 )
8996 self.assertEqual(
8997 get_annotations(inspect, format=Format.STRING),
8998 {},
8999 )
9000 self.assertEqual(
9001 get_annotations(
9002 isa.UnannotatedClass, format=Format.STRING
9003 ),
9004 {},
9005 )
9006 self.assertEqual(
9007 get_annotations(
9008 isa.unannotated_function, format=Format.STRING
9009 ),
9010 {},
9011 )
9012
9013 def test_stock_annotations_on_wrapper(self):
9014 isa = self.inspect_stock_annotations
9015
9016 wrapped = times_three(isa.function)
9017 self.assertEqual(wrapped(1, "x"), isa.MyClass(3, "xxx"))
9018 self.assertIsNot(wrapped.__globals__, isa.function.__globals__)
9019 self.assertEqual(
9020 get_annotations(wrapped),
9021 {"a": int, "b": str, "return": isa.MyClass},
9022 )
9023 self.assertEqual(
9024 get_annotations(wrapped, format=Format.FORWARDREF),
9025 {"a": int, "b": str, "return": isa.MyClass},
9026 )
9027 mycls = "MyClass" if sys.version_info >= (3, 14) else "inspect_stock_annotations.MyClass"
9028 self.assertEqual(
9029 get_annotations(wrapped, format=Format.STRING),
9030 {"a": "int", "b": "str", "return": mycls},
9031 )
9032 self.assertEqual(
9033 get_annotations(wrapped, eval_str=True),
9034 {"a": int, "b": str, "return": isa.MyClass},
9035 )
9036 self.assertEqual(
9037 get_annotations(wrapped, eval_str=False),
9038 {"a": int, "b": str, "return": isa.MyClass},
9039 )
9040
9041 def test_stringized_annotations_in_module(self):
9042 isa = self.inspect_stringized_annotations
9043 for kwargs in [
9044 {},
9045 {"eval_str": False},
9046 {"format": Format.VALUE},
9047 {"format": Format.FORWARDREF},
9048 {"format": Format.STRING},
9049 {"format": Format.VALUE, "eval_str": False},
9050 {"format": Format.FORWARDREF, "eval_str": False},
9051 {"format": Format.STRING, "eval_str": False},
9052 ]:
9053 with self.subTest(**kwargs):
9054 self.assertEqual(
9055 get_annotations(isa, **kwargs), {"a": "int", "b": "str"}
9056 )
9057 self.assertEqual(
9058 get_annotations(isa.MyClass, **kwargs),
9059 {"a": "int", "b": "str"},
9060 )
9061 self.assertEqual(
9062 get_annotations(isa.function, **kwargs),
9063 {"a": "int", "b": "str", "return": "MyClass"},
9064 )
9065 self.assertEqual(
9066 get_annotations(isa.function2, **kwargs),
9067 {"a": "int", "b": "'str'", "c": "MyClass", "return": "MyClass"},
9068 )
9069 self.assertEqual(
9070 get_annotations(isa.function3, **kwargs),
9071 {"a": "'int'", "b": "'str'", "c": "'MyClass'"},
9072 )
9073 self.assertEqual(
9074 get_annotations(isa.UnannotatedClass, **kwargs), {}
9075 )
9076 self.assertEqual(
9077 get_annotations(isa.unannotated_function, **kwargs), {}
9078 )
9079
9080 for kwargs in [
9081 {"eval_str": True},
9082 {"format": Format.VALUE, "eval_str": True},
9083 ]:
9084 with self.subTest(**kwargs):
9085 self.assertEqual(
9086 get_annotations(isa, **kwargs), {"a": int, "b": str}
9087 )
9088 self.assertEqual(
9089 get_annotations(isa.MyClass, **kwargs),
9090 {"a": int, "b": str},
9091 )
9092 self.assertEqual(
9093 get_annotations(isa.function, **kwargs),
9094 {"a": int, "b": str, "return": isa.MyClass},
9095 )
9096 self.assertEqual(
9097 get_annotations(isa.function2, **kwargs),
9098 {"a": int, "b": "str", "c": isa.MyClass, "return": isa.MyClass},
9099 )
9100 self.assertEqual(
9101 get_annotations(isa.function3, **kwargs),
9102 {"a": "int", "b": "str", "c": "MyClass"},
9103 )
9104 self.assertEqual(
9105 get_annotations(isa.UnannotatedClass, **kwargs), {}
9106 )
9107 self.assertEqual(
9108 get_annotations(isa.unannotated_function, **kwargs), {}
9109 )
9110
9111 def test_stringized_annotations_in_empty_module(self):
9112 isa2 = self.inspect_stringized_annotations_2
9113 self.assertEqual(get_annotations(isa2), {})
9114 self.assertEqual(get_annotations(isa2, eval_str=True), {})
9115 self.assertEqual(get_annotations(isa2, eval_str=False), {})
9116
9117 def test_stringized_annotations_on_wrapper(self):
9118 isa = self.inspect_stringized_annotations
9119 wrapped = times_three(isa.function)
9120 self.assertEqual(wrapped(1, "x"), isa.MyClass(3, "xxx"))
9121 self.assertIsNot(wrapped.__globals__, isa.function.__globals__)
9122 self.assertEqual(
9123 get_annotations(wrapped),
9124 {"a": "int", "b": "str", "return": "MyClass"},
9125 )
9126 self.assertEqual(
9127 get_annotations(wrapped, eval_str=True),
9128 {"a": int, "b": str, "return": isa.MyClass},
9129 )
9130 self.assertEqual(
9131 get_annotations(wrapped, eval_str=False),
9132 {"a": "int", "b": "str", "return": "MyClass"},
9133 )
9134
9135 def test_stringized_annotations_on_class(self):
9136 isa = self.inspect_stringized_annotations
9137 # test that local namespace lookups work
9138 self.assertEqual(
9139 get_annotations(isa.MyClassWithLocalAnnotations),
9140 {"x": "mytype"},
9141 )
9142 self.assertEqual(
9143 get_annotations(isa.MyClassWithLocalAnnotations, eval_str=True),
9144 {"x": int},
9145 )
9146
9147 def test_modify_annotations(self):
9148 def f(x: int):
9149 pass
9150
9151 self.assertEqual(get_annotations(f), {"x": int})
9152 self.assertEqual(
9153 get_annotations(f, format=Format.FORWARDREF),
9154 {"x": int},
9155 )
9156
9157 f.__annotations__["x"] = str
9158 self.assertEqual(get_annotations(f), {"x": str})
9159
9160
9161 class TestGetAnnotationsMetaclasses(BaseTestCase):
9162 def test_annotated_meta(self):
9163 class Meta(type):
9164 a: int
9165
9166 class X(metaclass=Meta):
9167 pass
9168
9169 class Y(metaclass=Meta):
9170 b: float
9171
9172 self.assertEqual(get_annotations(Meta), {"a": int})
9173 self.assertEqual(get_annotations(X), {})
9174 self.assertEqual(get_annotations(Y), {"b": float})
9175
9176 def test_unannotated_meta(self):
9177 class Meta(type): pass
9178
9179 class X(metaclass=Meta):
9180 a: str
9181
9182 class Y(X): pass
9183
9184 self.assertEqual(get_annotations(Meta), {})
9185 self.assertEqual(get_annotations(Y), {})
9186 self.assertEqual(get_annotations(X), {"a": str})
9187
9188 def test_ordering(self):
9189 # Based on a sample by David Ellis
9190 # https://discuss.python.org/t/pep-749-implementing-pep-649/54974/38
9191
9192 def make_classes():
9193 class Meta(type):
9194 a: int
9195 expected_annotations = {"a": int}
9196
9197 class A(type, metaclass=Meta):
9198 b: float
9199 expected_annotations = {"b": float}
9200
9201 class B(metaclass=A):
9202 c: str
9203 expected_annotations = {"c": str}
9204
9205 class C(B):
9206 expected_annotations = {}
9207
9208 class D(metaclass=Meta):
9209 expected_annotations = {}
9210
9211 return Meta, A, B, C, D
9212
9213 classes = make_classes()
9214 class_count = len(classes)
9215 for order in itertools.permutations(range(class_count), class_count):
9216 names = ", ".join(classes[i].__name__ for i in order)
9217 with self.subTest(names=names):
9218 classes = make_classes() # Regenerate classes
9219 for i in order:
9220 get_annotations(classes[i])
9221 for c in classes:
9222 with self.subTest(c=c):
9223 self.assertEqual(get_annotations(c), c.expected_annotations)
9224
9225
9226 @skipIf(STRINGIZED_ANNOTATIONS_PEP_695 is None, "PEP 695 has yet to be")
9227 class TestGetAnnotationsWithPEP695(BaseTestCase):
9228 @classmethod
9229 def setUpClass(cls):
9230 with tempfile.TemporaryDirectory() as tempdir:
9231 sys.path.append(tempdir)
9232 Path(tempdir, "inspect_stringized_annotations_pep_695.py").write_text(STRINGIZED_ANNOTATIONS_PEP_695)
9233 cls.inspect_stringized_annotations_pep_695 = importlib.import_module(
9234 "inspect_stringized_annotations_pep_695"
9235 )
9236 sys.path.pop()
9237
9238 @classmethod
9239 def tearDownClass(cls):
9240 del cls.inspect_stringized_annotations_pep_695
9241 del sys.modules["inspect_stringized_annotations_pep_695"]
9242
9243 def test_pep695_generic_class_with_future_annotations(self):
9244 ann_module695 = self.inspect_stringized_annotations_pep_695
9245 A_annotations = get_annotations(ann_module695.A, eval_str=True)
9246 A_type_params = ann_module695.A.__type_params__
9247 self.assertIs(A_annotations["x"], A_type_params[0])
9248 self.assertEqual(A_annotations["y"].__args__[0], Unpack[A_type_params[1]])
9249 self.assertIs(A_annotations["z"].__args__[0], A_type_params[2])
9250
9251 def test_pep695_generic_class_with_future_annotations_and_local_shadowing(self):
9252 B_annotations = get_annotations(
9253 self.inspect_stringized_annotations_pep_695.B, eval_str=True
9254 )
9255 self.assertEqual(B_annotations, {"x": int, "y": str, "z": bytes})
9256
9257 def test_pep695_generic_class_with_future_annotations_name_clash_with_global_vars(self):
9258 ann_module695 = self.inspect_stringized_annotations_pep_695
9259 C_annotations = get_annotations(ann_module695.C, eval_str=True)
9260 self.assertEqual(
9261 set(C_annotations.values()),
9262 set(ann_module695.C.__type_params__)
9263 )
9264
9265 def test_pep_695_generic_function_with_future_annotations(self):
9266 ann_module695 = self.inspect_stringized_annotations_pep_695
9267 generic_func_annotations = get_annotations(
9268 ann_module695.generic_function, eval_str=True
9269 )
9270 func_t_params = ann_module695.generic_function.__type_params__
9271 self.assertEqual(
9272 generic_func_annotations.keys(), {"x", "y", "z", "zz", "return"}
9273 )
9274 self.assertIs(generic_func_annotations["x"], func_t_params[0])
9275 self.assertEqual(generic_func_annotations["y"], Unpack[func_t_params[1]])
9276 self.assertIs(generic_func_annotations["z"].__origin__, func_t_params[2])
9277 self.assertIs(generic_func_annotations["zz"].__origin__, func_t_params[2])
9278
9279 def test_pep_695_generic_function_with_future_annotations_name_clash_with_global_vars(self):
9280 self.assertEqual(
9281 set(
9282 get_annotations(
9283 self.inspect_stringized_annotations_pep_695.generic_function_2,
9284 eval_str=True
9285 ).values()
9286 ),
9287 set(
9288 self.inspect_stringized_annotations_pep_695.generic_function_2.__type_params__
9289 )
9290 )
9291
9292 def test_pep_695_generic_method_with_future_annotations(self):
9293 ann_module695 = self.inspect_stringized_annotations_pep_695
9294 generic_method_annotations = get_annotations(
9295 ann_module695.D.generic_method, eval_str=True
9296 )
9297 params = {
9298 param.__name__: param
9299 for param in ann_module695.D.generic_method.__type_params__
9300 }
9301 self.assertEqual(
9302 generic_method_annotations,
9303 {"x": params["Foo"], "y": params["Bar"], "return": None}
9304 )
9305
9306 def test_pep_695_generic_method_with_future_annotations_name_clash_with_global_vars(self):
9307 self.assertEqual(
9308 set(
9309 get_annotations(
9310 self.inspect_stringized_annotations_pep_695.D.generic_method_2,
9311 eval_str=True
9312 ).values()
9313 ),
9314 set(
9315 self.inspect_stringized_annotations_pep_695.D.generic_method_2.__type_params__
9316 )
9317 )
9318
9319 def test_pep_695_generic_method_with_future_annotations_name_clash_with_global_and_local_vars(self):
9320 self.assertEqual(
9321 get_annotations(
9322 self.inspect_stringized_annotations_pep_695.E, eval_str=True
9323 ),
9324 {"x": str},
9325 )
9326
9327 def test_pep_695_generics_with_future_annotations_nested_in_function(self):
9328 results = self.inspect_stringized_annotations_pep_695.nested()
9329
9330 self.assertEqual(
9331 set(results.F_annotations.values()),
9332 set(results.F.__type_params__)
9333 )
9334 self.assertEqual(
9335 set(results.F_meth_annotations.values()),
9336 set(results.F.generic_method.__type_params__)
9337 )
9338 self.assertNotEqual(
9339 set(results.F_meth_annotations.values()),
9340 set(results.F.__type_params__)
9341 )
9342 self.assertEqual(
9343 set(results.F_meth_annotations.values()).intersection(results.F.__type_params__),
9344 set()
9345 )
9346
9347 self.assertEqual(results.G_annotations, {"x": str})
9348
9349 self.assertEqual(
9350 set(results.generic_func_annotations.values()),
9351 set(results.generic_func.__type_params__)
9352 )
9353
9354
9355 class EvaluateForwardRefTests(BaseTestCase):
9356 def test_evaluate_forward_ref(self):
9357 int_ref = typing_extensions.ForwardRef('int')
9358 self.assertIs(typing_extensions.evaluate_forward_ref(int_ref), int)
9359 self.assertIs(
9360 typing_extensions.evaluate_forward_ref(int_ref, type_params=()),
9361 int,
9362 )
9363 self.assertIs(
9364 typing_extensions.evaluate_forward_ref(int_ref, format=typing_extensions.Format.VALUE),
9365 int,
9366 )
9367 self.assertIs(
9368 typing_extensions.evaluate_forward_ref(
9369 int_ref, format=typing_extensions.Format.FORWARDREF,
9370 ),
9371 int,
9372 )
9373 self.assertEqual(
9374 typing_extensions.evaluate_forward_ref(
9375 int_ref, format=typing_extensions.Format.STRING,
9376 ),
9377 'int',
9378 )
9379
9380 def test_evaluate_forward_ref_undefined(self):
9381 missing = typing_extensions.ForwardRef('missing')
9382 with self.assertRaises(NameError):
9383 typing_extensions.evaluate_forward_ref(missing)
9384 self.assertIs(
9385 typing_extensions.evaluate_forward_ref(
9386 missing, format=typing_extensions.Format.FORWARDREF,
9387 ),
9388 missing,
9389 )
9390 self.assertEqual(
9391 typing_extensions.evaluate_forward_ref(
9392 missing, format=typing_extensions.Format.STRING,
9393 ),
9394 "missing",
9395 )
9396
9397 def test_evaluate_forward_ref_nested(self):
9398 ref = typing_extensions.ForwardRef("Union[int, list['str']]")
9399 ns = {"Union": Union}
9400 if sys.version_info >= (3, 11):
9401 expected = Union[int, list[str]]
9402 else:
9403 expected = Union[int, list['str']] # TODO: evaluate nested forward refs in Python < 3.11
9404 self.assertEqual(
9405 typing_extensions.evaluate_forward_ref(ref, globals=ns),
9406 expected,
9407 )
9408 self.assertEqual(
9409 typing_extensions.evaluate_forward_ref(
9410 ref, globals=ns, format=typing_extensions.Format.FORWARDREF
9411 ),
9412 expected,
9413 )
9414 self.assertEqual(
9415 typing_extensions.evaluate_forward_ref(ref, format=typing_extensions.Format.STRING),
9416 "Union[int, list['str']]",
9417 )
9418
9419 why = typing_extensions.ForwardRef('"\'str\'"')
9420 self.assertIs(typing_extensions.evaluate_forward_ref(why), str)
9421
9422 @skipUnless(sys.version_info >= (3, 10), "Relies on PEP 604")
9423 def test_evaluate_forward_ref_nested_pep604(self):
9424 ref = typing_extensions.ForwardRef("int | list['str']")
9425 if sys.version_info >= (3, 11):
9426 expected = int | list[str]
9427 else:
9428 expected = int | list['str'] # TODO: evaluate nested forward refs in Python < 3.11
9429 self.assertEqual(
9430 typing_extensions.evaluate_forward_ref(ref),
9431 expected,
9432 )
9433 self.assertEqual(
9434 typing_extensions.evaluate_forward_ref(ref, format=typing_extensions.Format.FORWARDREF),
9435 expected,
9436 )
9437 self.assertEqual(
9438 typing_extensions.evaluate_forward_ref(ref, format=typing_extensions.Format.STRING),
9439 "int | list['str']",
9440 )
9441
9442 def test_evaluate_forward_ref_none(self):
9443 none_ref = typing_extensions.ForwardRef('None')
9444 self.assertIs(typing_extensions.evaluate_forward_ref(none_ref), None)
9445
9446 def test_globals(self):
9447 A = "str"
9448 ref = typing_extensions.ForwardRef('list[A]')
9449 with self.assertRaises(NameError):
9450 typing_extensions.evaluate_forward_ref(ref)
9451 self.assertEqual(
9452 typing_extensions.evaluate_forward_ref(ref, globals={'A': A}),
9453 list[str] if sys.version_info >= (3, 11) else list['str'],
9454 )
9455
9456 def test_owner(self):
9457 ref = typing_extensions.ForwardRef("A")
9458
9459 with self.assertRaises(NameError):
9460 typing_extensions.evaluate_forward_ref(ref)
9461
9462 # We default to the globals of `owner`,
9463 # so it no longer raises `NameError`
9464 self.assertIs(
9465 typing_extensions.evaluate_forward_ref(ref, owner=Loop), A
9466 )
9467
9468 @skipUnless(sys.version_info >= (3, 14), "Not yet implemented in Python < 3.14")
9469 def test_inherited_owner(self):
9470 # owner passed to evaluate_forward_ref
9471 ref = typing_extensions.ForwardRef("list['A']")
9472 self.assertEqual(
9473 typing_extensions.evaluate_forward_ref(ref, owner=Loop),
9474 list[A],
9475 )
9476
9477 # owner set on the ForwardRef
9478 ref = typing_extensions.ForwardRef("list['A']", owner=Loop)
9479 self.assertEqual(
9480 typing_extensions.evaluate_forward_ref(ref),
9481 list[A],
9482 )
9483
9484 @skipUnless(sys.version_info >= (3, 14), "Not yet implemented in Python < 3.14")
9485 def test_partial_evaluation(self):
9486 ref = typing_extensions.ForwardRef("list[A]")
9487 with self.assertRaises(NameError):
9488 typing_extensions.evaluate_forward_ref(ref)
9489
9490 self.assertEqual(
9491 typing_extensions.evaluate_forward_ref(ref, format=typing_extensions.Format.FORWARDREF),
9492 list[EqualToForwardRef('A')],
9493 )
9494
9495 def test_global_constant(self):
9496 if sys.version_info[:3] > (3, 10, 0):
9497 self.assertTrue(_FORWARD_REF_HAS_CLASS)
9498
9499 def test_forward_ref_fallback(self):
9500 with self.assertRaises(NameError):
9501 evaluate_forward_ref(typing.ForwardRef("doesntexist"))
9502 ref = typing.ForwardRef("doesntexist")
9503 self.assertIs(evaluate_forward_ref(ref, format=Format.FORWARDREF), ref)
9504
9505 class X:
9506 unresolvable = "doesnotexist2"
9507
9508 evaluated_ref = evaluate_forward_ref(
9509 typing.ForwardRef("X.unresolvable"),
9510 locals={"X": X},
9511 type_params=None,
9512 format=Format.FORWARDREF,
9513 )
9514 self.assertEqual(evaluated_ref, EqualToForwardRef("doesnotexist2"))
9515
9516 def test_evaluate_with_type_params(self):
9517 # Use a T name that is not in globals
9518 self.assertNotIn("Tx", globals())
9519 if not TYPING_3_12_0:
9520 Tx = TypeVar("Tx")
9521 class Gen(Generic[Tx]):
9522 alias = int
9523 if not hasattr(Gen, "__type_params__"):
9524 Gen.__type_params__ = (Tx,)
9525 self.assertEqual(Gen.__type_params__, (Tx,))
9526 del Tx
9527 else:
9528 ns = {}
9529 exec(textwrap.dedent("""
9530 class Gen[Tx]:
9531 alias = int
9532 """), None, ns)
9533 Gen = ns["Gen"]
9534
9535 # owner=None, type_params=None
9536 # NOTE: The behavior of owner=None might change in the future when ForwardRef.__owner__ is available
9537 with self.assertRaises(NameError):
9538 evaluate_forward_ref(typing.ForwardRef("Tx"))
9539 with self.assertRaises(NameError):
9540 evaluate_forward_ref(typing.ForwardRef("Tx"), type_params=())
9541 with self.assertRaises(NameError):
9542 evaluate_forward_ref(typing.ForwardRef("Tx"), owner=int)
9543
9544 (Tx,) = Gen.__type_params__
9545 self.assertIs(evaluate_forward_ref(typing.ForwardRef("Tx"), type_params=Gen.__type_params__), Tx)
9546
9547 # For this test its important that Tx is not a global variable, i.e. do not use "T" here
9548 self.assertNotIn("Tx", globals())
9549 self.assertIs(evaluate_forward_ref(typing.ForwardRef("Tx"), owner=Gen), Tx)
9550
9551 # Different type_params take precedence
9552 not_Tx = TypeVar("Tx") # different TypeVar with same name
9553 self.assertIs(evaluate_forward_ref(typing.ForwardRef("Tx"), type_params=(not_Tx,), owner=Gen), not_Tx)
9554
9555 # globals do not take higher precedence
9556 self.assertIs(evaluate_forward_ref(typing.ForwardRef("Tx", is_class=True), owner=Gen, globals={"Tx": str}), Tx)
9557 self.assertIs(evaluate_forward_ref(typing.ForwardRef("Tx", is_class=True), owner=Gen, type_params=(not_Tx,), globals={"Tx": str}), not_Tx)
9558
9559 with self.assertRaises(NameError):
9560 evaluate_forward_ref(typing.ForwardRef("alias"), type_params=Gen.__type_params__)
9561 self.assertIs(evaluate_forward_ref(typing.ForwardRef("alias"), owner=Gen), int)
9562 # If you pass custom locals, we don't look at the owner's locals
9563 with self.assertRaises(NameError):
9564 evaluate_forward_ref(typing.ForwardRef("alias"), owner=Gen, locals={})
9565 # But if the name exists in the locals, it works
9566 self.assertIs(
9567 evaluate_forward_ref(typing.ForwardRef("alias"), owner=Gen, locals={"alias": str}), str
9568 )
9569
9570 @skipUnless(
9571 HAS_FORWARD_MODULE, "Needs module 'forward' to test forward references"
9572 )
9573 def test_fwdref_with_module(self):
9574 self.assertIs(
9575 evaluate_forward_ref(typing.ForwardRef("Counter", module="collections")), collections.Counter
9576 )
9577 self.assertEqual(
9578 evaluate_forward_ref(typing.ForwardRef("Counter[int]", module="collections")),
9579 collections.Counter[int],
9580 )
9581
9582 with self.assertRaises(NameError):
9583 # If globals are passed explicitly, we don't look at the module dict
9584 evaluate_forward_ref(typing.ForwardRef("Format", module="annotationlib"), globals={})
9585
9586 def test_fwdref_to_builtin(self):
9587 self.assertIs(evaluate_forward_ref(typing.ForwardRef("int")), int)
9588 if HAS_FORWARD_MODULE:
9589 self.assertIs(evaluate_forward_ref(typing.ForwardRef("int", module="collections")), int)
9590 self.assertIs(evaluate_forward_ref(typing.ForwardRef("int"), owner=str), int)
9591
9592 # builtins are still searched with explicit globals
9593 self.assertIs(evaluate_forward_ref(typing.ForwardRef("int"), globals={}), int)
9594
9595 def test_fwdref_with_globals(self):
9596 # explicit values in globals have precedence
9597 obj = object()
9598 self.assertIs(evaluate_forward_ref(typing.ForwardRef("int"), globals={"int": obj}), obj)
9599
9600 def test_fwdref_with_owner(self):
9601 self.assertEqual(
9602 evaluate_forward_ref(typing.ForwardRef("Counter[int]"), owner=collections),
9603 collections.Counter[int],
9604 )
9605
9606 def test_name_lookup_without_eval(self):
9607 # test the codepath where we look up simple names directly in the
9608 # namespaces without going through eval()
9609 self.assertIs(evaluate_forward_ref(typing.ForwardRef("int")), int)
9610 self.assertIs(evaluate_forward_ref(typing.ForwardRef("int"), locals={"int": str}), str)
9611 self.assertIs(
9612 evaluate_forward_ref(typing.ForwardRef("int"), locals={"int": float}, globals={"int": str}),
9613 float,
9614 )
9615 self.assertIs(evaluate_forward_ref(typing.ForwardRef("int"), globals={"int": str}), str)
9616
9617 import builtins
9618
9619 with patch.object(builtins, "int", dict):
9620 self.assertIs(evaluate_forward_ref(typing.ForwardRef("int")), dict)
9621
9622 def test_nested_strings(self):
9623 # This variable must have a different name TypeVar
9624 Tx = TypeVar("Tx")
9625
9626 class Y(Generic[Tx]):
9627 a = "X"
9628 bT = "Y[T_nonlocal]"
9629
9630 Z = TypeAliasType("Z", Y[Tx], type_params=(Tx,))
9631
9632 evaluated_ref1a = evaluate_forward_ref(typing.ForwardRef("Y[Y['Tx']]"), locals={"Y": Y, "Tx": Tx})
9633 self.assertEqual(get_origin(evaluated_ref1a), Y)
9634 self.assertEqual(get_args(evaluated_ref1a), (Y[Tx],))
9635
9636 evaluated_ref1b = evaluate_forward_ref(
9637 typing.ForwardRef("Y[Y['Tx']]"), locals={"Y": Y}, type_params=(Tx,)
9638 )
9639 self.assertEqual(get_origin(evaluated_ref1b), Y)
9640 self.assertEqual(get_args(evaluated_ref1b), (Y[Tx],))
9641
9642 with self.subTest("nested string of TypeVar"):
9643 evaluated_ref2 = evaluate_forward_ref(typing.ForwardRef("""Y["Y['Tx']"]"""), locals={"Y": Y, "Tx": Tx})
9644 self.assertEqual(get_origin(evaluated_ref2), Y)
9645 self.assertEqual(get_args(evaluated_ref2), (Y[Tx],))
9646
9647 with self.subTest("nested string of TypeAliasType and alias"):
9648 # NOTE: Using Y here works for 3.10
9649 evaluated_ref3 = evaluate_forward_ref(typing.ForwardRef("""Y['Z["StrAlias"]']"""), locals={"Y": Y, "Z": Z, "StrAlias": str})
9650 self.assertEqual(get_origin(evaluated_ref3), Y)
9651 if sys.version_info[:2] == (3, 10):
9652 self.skipTest("Nested string 'StrAlias' is not resolved in 3.10")
9653 self.assertEqual(get_args(evaluated_ref3), (Z[str],))
9654
9655 def test_invalid_special_forms(self):
9656 for name in ("Protocol", "Final", "ClassVar", "Generic"):
9657 with self.subTest(name=name):
9658 self.assertIs(
9659 evaluate_forward_ref(typing.ForwardRef(name), globals=vars(typing)),
9660 getattr(typing, name),
9661 )
9662 if _FORWARD_REF_HAS_CLASS:
9663 self.assertIs(evaluate_forward_ref(typing.ForwardRef("Final", is_class=True), globals=vars(typing)), Final)
9664 self.assertIs(evaluate_forward_ref(typing.ForwardRef("ClassVar", is_class=True), globals=vars(typing)), ClassVar)
9665 self.assertIs(evaluate_forward_ref(typing.ForwardRef("Final", is_argument=False), globals=vars(typing)), Final)
9666 self.assertIs(evaluate_forward_ref(typing.ForwardRef("ClassVar", is_argument=False), globals=vars(typing)), ClassVar)
9667
9668
9669 class TestSentinels(BaseTestCase):
9670 SENTINEL = sentinel("TestSentinels.SENTINEL")
9671
9672 def test_sentinel_no_repr(self):
9673 sentinel_no_repr = sentinel('sentinel_no_repr')
9674
9675 self.assertEqual(sentinel_no_repr.__name__, 'sentinel_no_repr')
9676 self.assertEqual(repr(sentinel_no_repr), 'sentinel_no_repr')
9677
9678 @skipIf(TYPING_3_15_0, reason="'Passing 'repr' as a positional argument was removed in 3.15")
9679 def test_sentinel_deprecated_argument_repr(self):
9680 with self.assertWarnsRegex(DeprecationWarning, r"Passing 'repr' as a positional argument is deprecated; pass it by keyword instead."):
9681 sentinel_argument_repr = sentinel('sentinel_argument_repr', 'argument_repr')
9682
9683 self.assertEqual(repr(sentinel_argument_repr), 'argument_repr')
9684
9685 @skipIf(TYPING_3_15_0_BETA_1, reason="'repr' parameter is not yet available in 3.15.0b1")
9686 def test_sentinel_keyword_repr(self):
9687 sentinel_keyword_repr = sentinel('sentinel_keyword_repr', repr='keyword_repr')
9688
9689 self.assertEqual(repr(sentinel_keyword_repr), 'keyword_repr')
9690
9691 @skipIf(sys.version_info < (3, 10), reason='New unions not available in 3.9')
9692 def test_sentinel_type_expression_union(self):
9693 sentinel_type = sentinel('sentinel')
9694
9695 def func1(a: int | sentinel_type = sentinel_type): pass
9696 def func2(a: sentinel_type | int = sentinel_type): pass
9697
9698 self.assertEqual(func1.__annotations__['a'], Union[int, sentinel_type])
9699 self.assertEqual(func2.__annotations__['a'], Union[sentinel_type, int])
9700
9701 def test_sentinel_not_callable(self):
9702 sentinel_ = sentinel('sentinel')
9703 with self.assertRaisesRegex(
9704 TypeError,
9705 "'sentinel' object is not callable"
9706 ):
9707 sentinel_()
9708
9709 def test_sentinel_copy_identity(self):
9710 self.assertIs(self.SENTINEL, copy.copy(self.SENTINEL))
9711 self.assertIs(self.SENTINEL, copy.deepcopy(self.SENTINEL))
9712
9713 anonymous_sentinel = sentinel("anonymous_sentinel")
9714 self.assertIs(anonymous_sentinel, copy.copy(anonymous_sentinel))
9715 self.assertIs(anonymous_sentinel, copy.deepcopy(anonymous_sentinel))
9716
9717 def test_sentinel_picklable_qualified(self):
9718 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
9719 self.assertIs(self.SENTINEL, pickle.loads(pickle.dumps(self.SENTINEL, protocol=proto)))
9720
9721 def test_sentinel_picklable_anonymous(self):
9722 anonymous_sentinel = sentinel("anonymous_sentinel") # Anonymous sentinel can not be pickled
9723 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
9724 with self.assertRaisesRegex(
9725 pickle.PicklingError,
9726 r"attribute lookup anonymous_sentinel on \w+ failed|not found as \w+.anonymous_sentinel"
9727 ):
9728 self.assertIs(anonymous_sentinel, pickle.loads(pickle.dumps(anonymous_sentinel, protocol=proto)))
9729
9730 @skipIf(TYPING_3_15_0, reason='Deprecated sentinel APIs were removed in 3.15')
9731 def test_sentinel_deprecated(self):
9732 with self.assertWarnsRegex(DeprecationWarning, r"Subclassing sentinel is deprecated"):
9733 class SentinelSubclass(Sentinel):
9734 pass
9735 with self.assertRaisesRegex(TypeError, r"First parameter 'name' is required"):
9736 sentinel()
9737
9738 with self.assertWarnsRegex(DeprecationWarning, r"Passing 'name' as a keyword argument is deprecated"):
9739 my_sentinel = Sentinel(name="my_sentinel")
9740 with self.assertWarnsRegex(DeprecationWarning, r"Setting attribute 'foo' on sentinel objects is deprecated"):
9741 my_sentinel.foo = "bar"
9742 with self.assertWarnsRegex(DeprecationWarning, r"Setting attribute '__name__' on sentinel objects is deprecated"):
9743 my_sentinel.__name__ = "bar"
9744
9745 @skipUnless(TYPING_3_15_0, reason='Deprecated sentinel APIs are available before 3.15')
9746 def test_sentinel_removed_deprecated_apis(self):
9747 with self.assertRaises(TypeError):
9748 class SentinelSubclass(Sentinel):
9749 pass
9750 with self.assertRaises(TypeError):
9751 sentinel()
9752 with self.assertRaises(TypeError):
9753 Sentinel(name="my_sentinel")
9754 with self.assertRaises(AttributeError):
9755 sentinel('my_sentinel').foo = "bar"
9756 with self.assertRaises(AttributeError):
9757 sentinel('my_sentinel').__name__ = "bar"
9758
9759
9760 def load_tests(loader, tests, pattern):
9761 import doctest
9762 tests.addTests(doctest.DocTestSuite(typing_extensions))
9763 return tests
9764
9765 if __name__ == '__main__': # pragma: no cover
9766 main()