Debian Codegraph @

src/test_typing_extensions.py

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