1 """
2 The typing module: Support for gradual typing as defined by PEP 484 and subsequent PEPs.
3
4 Among other things, the module includes the following:
5 * Generic, Protocol, and internal machinery to support generic aliases.
6 All subscripted types like X[int], Union[int, str] are generic aliases.
7 * Various "special forms" that have unique meanings in type annotations:
8 NoReturn, Never, ClassVar, Self, Concatenate, Unpack, and others.
9 * Classes whose instances can be type arguments to generic classes and functions:
10 TypeVar, ParamSpec, TypeVarTuple.
11 * Public helper functions: get_type_hints, overload, cast, final, and others.
12 * Several protocols to support duck-typing:
13 SupportsFloat, SupportsIndex, SupportsAbs, and others.
14 * Special types: NewType, NamedTuple, TypedDict.
15 * Deprecated wrapper submodules for re and io related types.
16 * Deprecated aliases for builtin types and collections.abc ABCs.
17
18 Any name not present in __all__ is an implementation detail
19 that may be changed without notice. Use at your own risk!
20 """
21
22 from abc import abstractmethod, ABCMeta
23 import collections
24 from collections import defaultdict
25 import collections.abc
26 import contextlib
27 import functools
28 import operator
29 import re as stdlib_re # Avoid confusion with the re we export.
30 import sys
31 import types
32 import warnings
33 from types import WrapperDescriptorType, MethodWrapperType, MethodDescriptorType, GenericAlias
34
35
36 try:
37 from _typing import _idfunc
38 except ImportError:
39 def _idfunc(_, x):
40 return x
41
42 # Please keep __all__ alphabetized within each category.
43 __all__ = [
44 # Super-special typing primitives.
45 'Annotated',
46 'Any',
47 'Callable',
48 'ClassVar',
49 'Concatenate',
50 'Final',
51 'ForwardRef',
52 'Generic',
53 'Literal',
54 'Optional',
55 'ParamSpec',
56 'Protocol',
57 'Tuple',
58 'Type',
59 'TypeVar',
60 'TypeVarTuple',
61 'Union',
62
63 # ABCs (from collections.abc).
64 'AbstractSet', # collections.abc.Set.
65 'ByteString',
66 'Container',
67 'ContextManager',
68 'Hashable',
69 'ItemsView',
70 'Iterable',
71 'Iterator',
72 'KeysView',
73 'Mapping',
74 'MappingView',
75 'MutableMapping',
76 'MutableSequence',
77 'MutableSet',
78 'Sequence',
79 'Sized',
80 'ValuesView',
81 'Awaitable',
82 'AsyncIterator',
83 'AsyncIterable',
84 'Coroutine',
85 'Collection',
86 'AsyncGenerator',
87 'AsyncContextManager',
88
89 # Structural checks, a.k.a. protocols.
90 'Reversible',
91 'SupportsAbs',
92 'SupportsBytes',
93 'SupportsComplex',
94 'SupportsFloat',
95 'SupportsIndex',
96 'SupportsInt',
97 'SupportsRound',
98
99 # Concrete collection types.
100 'ChainMap',
101 'Counter',
102 'Deque',
103 'Dict',
104 'DefaultDict',
105 'List',
106 'OrderedDict',
107 'Set',
108 'FrozenSet',
109 'NamedTuple', # Not really a type.
110 'TypedDict', # Not really a type.
111 'Generator',
112
113 # Other concrete types.
114 'BinaryIO',
115 'IO',
116 'Match',
117 'Pattern',
118 'TextIO',
119
120 # One-off things.
121 'AnyStr',
122 'assert_type',
123 'assert_never',
124 'cast',
125 'clear_overloads',
126 'dataclass_transform',
127 'final',
128 'get_args',
129 'get_origin',
130 'get_overloads',
131 'get_type_hints',
132 'is_typeddict',
133 'LiteralString',
134 'Never',
135 'NewType',
136 'no_type_check',
137 'no_type_check_decorator',
138 'NoReturn',
139 'NotRequired',
140 'overload',
141 'ParamSpecArgs',
142 'ParamSpecKwargs',
143 'Required',
144 'reveal_type',
145 'runtime_checkable',
146 'Self',
147 'Text',
148 'TYPE_CHECKING',
149 'TypeAlias',
150 'TypeGuard',
151 'Unpack',
152 ]
153
154 # The pseudo-submodules 're' and 'io' are part of the public
155 # namespace, but excluded from __all__ because they might stomp on
156 # legitimate imports of those modules.
157
158
159 def _type_convert(arg, module=None, *, allow_special_forms=False):
160 """For converting None to type(None), and strings to ForwardRef."""
161 if arg is None:
162 return type(None)
163 if isinstance(arg, str):
164 return ForwardRef(arg, module=module, is_class=allow_special_forms)
165 return arg
166
167
168 def _type_check(arg, msg, is_argument=True, module=None, *, allow_special_forms=False):
169 """Check that the argument is a type, and return it (internal helper).
170
171 As a special case, accept None and return type(None) instead. Also wrap strings
172 into ForwardRef instances. Consider several corner cases, for example plain
173 special forms like Union are not valid, while Union[int, str] is OK, etc.
174 The msg argument is a human-readable error message, e.g.::
175
176 "Union[arg, ...]: arg should be a type."
177
178 We append the repr() of the actual value (truncated to 100 chars).
179 """
180 invalid_generic_forms = (Generic, Protocol)
181 if not allow_special_forms:
182 invalid_generic_forms += (ClassVar,)
183 if is_argument:
184 invalid_generic_forms += (Final,)
185
186 arg = _type_convert(arg, module=module, allow_special_forms=allow_special_forms)
187 if (isinstance(arg, _GenericAlias) and
188 arg.__origin__ in invalid_generic_forms):
189 raise TypeError(f"{arg} is not valid as type argument")
190 if arg in (Any, LiteralString, NoReturn, Never, Self, TypeAlias):
191 return arg
192 if allow_special_forms and arg in (ClassVar, Final):
193 return arg
194 if isinstance(arg, _SpecialForm) or arg in (Generic, Protocol):
195 raise TypeError(f"Plain {arg} is not valid as type argument")
196 if type(arg) is tuple:
197 raise TypeError(f"{msg} Got {arg!r:.100}.")
198 return arg
199
200
201 def _is_param_expr(arg):
202 return arg is ... or isinstance(arg,
203 (tuple, list, ParamSpec, _ConcatenateGenericAlias))
204
205
206 def _should_unflatten_callable_args(typ, args):
207 """Internal helper for munging collections.abc.Callable's __args__.
208
209 The canonical representation for a Callable's __args__ flattens the
210 argument types, see https://github.com/python/cpython/issues/86361.
211
212 For example::
213
214 >>> import collections.abc
215 >>> P = ParamSpec('P')
216 >>> collections.abc.Callable[[int, int], str].__args__ == (int, int, str)
217 True
218 >>> collections.abc.Callable[P, str].__args__ == (P, str)
219 True
220
221 As a result, if we need to reconstruct the Callable from its __args__,
222 we need to unflatten it.
223 """
224 return (
225 typ.__origin__ is collections.abc.Callable
226 and not (len(args) == 2 and _is_param_expr(args[0]))
227 )
228
229
230 def _type_repr(obj):
231 """Return the repr() of an object, special-casing types (internal helper).
232
233 If obj is a type, we return a shorter version than the default
234 type.__repr__, based on the module and qualified name, which is
235 typically enough to uniquely identify a type. For everything
236 else, we fall back on repr(obj).
237 """
238 if isinstance(obj, types.GenericAlias):
239 return repr(obj)
240 if isinstance(obj, type):
241 if obj.__module__ == 'builtins':
242 return obj.__qualname__
243 return f'{obj.__module__}.{obj.__qualname__}'
244 if obj is ...:
245 return('...')
246 if isinstance(obj, types.FunctionType):
247 return obj.__name__
248 return repr(obj)
249
250
251 def _collect_parameters(args):
252 """Collect all type variables and parameter specifications in args
253 in order of first appearance (lexicographic order).
254
255 For example::
256
257 >>> P = ParamSpec('P')
258 >>> T = TypeVar('T')
259 >>> _collect_parameters((T, Callable[P, T]))
260 (~T, ~P)
261 """
262 parameters = []
263 for t in args:
264 if isinstance(t, type):
265 # We don't want __parameters__ descriptor of a bare Python class.
266 pass
267 elif isinstance(t, tuple):
268 # `t` might be a tuple, when `ParamSpec` is substituted with
269 # `[T, int]`, or `[int, *Ts]`, etc.
270 for x in t:
271 for collected in _collect_parameters([x]):
272 if collected not in parameters:
273 parameters.append(collected)
274 elif hasattr(t, '__typing_subst__'):
275 if t not in parameters:
276 parameters.append(t)
277 else:
278 for x in getattr(t, '__parameters__', ()):
279 if x not in parameters:
280 parameters.append(x)
281 return tuple(parameters)
282
283
284 def _check_generic(cls, parameters, elen):
285 """Check correct count for parameters of a generic cls (internal helper).
286
287 This gives a nice error message in case of count mismatch.
288 """
289 if not elen:
290 raise TypeError(f"{cls} is not a generic class")
291 alen = len(parameters)
292 if alen != elen:
293 raise TypeError(f"Too {'many' if alen > elen else 'few'} arguments for {cls};"
294 f" actual {alen}, expected {elen}")
295
296 def _unpack_args(args):
297 newargs = []
298 for arg in args:
299 subargs = getattr(arg, '__typing_unpacked_tuple_args__', None)
300 if subargs is not None and not (subargs and subargs[-1] is ...):
301 newargs.extend(subargs)
302 else:
303 newargs.append(arg)
304 return newargs
305
306 def _deduplicate(params):
307 # Weed out strict duplicates, preserving the first of each occurrence.
308 all_params = set(params)
309 if len(all_params) < len(params):
310 new_params = []
311 for t in params:
312 if t in all_params:
313 new_params.append(t)
314 all_params.remove(t)
315 params = new_params
316 assert not all_params, all_params
317 return params
318
319
320 def _remove_dups_flatten(parameters):
321 """Internal helper for Union creation and substitution.
322
323 Flatten Unions among parameters, then remove duplicates.
324 """
325 # Flatten out Union[Union[...], ...].
326 params = []
327 for p in parameters:
328 if isinstance(p, (_UnionGenericAlias, types.UnionType)):
329 params.extend(p.__args__)
330 else:
331 params.append(p)
332
333 return tuple(_deduplicate(params))
334
335
336 def _flatten_literal_params(parameters):
337 """Internal helper for Literal creation: flatten Literals among parameters."""
338 params = []
339 for p in parameters:
340 if isinstance(p, _LiteralGenericAlias):
341 params.extend(p.__args__)
342 else:
343 params.append(p)
344 return tuple(params)
345
346
347 _cleanups = []
348
349
350 def _tp_cache(func=None, /, *, typed=False):
351 """Internal wrapper caching __getitem__ of generic types.
352
353 For non-hashable arguments, the original function is used as a fallback.
354 """
355 def decorator(func):
356 cached = functools.lru_cache(typed=typed)(func)
357 _cleanups.append(cached.cache_clear)
358
359 @functools.wraps(func)
360 def inner(*args, **kwds):
361 try:
362 return cached(*args, **kwds)
363 except TypeError:
364 pass # All real errors (not unhashable args) are raised below.
365 return func(*args, **kwds)
366 return inner
367
368 if func is not None:
369 return decorator(func)
370
371 return decorator
372
373 def _eval_type(t, globalns, localns, recursive_guard=frozenset()):
374 """Evaluate all forward references in the given type t.
375
376 For use of globalns and localns see the docstring for get_type_hints().
377 recursive_guard is used to prevent infinite recursion with a recursive
378 ForwardRef.
379 """
380 if isinstance(t, ForwardRef):
381 return t._evaluate(globalns, localns, recursive_guard)
382 if isinstance(t, (_GenericAlias, GenericAlias, types.UnionType)):
383 if isinstance(t, GenericAlias):
384 args = tuple(
385 ForwardRef(arg) if isinstance(arg, str) else arg
386 for arg in t.__args__
387 )
388 is_unpacked = t.__unpacked__
389 if _should_unflatten_callable_args(t, args):
390 t = t.__origin__[(args[:-1], args[-1])]
391 else:
392 t = t.__origin__[args]
393 if is_unpacked:
394 t = Unpack[t]
395 ev_args = tuple(_eval_type(a, globalns, localns, recursive_guard) for a in t.__args__)
396 if ev_args == t.__args__:
397 return t
398 if isinstance(t, GenericAlias):
399 return GenericAlias(t.__origin__, ev_args)
400 if isinstance(t, types.UnionType):
401 return functools.reduce(operator.or_, ev_args)
402 else:
403 return t.copy_with(ev_args)
404 return t
405
406
407 class ESC[4;38;5;81m_Final:
408 """Mixin to prohibit subclassing."""
409
410 __slots__ = ('__weakref__',)
411
412 def __init_subclass__(cls, /, *args, **kwds):
413 if '_root' not in kwds:
414 raise TypeError("Cannot subclass special typing classes")
415
416 class ESC[4;38;5;81m_Immutable:
417 """Mixin to indicate that object should not be copied."""
418
419 __slots__ = ()
420
421 def __copy__(self):
422 return self
423
424 def __deepcopy__(self, memo):
425 return self
426
427
428 class ESC[4;38;5;81m_NotIterable:
429 """Mixin to prevent iteration, without being compatible with Iterable.
430
431 That is, we could do::
432
433 def __iter__(self): raise TypeError()
434
435 But this would make users of this mixin duck type-compatible with
436 collections.abc.Iterable - isinstance(foo, Iterable) would be True.
437
438 Luckily, we can instead prevent iteration by setting __iter__ to None, which
439 is treated specially.
440 """
441
442 __slots__ = ()
443 __iter__ = None
444
445
446 # Internal indicator of special typing constructs.
447 # See __doc__ instance attribute for specific docs.
448 class ESC[4;38;5;81m_SpecialForm(ESC[4;38;5;149m_Final, ESC[4;38;5;149m_NotIterable, _root=ESC[4;38;5;149mTrue):
449 __slots__ = ('_name', '__doc__', '_getitem')
450
451 def __init__(self, getitem):
452 self._getitem = getitem
453 self._name = getitem.__name__
454 self.__doc__ = getitem.__doc__
455
456 def __getattr__(self, item):
457 if item in {'__name__', '__qualname__'}:
458 return self._name
459
460 raise AttributeError(item)
461
462 def __mro_entries__(self, bases):
463 raise TypeError(f"Cannot subclass {self!r}")
464
465 def __repr__(self):
466 return 'typing.' + self._name
467
468 def __reduce__(self):
469 return self._name
470
471 def __call__(self, *args, **kwds):
472 raise TypeError(f"Cannot instantiate {self!r}")
473
474 def __or__(self, other):
475 return Union[self, other]
476
477 def __ror__(self, other):
478 return Union[other, self]
479
480 def __instancecheck__(self, obj):
481 raise TypeError(f"{self} cannot be used with isinstance()")
482
483 def __subclasscheck__(self, cls):
484 raise TypeError(f"{self} cannot be used with issubclass()")
485
486 @_tp_cache
487 def __getitem__(self, parameters):
488 return self._getitem(self, parameters)
489
490
491 class ESC[4;38;5;81m_LiteralSpecialForm(ESC[4;38;5;149m_SpecialForm, _root=ESC[4;38;5;149mTrue):
492 def __getitem__(self, parameters):
493 if not isinstance(parameters, tuple):
494 parameters = (parameters,)
495 return self._getitem(self, *parameters)
496
497
498 class ESC[4;38;5;81m_AnyMeta(ESC[4;38;5;149mtype):
499 def __instancecheck__(self, obj):
500 if self is Any:
501 raise TypeError("typing.Any cannot be used with isinstance()")
502 return super().__instancecheck__(obj)
503
504 def __repr__(self):
505 if self is Any:
506 return "typing.Any"
507 return super().__repr__() # respect to subclasses
508
509
510 class ESC[4;38;5;81mAny(metaclass=ESC[4;38;5;149m_AnyMeta):
511 """Special type indicating an unconstrained type.
512
513 - Any is compatible with every type.
514 - Any assumed to have all methods.
515 - All values assumed to be instances of Any.
516
517 Note that all the above statements are true from the point of view of
518 static type checkers. At runtime, Any should not be used with instance
519 checks.
520 """
521
522 def __new__(cls, *args, **kwargs):
523 if cls is Any:
524 raise TypeError("Any cannot be instantiated")
525 return super().__new__(cls, *args, **kwargs)
526
527
528 @_SpecialForm
529 def NoReturn(self, parameters):
530 """Special type indicating functions that never return.
531
532 Example::
533
534 from typing import NoReturn
535
536 def stop() -> NoReturn:
537 raise Exception('no way')
538
539 NoReturn can also be used as a bottom type, a type that
540 has no values. Starting in Python 3.11, the Never type should
541 be used for this concept instead. Type checkers should treat the two
542 equivalently.
543 """
544 raise TypeError(f"{self} is not subscriptable")
545
546 # This is semantically identical to NoReturn, but it is implemented
547 # separately so that type checkers can distinguish between the two
548 # if they want.
549 @_SpecialForm
550 def Never(self, parameters):
551 """The bottom type, a type that has no members.
552
553 This can be used to define a function that should never be
554 called, or a function that never returns::
555
556 from typing import Never
557
558 def never_call_me(arg: Never) -> None:
559 pass
560
561 def int_or_str(arg: int | str) -> None:
562 never_call_me(arg) # type checker error
563 match arg:
564 case int():
565 print("It's an int")
566 case str():
567 print("It's a str")
568 case _:
569 never_call_me(arg) # OK, arg is of type Never
570 """
571 raise TypeError(f"{self} is not subscriptable")
572
573
574 @_SpecialForm
575 def Self(self, parameters):
576 """Used to spell the type of "self" in classes.
577
578 Example::
579
580 from typing import Self
581
582 class Foo:
583 def return_self(self) -> Self:
584 ...
585 return self
586
587 This is especially useful for:
588 - classmethods that are used as alternative constructors
589 - annotating an `__enter__` method which returns self
590 """
591 raise TypeError(f"{self} is not subscriptable")
592
593
594 @_SpecialForm
595 def LiteralString(self, parameters):
596 """Represents an arbitrary literal string.
597
598 Example::
599
600 from typing import LiteralString
601
602 def run_query(sql: LiteralString) -> None:
603 ...
604
605 def caller(arbitrary_string: str, literal_string: LiteralString) -> None:
606 run_query("SELECT * FROM students") # OK
607 run_query(literal_string) # OK
608 run_query("SELECT * FROM " + literal_string) # OK
609 run_query(arbitrary_string) # type checker error
610 run_query( # type checker error
611 f"SELECT * FROM students WHERE name = {arbitrary_string}"
612 )
613
614 Only string literals and other LiteralStrings are compatible
615 with LiteralString. This provides a tool to help prevent
616 security issues such as SQL injection.
617 """
618 raise TypeError(f"{self} is not subscriptable")
619
620
621 @_SpecialForm
622 def ClassVar(self, parameters):
623 """Special type construct to mark class variables.
624
625 An annotation wrapped in ClassVar indicates that a given
626 attribute is intended to be used as a class variable and
627 should not be set on instances of that class.
628
629 Usage::
630
631 class Starship:
632 stats: ClassVar[dict[str, int]] = {} # class variable
633 damage: int = 10 # instance variable
634
635 ClassVar accepts only types and cannot be further subscribed.
636
637 Note that ClassVar is not a class itself, and should not
638 be used with isinstance() or issubclass().
639 """
640 item = _type_check(parameters, f'{self} accepts only single type.')
641 return _GenericAlias(self, (item,))
642
643 @_SpecialForm
644 def Final(self, parameters):
645 """Special typing construct to indicate final names to type checkers.
646
647 A final name cannot be re-assigned or overridden in a subclass.
648
649 For example::
650
651 MAX_SIZE: Final = 9000
652 MAX_SIZE += 1 # Error reported by type checker
653
654 class Connection:
655 TIMEOUT: Final[int] = 10
656
657 class FastConnector(Connection):
658 TIMEOUT = 1 # Error reported by type checker
659
660 There is no runtime checking of these properties.
661 """
662 item = _type_check(parameters, f'{self} accepts only single type.')
663 return _GenericAlias(self, (item,))
664
665 @_SpecialForm
666 def Union(self, parameters):
667 """Union type; Union[X, Y] means either X or Y.
668
669 On Python 3.10 and higher, the | operator
670 can also be used to denote unions;
671 X | Y means the same thing to the type checker as Union[X, Y].
672
673 To define a union, use e.g. Union[int, str]. Details:
674 - The arguments must be types and there must be at least one.
675 - None as an argument is a special case and is replaced by
676 type(None).
677 - Unions of unions are flattened, e.g.::
678
679 assert Union[Union[int, str], float] == Union[int, str, float]
680
681 - Unions of a single argument vanish, e.g.::
682
683 assert Union[int] == int # The constructor actually returns int
684
685 - Redundant arguments are skipped, e.g.::
686
687 assert Union[int, str, int] == Union[int, str]
688
689 - When comparing unions, the argument order is ignored, e.g.::
690
691 assert Union[int, str] == Union[str, int]
692
693 - You cannot subclass or instantiate a union.
694 - You can use Optional[X] as a shorthand for Union[X, None].
695 """
696 if parameters == ():
697 raise TypeError("Cannot take a Union of no types.")
698 if not isinstance(parameters, tuple):
699 parameters = (parameters,)
700 msg = "Union[arg, ...]: each arg must be a type."
701 parameters = tuple(_type_check(p, msg) for p in parameters)
702 parameters = _remove_dups_flatten(parameters)
703 if len(parameters) == 1:
704 return parameters[0]
705 if len(parameters) == 2 and type(None) in parameters:
706 return _UnionGenericAlias(self, parameters, name="Optional")
707 return _UnionGenericAlias(self, parameters)
708
709 @_SpecialForm
710 def Optional(self, parameters):
711 """Optional[X] is equivalent to Union[X, None]."""
712 arg = _type_check(parameters, f"{self} requires a single type.")
713 return Union[arg, type(None)]
714
715 @_LiteralSpecialForm
716 @_tp_cache(typed=True)
717 def Literal(self, *parameters):
718 """Special typing form to define literal types (a.k.a. value types).
719
720 This form can be used to indicate to type checkers that the corresponding
721 variable or function parameter has a value equivalent to the provided
722 literal (or one of several literals)::
723
724 def validate_simple(data: Any) -> Literal[True]: # always returns True
725 ...
726
727 MODE = Literal['r', 'rb', 'w', 'wb']
728 def open_helper(file: str, mode: MODE) -> str:
729 ...
730
731 open_helper('/some/path', 'r') # Passes type check
732 open_helper('/other/path', 'typo') # Error in type checker
733
734 Literal[...] cannot be subclassed. At runtime, an arbitrary value
735 is allowed as type argument to Literal[...], but type checkers may
736 impose restrictions.
737 """
738 # There is no '_type_check' call because arguments to Literal[...] are
739 # values, not types.
740 parameters = _flatten_literal_params(parameters)
741
742 try:
743 parameters = tuple(p for p, _ in _deduplicate(list(_value_and_type_iter(parameters))))
744 except TypeError: # unhashable parameters
745 pass
746
747 return _LiteralGenericAlias(self, parameters)
748
749
750 @_SpecialForm
751 def TypeAlias(self, parameters):
752 """Special form for marking type aliases.
753
754 Use TypeAlias to indicate that an assignment should
755 be recognized as a proper type alias definition by type
756 checkers.
757
758 For example::
759
760 Predicate: TypeAlias = Callable[..., bool]
761
762 It's invalid when used anywhere except as in the example above.
763 """
764 raise TypeError(f"{self} is not subscriptable")
765
766
767 @_SpecialForm
768 def Concatenate(self, parameters):
769 """Special form for annotating higher-order functions.
770
771 ``Concatenate`` can be used in conjunction with ``ParamSpec`` and
772 ``Callable`` to represent a higher-order function which adds, removes or
773 transforms the parameters of a callable.
774
775 For example::
776
777 Callable[Concatenate[int, P], int]
778
779 See PEP 612 for detailed information.
780 """
781 if parameters == ():
782 raise TypeError("Cannot take a Concatenate of no types.")
783 if not isinstance(parameters, tuple):
784 parameters = (parameters,)
785 if not (parameters[-1] is ... or isinstance(parameters[-1], ParamSpec)):
786 raise TypeError("The last parameter to Concatenate should be a "
787 "ParamSpec variable or ellipsis.")
788 msg = "Concatenate[arg, ...]: each arg must be a type."
789 parameters = (*(_type_check(p, msg) for p in parameters[:-1]), parameters[-1])
790 return _ConcatenateGenericAlias(self, parameters,
791 _paramspec_tvars=True)
792
793
794 @_SpecialForm
795 def TypeGuard(self, parameters):
796 """Special typing construct for marking user-defined type guard functions.
797
798 ``TypeGuard`` can be used to annotate the return type of a user-defined
799 type guard function. ``TypeGuard`` only accepts a single type argument.
800 At runtime, functions marked this way should return a boolean.
801
802 ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
803 type checkers to determine a more precise type of an expression within a
804 program's code flow. Usually type narrowing is done by analyzing
805 conditional code flow and applying the narrowing to a block of code. The
806 conditional expression here is sometimes referred to as a "type guard".
807
808 Sometimes it would be convenient to use a user-defined boolean function
809 as a type guard. Such a function should use ``TypeGuard[...]`` as its
810 return type to alert static type checkers to this intention.
811
812 Using ``-> TypeGuard`` tells the static type checker that for a given
813 function:
814
815 1. The return value is a boolean.
816 2. If the return value is ``True``, the type of its argument
817 is the type inside ``TypeGuard``.
818
819 For example::
820
821 def is_str(val: Union[str, float]):
822 # "isinstance" type guard
823 if isinstance(val, str):
824 # Type of ``val`` is narrowed to ``str``
825 ...
826 else:
827 # Else, type of ``val`` is narrowed to ``float``.
828 ...
829
830 Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
831 form of ``TypeA`` (it can even be a wider form) and this may lead to
832 type-unsafe results. The main reason is to allow for things like
833 narrowing ``List[object]`` to ``List[str]`` even though the latter is not
834 a subtype of the former, since ``List`` is invariant. The responsibility of
835 writing type-safe type guards is left to the user.
836
837 ``TypeGuard`` also works with type variables. For more information, see
838 PEP 647 (User-Defined Type Guards).
839 """
840 item = _type_check(parameters, f'{self} accepts only single type.')
841 return _GenericAlias(self, (item,))
842
843
844 class ESC[4;38;5;81mForwardRef(ESC[4;38;5;149m_Final, _root=ESC[4;38;5;149mTrue):
845 """Internal wrapper to hold a forward reference."""
846
847 __slots__ = ('__forward_arg__', '__forward_code__',
848 '__forward_evaluated__', '__forward_value__',
849 '__forward_is_argument__', '__forward_is_class__',
850 '__forward_module__')
851
852 def __init__(self, arg, is_argument=True, module=None, *, is_class=False):
853 if not isinstance(arg, str):
854 raise TypeError(f"Forward reference must be a string -- got {arg!r}")
855
856 # If we do `def f(*args: *Ts)`, then we'll have `arg = '*Ts'`.
857 # Unfortunately, this isn't a valid expression on its own, so we
858 # do the unpacking manually.
859 if arg[0] == '*':
860 arg_to_compile = f'({arg},)[0]' # E.g. (*Ts,)[0] or (*tuple[int, int],)[0]
861 else:
862 arg_to_compile = arg
863 try:
864 code = compile(arg_to_compile, '<string>', 'eval')
865 except SyntaxError:
866 raise SyntaxError(f"Forward reference must be an expression -- got {arg!r}")
867
868 self.__forward_arg__ = arg
869 self.__forward_code__ = code
870 self.__forward_evaluated__ = False
871 self.__forward_value__ = None
872 self.__forward_is_argument__ = is_argument
873 self.__forward_is_class__ = is_class
874 self.__forward_module__ = module
875
876 def _evaluate(self, globalns, localns, recursive_guard):
877 if self.__forward_arg__ in recursive_guard:
878 return self
879 if not self.__forward_evaluated__ or localns is not globalns:
880 if globalns is None and localns is None:
881 globalns = localns = {}
882 elif globalns is None:
883 globalns = localns
884 elif localns is None:
885 localns = globalns
886 if self.__forward_module__ is not None:
887 globalns = getattr(
888 sys.modules.get(self.__forward_module__, None), '__dict__', globalns
889 )
890 type_ = _type_check(
891 eval(self.__forward_code__, globalns, localns),
892 "Forward references must evaluate to types.",
893 is_argument=self.__forward_is_argument__,
894 allow_special_forms=self.__forward_is_class__,
895 )
896 self.__forward_value__ = _eval_type(
897 type_, globalns, localns, recursive_guard | {self.__forward_arg__}
898 )
899 self.__forward_evaluated__ = True
900 return self.__forward_value__
901
902 def __eq__(self, other):
903 if not isinstance(other, ForwardRef):
904 return NotImplemented
905 if self.__forward_evaluated__ and other.__forward_evaluated__:
906 return (self.__forward_arg__ == other.__forward_arg__ and
907 self.__forward_value__ == other.__forward_value__)
908 return (self.__forward_arg__ == other.__forward_arg__ and
909 self.__forward_module__ == other.__forward_module__)
910
911 def __hash__(self):
912 return hash((self.__forward_arg__, self.__forward_module__))
913
914 def __or__(self, other):
915 return Union[self, other]
916
917 def __ror__(self, other):
918 return Union[other, self]
919
920 def __repr__(self):
921 if self.__forward_module__ is None:
922 module_repr = ''
923 else:
924 module_repr = f', module={self.__forward_module__!r}'
925 return f'ForwardRef({self.__forward_arg__!r}{module_repr})'
926
927
928 def _is_unpacked_typevartuple(x: Any) -> bool:
929 return ((not isinstance(x, type)) and
930 getattr(x, '__typing_is_unpacked_typevartuple__', False))
931
932
933 def _is_typevar_like(x: Any) -> bool:
934 return isinstance(x, (TypeVar, ParamSpec)) or _is_unpacked_typevartuple(x)
935
936
937 class ESC[4;38;5;81m_PickleUsingNameMixin:
938 """Mixin enabling pickling based on self.__name__."""
939
940 def __reduce__(self):
941 return self.__name__
942
943
944 class ESC[4;38;5;81m_BoundVarianceMixin:
945 """Mixin giving __init__ bound and variance arguments.
946
947 This is used by TypeVar and ParamSpec, which both employ the notions of
948 a type 'bound' (restricting type arguments to be a subtype of some
949 specified type) and type 'variance' (determining subtype relations between
950 generic types).
951 """
952 def __init__(self, bound, covariant, contravariant):
953 """Used to setup TypeVars and ParamSpec's bound, covariant and
954 contravariant attributes.
955 """
956 if covariant and contravariant:
957 raise ValueError("Bivariant types are not supported.")
958 self.__covariant__ = bool(covariant)
959 self.__contravariant__ = bool(contravariant)
960 if bound:
961 self.__bound__ = _type_check(bound, "Bound must be a type.")
962 else:
963 self.__bound__ = None
964
965 def __or__(self, right):
966 return Union[self, right]
967
968 def __ror__(self, left):
969 return Union[left, self]
970
971 def __repr__(self):
972 if self.__covariant__:
973 prefix = '+'
974 elif self.__contravariant__:
975 prefix = '-'
976 else:
977 prefix = '~'
978 return prefix + self.__name__
979
980
981 class ESC[4;38;5;81mTypeVar(ESC[4;38;5;149m_Final, ESC[4;38;5;149m_Immutable, ESC[4;38;5;149m_BoundVarianceMixin, ESC[4;38;5;149m_PickleUsingNameMixin,
982 _root=ESC[4;38;5;149mTrue):
983 """Type variable.
984
985 Usage::
986
987 T = TypeVar('T') # Can be anything
988 A = TypeVar('A', str, bytes) # Must be str or bytes
989
990 Type variables exist primarily for the benefit of static type
991 checkers. They serve as the parameters for generic types as well
992 as for generic function definitions. See class Generic for more
993 information on generic types. Generic functions work as follows:
994
995 def repeat(x: T, n: int) -> List[T]:
996 '''Return a list containing n references to x.'''
997 return [x]*n
998
999 def longest(x: A, y: A) -> A:
1000 '''Return the longest of two strings.'''
1001 return x if len(x) >= len(y) else y
1002
1003 The latter example's signature is essentially the overloading
1004 of (str, str) -> str and (bytes, bytes) -> bytes. Also note
1005 that if the arguments are instances of some subclass of str,
1006 the return type is still plain str.
1007
1008 At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.
1009
1010 Type variables defined with covariant=True or contravariant=True
1011 can be used to declare covariant or contravariant generic types.
1012 See PEP 484 for more details. By default generic types are invariant
1013 in all type variables.
1014
1015 Type variables can be introspected. e.g.:
1016
1017 T.__name__ == 'T'
1018 T.__constraints__ == ()
1019 T.__covariant__ == False
1020 T.__contravariant__ = False
1021 A.__constraints__ == (str, bytes)
1022
1023 Note that only type variables defined in global scope can be pickled.
1024 """
1025
1026 def __init__(self, name, *constraints, bound=None,
1027 covariant=False, contravariant=False):
1028 self.__name__ = name
1029 super().__init__(bound, covariant, contravariant)
1030 if constraints and bound is not None:
1031 raise TypeError("Constraints cannot be combined with bound=...")
1032 if constraints and len(constraints) == 1:
1033 raise TypeError("A single constraint is not allowed")
1034 msg = "TypeVar(name, constraint, ...): constraints must be types."
1035 self.__constraints__ = tuple(_type_check(t, msg) for t in constraints)
1036 def_mod = _caller()
1037 if def_mod != 'typing':
1038 self.__module__ = def_mod
1039
1040 def __typing_subst__(self, arg):
1041 msg = "Parameters to generic types must be types."
1042 arg = _type_check(arg, msg, is_argument=True)
1043 if ((isinstance(arg, _GenericAlias) and arg.__origin__ is Unpack) or
1044 (isinstance(arg, GenericAlias) and getattr(arg, '__unpacked__', False))):
1045 raise TypeError(f"{arg} is not valid as type argument")
1046 return arg
1047
1048
1049 class ESC[4;38;5;81mTypeVarTuple(ESC[4;38;5;149m_Final, ESC[4;38;5;149m_Immutable, ESC[4;38;5;149m_PickleUsingNameMixin, _root=ESC[4;38;5;149mTrue):
1050 """Type variable tuple.
1051
1052 Usage:
1053
1054 Ts = TypeVarTuple('Ts') # Can be given any name
1055
1056 Just as a TypeVar (type variable) is a placeholder for a single type,
1057 a TypeVarTuple is a placeholder for an *arbitrary* number of types. For
1058 example, if we define a generic class using a TypeVarTuple:
1059
1060 class C(Generic[*Ts]): ...
1061
1062 Then we can parameterize that class with an arbitrary number of type
1063 arguments:
1064
1065 C[int] # Fine
1066 C[int, str] # Also fine
1067 C[()] # Even this is fine
1068
1069 For more details, see PEP 646.
1070
1071 Note that only TypeVarTuples defined in global scope can be pickled.
1072 """
1073
1074 def __init__(self, name):
1075 self.__name__ = name
1076
1077 # Used for pickling.
1078 def_mod = _caller()
1079 if def_mod != 'typing':
1080 self.__module__ = def_mod
1081
1082 def __iter__(self):
1083 yield Unpack[self]
1084
1085 def __repr__(self):
1086 return self.__name__
1087
1088 def __typing_subst__(self, arg):
1089 raise TypeError("Substitution of bare TypeVarTuple is not supported")
1090
1091 def __typing_prepare_subst__(self, alias, args):
1092 params = alias.__parameters__
1093 typevartuple_index = params.index(self)
1094 for param in params[typevartuple_index + 1:]:
1095 if isinstance(param, TypeVarTuple):
1096 raise TypeError(f"More than one TypeVarTuple parameter in {alias}")
1097
1098 alen = len(args)
1099 plen = len(params)
1100 left = typevartuple_index
1101 right = plen - typevartuple_index - 1
1102 var_tuple_index = None
1103 fillarg = None
1104 for k, arg in enumerate(args):
1105 if not isinstance(arg, type):
1106 subargs = getattr(arg, '__typing_unpacked_tuple_args__', None)
1107 if subargs and len(subargs) == 2 and subargs[-1] is ...:
1108 if var_tuple_index is not None:
1109 raise TypeError("More than one unpacked arbitrary-length tuple argument")
1110 var_tuple_index = k
1111 fillarg = subargs[0]
1112 if var_tuple_index is not None:
1113 left = min(left, var_tuple_index)
1114 right = min(right, alen - var_tuple_index - 1)
1115 elif left + right > alen:
1116 raise TypeError(f"Too few arguments for {alias};"
1117 f" actual {alen}, expected at least {plen-1}")
1118
1119 return (
1120 *args[:left],
1121 *([fillarg]*(typevartuple_index - left)),
1122 tuple(args[left: alen - right]),
1123 *([fillarg]*(plen - right - left - typevartuple_index - 1)),
1124 *args[alen - right:],
1125 )
1126
1127
1128 class ESC[4;38;5;81mParamSpecArgs(ESC[4;38;5;149m_Final, ESC[4;38;5;149m_Immutable, _root=ESC[4;38;5;149mTrue):
1129 """The args for a ParamSpec object.
1130
1131 Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.
1132
1133 ParamSpecArgs objects have a reference back to their ParamSpec:
1134
1135 P.args.__origin__ is P
1136
1137 This type is meant for runtime introspection and has no special meaning to
1138 static type checkers.
1139 """
1140 def __init__(self, origin):
1141 self.__origin__ = origin
1142
1143 def __repr__(self):
1144 return f"{self.__origin__.__name__}.args"
1145
1146 def __eq__(self, other):
1147 if not isinstance(other, ParamSpecArgs):
1148 return NotImplemented
1149 return self.__origin__ == other.__origin__
1150
1151
1152 class ESC[4;38;5;81mParamSpecKwargs(ESC[4;38;5;149m_Final, ESC[4;38;5;149m_Immutable, _root=ESC[4;38;5;149mTrue):
1153 """The kwargs for a ParamSpec object.
1154
1155 Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs.
1156
1157 ParamSpecKwargs objects have a reference back to their ParamSpec:
1158
1159 P.kwargs.__origin__ is P
1160
1161 This type is meant for runtime introspection and has no special meaning to
1162 static type checkers.
1163 """
1164 def __init__(self, origin):
1165 self.__origin__ = origin
1166
1167 def __repr__(self):
1168 return f"{self.__origin__.__name__}.kwargs"
1169
1170 def __eq__(self, other):
1171 if not isinstance(other, ParamSpecKwargs):
1172 return NotImplemented
1173 return self.__origin__ == other.__origin__
1174
1175
1176 class ESC[4;38;5;81mParamSpec(ESC[4;38;5;149m_Final, ESC[4;38;5;149m_Immutable, ESC[4;38;5;149m_BoundVarianceMixin, ESC[4;38;5;149m_PickleUsingNameMixin,
1177 _root=ESC[4;38;5;149mTrue):
1178 """Parameter specification variable.
1179
1180 Usage::
1181
1182 P = ParamSpec('P')
1183
1184 Parameter specification variables exist primarily for the benefit of static
1185 type checkers. They are used to forward the parameter types of one
1186 callable to another callable, a pattern commonly found in higher order
1187 functions and decorators. They are only valid when used in ``Concatenate``,
1188 or as the first argument to ``Callable``, or as parameters for user-defined
1189 Generics. See class Generic for more information on generic types. An
1190 example for annotating a decorator::
1191
1192 T = TypeVar('T')
1193 P = ParamSpec('P')
1194
1195 def add_logging(f: Callable[P, T]) -> Callable[P, T]:
1196 '''A type-safe decorator to add logging to a function.'''
1197 def inner(*args: P.args, **kwargs: P.kwargs) -> T:
1198 logging.info(f'{f.__name__} was called')
1199 return f(*args, **kwargs)
1200 return inner
1201
1202 @add_logging
1203 def add_two(x: float, y: float) -> float:
1204 '''Add two numbers together.'''
1205 return x + y
1206
1207 Parameter specification variables can be introspected. e.g.:
1208
1209 P.__name__ == 'P'
1210
1211 Note that only parameter specification variables defined in global scope can
1212 be pickled.
1213 """
1214
1215 @property
1216 def args(self):
1217 return ParamSpecArgs(self)
1218
1219 @property
1220 def kwargs(self):
1221 return ParamSpecKwargs(self)
1222
1223 def __init__(self, name, *, bound=None, covariant=False, contravariant=False):
1224 self.__name__ = name
1225 super().__init__(bound, covariant, contravariant)
1226 def_mod = _caller()
1227 if def_mod != 'typing':
1228 self.__module__ = def_mod
1229
1230 def __typing_subst__(self, arg):
1231 if isinstance(arg, (list, tuple)):
1232 arg = tuple(_type_check(a, "Expected a type.") for a in arg)
1233 elif not _is_param_expr(arg):
1234 raise TypeError(f"Expected a list of types, an ellipsis, "
1235 f"ParamSpec, or Concatenate. Got {arg}")
1236 return arg
1237
1238 def __typing_prepare_subst__(self, alias, args):
1239 params = alias.__parameters__
1240 i = params.index(self)
1241 if i >= len(args):
1242 raise TypeError(f"Too few arguments for {alias}")
1243 # Special case where Z[[int, str, bool]] == Z[int, str, bool] in PEP 612.
1244 if len(params) == 1 and not _is_param_expr(args[0]):
1245 assert i == 0
1246 args = (args,)
1247 # Convert lists to tuples to help other libraries cache the results.
1248 elif isinstance(args[i], list):
1249 args = (*args[:i], tuple(args[i]), *args[i+1:])
1250 return args
1251
1252 def _is_dunder(attr):
1253 return attr.startswith('__') and attr.endswith('__')
1254
1255 class ESC[4;38;5;81m_BaseGenericAlias(ESC[4;38;5;149m_Final, _root=ESC[4;38;5;149mTrue):
1256 """The central part of the internal API.
1257
1258 This represents a generic version of type 'origin' with type arguments 'params'.
1259 There are two kind of these aliases: user defined and special. The special ones
1260 are wrappers around builtin collections and ABCs in collections.abc. These must
1261 have 'name' always set. If 'inst' is False, then the alias can't be instantiated;
1262 this is used by e.g. typing.List and typing.Dict.
1263 """
1264
1265 def __init__(self, origin, *, inst=True, name=None):
1266 self._inst = inst
1267 self._name = name
1268 self.__origin__ = origin
1269 self.__slots__ = None # This is not documented.
1270
1271 def __call__(self, *args, **kwargs):
1272 if not self._inst:
1273 raise TypeError(f"Type {self._name} cannot be instantiated; "
1274 f"use {self.__origin__.__name__}() instead")
1275 result = self.__origin__(*args, **kwargs)
1276 try:
1277 result.__orig_class__ = self
1278 except AttributeError:
1279 pass
1280 return result
1281
1282 def __mro_entries__(self, bases):
1283 res = []
1284 if self.__origin__ not in bases:
1285 res.append(self.__origin__)
1286 i = bases.index(self)
1287 for b in bases[i+1:]:
1288 if isinstance(b, _BaseGenericAlias) or issubclass(b, Generic):
1289 break
1290 else:
1291 res.append(Generic)
1292 return tuple(res)
1293
1294 def __getattr__(self, attr):
1295 if attr in {'__name__', '__qualname__'}:
1296 return self._name or self.__origin__.__name__
1297
1298 # We are careful for copy and pickle.
1299 # Also for simplicity we don't relay any dunder names
1300 if '__origin__' in self.__dict__ and not _is_dunder(attr):
1301 return getattr(self.__origin__, attr)
1302 raise AttributeError(attr)
1303
1304 def __setattr__(self, attr, val):
1305 if _is_dunder(attr) or attr in {'_name', '_inst', '_nparams',
1306 '_paramspec_tvars'}:
1307 super().__setattr__(attr, val)
1308 else:
1309 setattr(self.__origin__, attr, val)
1310
1311 def __instancecheck__(self, obj):
1312 return self.__subclasscheck__(type(obj))
1313
1314 def __subclasscheck__(self, cls):
1315 raise TypeError("Subscripted generics cannot be used with"
1316 " class and instance checks")
1317
1318 def __dir__(self):
1319 return list(set(super().__dir__()
1320 + [attr for attr in dir(self.__origin__) if not _is_dunder(attr)]))
1321
1322
1323 # Special typing constructs Union, Optional, Generic, Callable and Tuple
1324 # use three special attributes for internal bookkeeping of generic types:
1325 # * __parameters__ is a tuple of unique free type parameters of a generic
1326 # type, for example, Dict[T, T].__parameters__ == (T,);
1327 # * __origin__ keeps a reference to a type that was subscripted,
1328 # e.g., Union[T, int].__origin__ == Union, or the non-generic version of
1329 # the type.
1330 # * __args__ is a tuple of all arguments used in subscripting,
1331 # e.g., Dict[T, int].__args__ == (T, int).
1332
1333
1334 class ESC[4;38;5;81m_GenericAlias(ESC[4;38;5;149m_BaseGenericAlias, _root=ESC[4;38;5;149mTrue):
1335 # The type of parameterized generics.
1336 #
1337 # That is, for example, `type(List[int])` is `_GenericAlias`.
1338 #
1339 # Objects which are instances of this class include:
1340 # * Parameterized container types, e.g. `Tuple[int]`, `List[int]`.
1341 # * Note that native container types, e.g. `tuple`, `list`, use
1342 # `types.GenericAlias` instead.
1343 # * Parameterized classes:
1344 # T = TypeVar('T')
1345 # class C(Generic[T]): pass
1346 # # C[int] is a _GenericAlias
1347 # * `Callable` aliases, generic `Callable` aliases, and
1348 # parameterized `Callable` aliases:
1349 # T = TypeVar('T')
1350 # # _CallableGenericAlias inherits from _GenericAlias.
1351 # A = Callable[[], None] # _CallableGenericAlias
1352 # B = Callable[[T], None] # _CallableGenericAlias
1353 # C = B[int] # _CallableGenericAlias
1354 # * Parameterized `Final`, `ClassVar` and `TypeGuard`:
1355 # # All _GenericAlias
1356 # Final[int]
1357 # ClassVar[float]
1358 # TypeVar[bool]
1359
1360 def __init__(self, origin, args, *, inst=True, name=None,
1361 _paramspec_tvars=False):
1362 super().__init__(origin, inst=inst, name=name)
1363 if not isinstance(args, tuple):
1364 args = (args,)
1365 self.__args__ = tuple(... if a is _TypingEllipsis else
1366 a for a in args)
1367 self.__parameters__ = _collect_parameters(args)
1368 self._paramspec_tvars = _paramspec_tvars
1369 if not name:
1370 self.__module__ = origin.__module__
1371
1372 def __eq__(self, other):
1373 if not isinstance(other, _GenericAlias):
1374 return NotImplemented
1375 return (self.__origin__ == other.__origin__
1376 and self.__args__ == other.__args__)
1377
1378 def __hash__(self):
1379 return hash((self.__origin__, self.__args__))
1380
1381 def __or__(self, right):
1382 return Union[self, right]
1383
1384 def __ror__(self, left):
1385 return Union[left, self]
1386
1387 @_tp_cache
1388 def __getitem__(self, args):
1389 # Parameterizes an already-parameterized object.
1390 #
1391 # For example, we arrive here doing something like:
1392 # T1 = TypeVar('T1')
1393 # T2 = TypeVar('T2')
1394 # T3 = TypeVar('T3')
1395 # class A(Generic[T1]): pass
1396 # B = A[T2] # B is a _GenericAlias
1397 # C = B[T3] # Invokes _GenericAlias.__getitem__
1398 #
1399 # We also arrive here when parameterizing a generic `Callable` alias:
1400 # T = TypeVar('T')
1401 # C = Callable[[T], None]
1402 # C[int] # Invokes _GenericAlias.__getitem__
1403
1404 if self.__origin__ in (Generic, Protocol):
1405 # Can't subscript Generic[...] or Protocol[...].
1406 raise TypeError(f"Cannot subscript already-subscripted {self}")
1407 if not self.__parameters__:
1408 raise TypeError(f"{self} is not a generic class")
1409
1410 # Preprocess `args`.
1411 if not isinstance(args, tuple):
1412 args = (args,)
1413 args = tuple(_type_convert(p) for p in args)
1414 args = _unpack_args(args)
1415 new_args = self._determine_new_args(args)
1416 r = self.copy_with(new_args)
1417 return r
1418
1419 def _determine_new_args(self, args):
1420 # Determines new __args__ for __getitem__.
1421 #
1422 # For example, suppose we had:
1423 # T1 = TypeVar('T1')
1424 # T2 = TypeVar('T2')
1425 # class A(Generic[T1, T2]): pass
1426 # T3 = TypeVar('T3')
1427 # B = A[int, T3]
1428 # C = B[str]
1429 # `B.__args__` is `(int, T3)`, so `C.__args__` should be `(int, str)`.
1430 # Unfortunately, this is harder than it looks, because if `T3` is
1431 # anything more exotic than a plain `TypeVar`, we need to consider
1432 # edge cases.
1433
1434 params = self.__parameters__
1435 # In the example above, this would be {T3: str}
1436 for param in params:
1437 prepare = getattr(param, '__typing_prepare_subst__', None)
1438 if prepare is not None:
1439 args = prepare(self, args)
1440 alen = len(args)
1441 plen = len(params)
1442 if alen != plen:
1443 raise TypeError(f"Too {'many' if alen > plen else 'few'} arguments for {self};"
1444 f" actual {alen}, expected {plen}")
1445 new_arg_by_param = dict(zip(params, args))
1446 return tuple(self._make_substitution(self.__args__, new_arg_by_param))
1447
1448 def _make_substitution(self, args, new_arg_by_param):
1449 """Create a list of new type arguments."""
1450 new_args = []
1451 for old_arg in args:
1452 if isinstance(old_arg, type):
1453 new_args.append(old_arg)
1454 continue
1455
1456 substfunc = getattr(old_arg, '__typing_subst__', None)
1457 if substfunc:
1458 new_arg = substfunc(new_arg_by_param[old_arg])
1459 else:
1460 subparams = getattr(old_arg, '__parameters__', ())
1461 if not subparams:
1462 new_arg = old_arg
1463 else:
1464 subargs = []
1465 for x in subparams:
1466 if isinstance(x, TypeVarTuple):
1467 subargs.extend(new_arg_by_param[x])
1468 else:
1469 subargs.append(new_arg_by_param[x])
1470 new_arg = old_arg[tuple(subargs)]
1471
1472 if self.__origin__ == collections.abc.Callable and isinstance(new_arg, tuple):
1473 # Consider the following `Callable`.
1474 # C = Callable[[int], str]
1475 # Here, `C.__args__` should be (int, str) - NOT ([int], str).
1476 # That means that if we had something like...
1477 # P = ParamSpec('P')
1478 # T = TypeVar('T')
1479 # C = Callable[P, T]
1480 # D = C[[int, str], float]
1481 # ...we need to be careful; `new_args` should end up as
1482 # `(int, str, float)` rather than `([int, str], float)`.
1483 new_args.extend(new_arg)
1484 elif _is_unpacked_typevartuple(old_arg):
1485 # Consider the following `_GenericAlias`, `B`:
1486 # class A(Generic[*Ts]): ...
1487 # B = A[T, *Ts]
1488 # If we then do:
1489 # B[float, int, str]
1490 # The `new_arg` corresponding to `T` will be `float`, and the
1491 # `new_arg` corresponding to `*Ts` will be `(int, str)`. We
1492 # should join all these types together in a flat list
1493 # `(float, int, str)` - so again, we should `extend`.
1494 new_args.extend(new_arg)
1495 elif isinstance(old_arg, tuple):
1496 # Corner case:
1497 # P = ParamSpec('P')
1498 # T = TypeVar('T')
1499 # class Base(Generic[P]): ...
1500 # Can be substituted like this:
1501 # X = Base[[int, T]]
1502 # In this case, `old_arg` will be a tuple:
1503 new_args.append(
1504 tuple(self._make_substitution(old_arg, new_arg_by_param)),
1505 )
1506 else:
1507 new_args.append(new_arg)
1508 return new_args
1509
1510 def copy_with(self, args):
1511 return self.__class__(self.__origin__, args, name=self._name, inst=self._inst,
1512 _paramspec_tvars=self._paramspec_tvars)
1513
1514 def __repr__(self):
1515 if self._name:
1516 name = 'typing.' + self._name
1517 else:
1518 name = _type_repr(self.__origin__)
1519 if self.__args__:
1520 args = ", ".join([_type_repr(a) for a in self.__args__])
1521 else:
1522 # To ensure the repr is eval-able.
1523 args = "()"
1524 return f'{name}[{args}]'
1525
1526 def __reduce__(self):
1527 if self._name:
1528 origin = globals()[self._name]
1529 else:
1530 origin = self.__origin__
1531 args = tuple(self.__args__)
1532 if len(args) == 1 and not isinstance(args[0], tuple):
1533 args, = args
1534 return operator.getitem, (origin, args)
1535
1536 def __mro_entries__(self, bases):
1537 if isinstance(self.__origin__, _SpecialForm):
1538 raise TypeError(f"Cannot subclass {self!r}")
1539
1540 if self._name: # generic version of an ABC or built-in class
1541 return super().__mro_entries__(bases)
1542 if self.__origin__ is Generic:
1543 if Protocol in bases:
1544 return ()
1545 i = bases.index(self)
1546 for b in bases[i+1:]:
1547 if isinstance(b, _BaseGenericAlias) and b is not self:
1548 return ()
1549 return (self.__origin__,)
1550
1551 def __iter__(self):
1552 yield Unpack[self]
1553
1554
1555 # _nparams is the number of accepted parameters, e.g. 0 for Hashable,
1556 # 1 for List and 2 for Dict. It may be -1 if variable number of
1557 # parameters are accepted (needs custom __getitem__).
1558
1559 class ESC[4;38;5;81m_SpecialGenericAlias(ESC[4;38;5;149m_NotIterable, ESC[4;38;5;149m_BaseGenericAlias, _root=ESC[4;38;5;149mTrue):
1560 def __init__(self, origin, nparams, *, inst=True, name=None):
1561 if name is None:
1562 name = origin.__name__
1563 super().__init__(origin, inst=inst, name=name)
1564 self._nparams = nparams
1565 if origin.__module__ == 'builtins':
1566 self.__doc__ = f'A generic version of {origin.__qualname__}.'
1567 else:
1568 self.__doc__ = f'A generic version of {origin.__module__}.{origin.__qualname__}.'
1569
1570 @_tp_cache
1571 def __getitem__(self, params):
1572 if not isinstance(params, tuple):
1573 params = (params,)
1574 msg = "Parameters to generic types must be types."
1575 params = tuple(_type_check(p, msg) for p in params)
1576 _check_generic(self, params, self._nparams)
1577 return self.copy_with(params)
1578
1579 def copy_with(self, params):
1580 return _GenericAlias(self.__origin__, params,
1581 name=self._name, inst=self._inst)
1582
1583 def __repr__(self):
1584 return 'typing.' + self._name
1585
1586 def __subclasscheck__(self, cls):
1587 if isinstance(cls, _SpecialGenericAlias):
1588 return issubclass(cls.__origin__, self.__origin__)
1589 if not isinstance(cls, _GenericAlias):
1590 return issubclass(cls, self.__origin__)
1591 return super().__subclasscheck__(cls)
1592
1593 def __reduce__(self):
1594 return self._name
1595
1596 def __or__(self, right):
1597 return Union[self, right]
1598
1599 def __ror__(self, left):
1600 return Union[left, self]
1601
1602 class ESC[4;38;5;81m_CallableGenericAlias(ESC[4;38;5;149m_NotIterable, ESC[4;38;5;149m_GenericAlias, _root=ESC[4;38;5;149mTrue):
1603 def __repr__(self):
1604 assert self._name == 'Callable'
1605 args = self.__args__
1606 if len(args) == 2 and _is_param_expr(args[0]):
1607 return super().__repr__()
1608 return (f'typing.Callable'
1609 f'[[{", ".join([_type_repr(a) for a in args[:-1]])}], '
1610 f'{_type_repr(args[-1])}]')
1611
1612 def __reduce__(self):
1613 args = self.__args__
1614 if not (len(args) == 2 and _is_param_expr(args[0])):
1615 args = list(args[:-1]), args[-1]
1616 return operator.getitem, (Callable, args)
1617
1618
1619 class ESC[4;38;5;81m_CallableType(ESC[4;38;5;149m_SpecialGenericAlias, _root=ESC[4;38;5;149mTrue):
1620 def copy_with(self, params):
1621 return _CallableGenericAlias(self.__origin__, params,
1622 name=self._name, inst=self._inst,
1623 _paramspec_tvars=True)
1624
1625 def __getitem__(self, params):
1626 if not isinstance(params, tuple) or len(params) != 2:
1627 raise TypeError("Callable must be used as "
1628 "Callable[[arg, ...], result].")
1629 args, result = params
1630 # This relaxes what args can be on purpose to allow things like
1631 # PEP 612 ParamSpec. Responsibility for whether a user is using
1632 # Callable[...] properly is deferred to static type checkers.
1633 if isinstance(args, list):
1634 params = (tuple(args), result)
1635 else:
1636 params = (args, result)
1637 return self.__getitem_inner__(params)
1638
1639 @_tp_cache
1640 def __getitem_inner__(self, params):
1641 args, result = params
1642 msg = "Callable[args, result]: result must be a type."
1643 result = _type_check(result, msg)
1644 if args is Ellipsis:
1645 return self.copy_with((_TypingEllipsis, result))
1646 if not isinstance(args, tuple):
1647 args = (args,)
1648 args = tuple(_type_convert(arg) for arg in args)
1649 params = args + (result,)
1650 return self.copy_with(params)
1651
1652
1653 class ESC[4;38;5;81m_TupleType(ESC[4;38;5;149m_SpecialGenericAlias, _root=ESC[4;38;5;149mTrue):
1654 @_tp_cache
1655 def __getitem__(self, params):
1656 if not isinstance(params, tuple):
1657 params = (params,)
1658 if len(params) >= 2 and params[-1] is ...:
1659 msg = "Tuple[t, ...]: t must be a type."
1660 params = tuple(_type_check(p, msg) for p in params[:-1])
1661 return self.copy_with((*params, _TypingEllipsis))
1662 msg = "Tuple[t0, t1, ...]: each t must be a type."
1663 params = tuple(_type_check(p, msg) for p in params)
1664 return self.copy_with(params)
1665
1666
1667 class ESC[4;38;5;81m_UnionGenericAlias(ESC[4;38;5;149m_NotIterable, ESC[4;38;5;149m_GenericAlias, _root=ESC[4;38;5;149mTrue):
1668 def copy_with(self, params):
1669 return Union[params]
1670
1671 def __eq__(self, other):
1672 if not isinstance(other, (_UnionGenericAlias, types.UnionType)):
1673 return NotImplemented
1674 return set(self.__args__) == set(other.__args__)
1675
1676 def __hash__(self):
1677 return hash(frozenset(self.__args__))
1678
1679 def __repr__(self):
1680 args = self.__args__
1681 if len(args) == 2:
1682 if args[0] is type(None):
1683 return f'typing.Optional[{_type_repr(args[1])}]'
1684 elif args[1] is type(None):
1685 return f'typing.Optional[{_type_repr(args[0])}]'
1686 return super().__repr__()
1687
1688 def __instancecheck__(self, obj):
1689 return self.__subclasscheck__(type(obj))
1690
1691 def __subclasscheck__(self, cls):
1692 for arg in self.__args__:
1693 if issubclass(cls, arg):
1694 return True
1695
1696 def __reduce__(self):
1697 func, (origin, args) = super().__reduce__()
1698 return func, (Union, args)
1699
1700
1701 def _value_and_type_iter(parameters):
1702 return ((p, type(p)) for p in parameters)
1703
1704
1705 class ESC[4;38;5;81m_LiteralGenericAlias(ESC[4;38;5;149m_GenericAlias, _root=ESC[4;38;5;149mTrue):
1706 def __eq__(self, other):
1707 if not isinstance(other, _LiteralGenericAlias):
1708 return NotImplemented
1709
1710 return set(_value_and_type_iter(self.__args__)) == set(_value_and_type_iter(other.__args__))
1711
1712 def __hash__(self):
1713 return hash(frozenset(_value_and_type_iter(self.__args__)))
1714
1715
1716 class ESC[4;38;5;81m_ConcatenateGenericAlias(ESC[4;38;5;149m_GenericAlias, _root=ESC[4;38;5;149mTrue):
1717 def copy_with(self, params):
1718 if isinstance(params[-1], (list, tuple)):
1719 return (*params[:-1], *params[-1])
1720 if isinstance(params[-1], _ConcatenateGenericAlias):
1721 params = (*params[:-1], *params[-1].__args__)
1722 return super().copy_with(params)
1723
1724
1725 @_SpecialForm
1726 def Unpack(self, parameters):
1727 """Type unpack operator.
1728
1729 The type unpack operator takes the child types from some container type,
1730 such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'.
1731
1732 For example::
1733
1734 # For some generic class `Foo`:
1735 Foo[Unpack[tuple[int, str]]] # Equivalent to Foo[int, str]
1736
1737 Ts = TypeVarTuple('Ts')
1738 # Specifies that `Bar` is generic in an arbitrary number of types.
1739 # (Think of `Ts` as a tuple of an arbitrary number of individual
1740 # `TypeVar`s, which the `Unpack` is 'pulling out' directly into the
1741 # `Generic[]`.)
1742 class Bar(Generic[Unpack[Ts]]): ...
1743 Bar[int] # Valid
1744 Bar[int, str] # Also valid
1745
1746 From Python 3.11, this can also be done using the `*` operator::
1747
1748 Foo[*tuple[int, str]]
1749 class Bar(Generic[*Ts]): ...
1750
1751 Note that there is only some runtime checking of this operator. Not
1752 everything the runtime allows may be accepted by static type checkers.
1753
1754 For more information, see PEP 646.
1755 """
1756 item = _type_check(parameters, f'{self} accepts only single type.')
1757 return _UnpackGenericAlias(origin=self, args=(item,))
1758
1759
1760 class ESC[4;38;5;81m_UnpackGenericAlias(ESC[4;38;5;149m_GenericAlias, _root=ESC[4;38;5;149mTrue):
1761 def __repr__(self):
1762 # `Unpack` only takes one argument, so __args__ should contain only
1763 # a single item.
1764 return '*' + repr(self.__args__[0])
1765
1766 def __getitem__(self, args):
1767 if self.__typing_is_unpacked_typevartuple__:
1768 return args
1769 return super().__getitem__(args)
1770
1771 @property
1772 def __typing_unpacked_tuple_args__(self):
1773 assert self.__origin__ is Unpack
1774 assert len(self.__args__) == 1
1775 arg, = self.__args__
1776 if isinstance(arg, _GenericAlias):
1777 assert arg.__origin__ is tuple
1778 return arg.__args__
1779 return None
1780
1781 @property
1782 def __typing_is_unpacked_typevartuple__(self):
1783 assert self.__origin__ is Unpack
1784 assert len(self.__args__) == 1
1785 return isinstance(self.__args__[0], TypeVarTuple)
1786
1787
1788 class ESC[4;38;5;81mGeneric:
1789 """Abstract base class for generic types.
1790
1791 A generic type is typically declared by inheriting from
1792 this class parameterized with one or more type variables.
1793 For example, a generic mapping type might be defined as::
1794
1795 class Mapping(Generic[KT, VT]):
1796 def __getitem__(self, key: KT) -> VT:
1797 ...
1798 # Etc.
1799
1800 This class can then be used as follows::
1801
1802 def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
1803 try:
1804 return mapping[key]
1805 except KeyError:
1806 return default
1807 """
1808 __slots__ = ()
1809 _is_protocol = False
1810
1811 @_tp_cache
1812 def __class_getitem__(cls, params):
1813 """Parameterizes a generic class.
1814
1815 At least, parameterizing a generic class is the *main* thing this method
1816 does. For example, for some generic class `Foo`, this is called when we
1817 do `Foo[int]` - there, with `cls=Foo` and `params=int`.
1818
1819 However, note that this method is also called when defining generic
1820 classes in the first place with `class Foo(Generic[T]): ...`.
1821 """
1822 if not isinstance(params, tuple):
1823 params = (params,)
1824
1825 params = tuple(_type_convert(p) for p in params)
1826 if cls in (Generic, Protocol):
1827 # Generic and Protocol can only be subscripted with unique type variables.
1828 if not params:
1829 raise TypeError(
1830 f"Parameter list to {cls.__qualname__}[...] cannot be empty"
1831 )
1832 if not all(_is_typevar_like(p) for p in params):
1833 raise TypeError(
1834 f"Parameters to {cls.__name__}[...] must all be type variables "
1835 f"or parameter specification variables.")
1836 if len(set(params)) != len(params):
1837 raise TypeError(
1838 f"Parameters to {cls.__name__}[...] must all be unique")
1839 else:
1840 # Subscripting a regular Generic subclass.
1841 for param in cls.__parameters__:
1842 prepare = getattr(param, '__typing_prepare_subst__', None)
1843 if prepare is not None:
1844 params = prepare(cls, params)
1845 _check_generic(cls, params, len(cls.__parameters__))
1846
1847 new_args = []
1848 for param, new_arg in zip(cls.__parameters__, params):
1849 if isinstance(param, TypeVarTuple):
1850 new_args.extend(new_arg)
1851 else:
1852 new_args.append(new_arg)
1853 params = tuple(new_args)
1854
1855 return _GenericAlias(cls, params,
1856 _paramspec_tvars=True)
1857
1858 def __init_subclass__(cls, *args, **kwargs):
1859 super().__init_subclass__(*args, **kwargs)
1860 tvars = []
1861 if '__orig_bases__' in cls.__dict__:
1862 error = Generic in cls.__orig_bases__
1863 else:
1864 error = (Generic in cls.__bases__ and
1865 cls.__name__ != 'Protocol' and
1866 type(cls) != _TypedDictMeta)
1867 if error:
1868 raise TypeError("Cannot inherit from plain Generic")
1869 if '__orig_bases__' in cls.__dict__:
1870 tvars = _collect_parameters(cls.__orig_bases__)
1871 # Look for Generic[T1, ..., Tn].
1872 # If found, tvars must be a subset of it.
1873 # If not found, tvars is it.
1874 # Also check for and reject plain Generic,
1875 # and reject multiple Generic[...].
1876 gvars = None
1877 for base in cls.__orig_bases__:
1878 if (isinstance(base, _GenericAlias) and
1879 base.__origin__ is Generic):
1880 if gvars is not None:
1881 raise TypeError(
1882 "Cannot inherit from Generic[...] multiple times.")
1883 gvars = base.__parameters__
1884 if gvars is not None:
1885 tvarset = set(tvars)
1886 gvarset = set(gvars)
1887 if not tvarset <= gvarset:
1888 s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)
1889 s_args = ', '.join(str(g) for g in gvars)
1890 raise TypeError(f"Some type variables ({s_vars}) are"
1891 f" not listed in Generic[{s_args}]")
1892 tvars = gvars
1893 cls.__parameters__ = tuple(tvars)
1894
1895
1896 class ESC[4;38;5;81m_TypingEllipsis:
1897 """Internal placeholder for ... (ellipsis)."""
1898
1899
1900 _TYPING_INTERNALS = ['__parameters__', '__orig_bases__', '__orig_class__',
1901 '_is_protocol', '_is_runtime_protocol', '__final__']
1902
1903 _SPECIAL_NAMES = ['__abstractmethods__', '__annotations__', '__dict__', '__doc__',
1904 '__init__', '__module__', '__new__', '__slots__',
1905 '__subclasshook__', '__weakref__', '__class_getitem__']
1906
1907 # These special attributes will be not collected as protocol members.
1908 EXCLUDED_ATTRIBUTES = _TYPING_INTERNALS + _SPECIAL_NAMES + ['_MutableMapping__marker']
1909
1910
1911 def _get_protocol_attrs(cls):
1912 """Collect protocol members from a protocol class objects.
1913
1914 This includes names actually defined in the class dictionary, as well
1915 as names that appear in annotations. Special names (above) are skipped.
1916 """
1917 attrs = set()
1918 for base in cls.__mro__[:-1]: # without object
1919 if base.__name__ in ('Protocol', 'Generic'):
1920 continue
1921 annotations = getattr(base, '__annotations__', {})
1922 for attr in list(base.__dict__.keys()) + list(annotations.keys()):
1923 if not attr.startswith('_abc_') and attr not in EXCLUDED_ATTRIBUTES:
1924 attrs.add(attr)
1925 return attrs
1926
1927
1928 def _is_callable_members_only(cls):
1929 # PEP 544 prohibits using issubclass() with protocols that have non-method members.
1930 return all(callable(getattr(cls, attr, None)) for attr in _get_protocol_attrs(cls))
1931
1932
1933 def _no_init_or_replace_init(self, *args, **kwargs):
1934 cls = type(self)
1935
1936 if cls._is_protocol:
1937 raise TypeError('Protocols cannot be instantiated')
1938
1939 # Already using a custom `__init__`. No need to calculate correct
1940 # `__init__` to call. This can lead to RecursionError. See bpo-45121.
1941 if cls.__init__ is not _no_init_or_replace_init:
1942 return
1943
1944 # Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`.
1945 # The first instantiation of the subclass will call `_no_init_or_replace_init` which
1946 # searches for a proper new `__init__` in the MRO. The new `__init__`
1947 # replaces the subclass' old `__init__` (ie `_no_init_or_replace_init`). Subsequent
1948 # instantiation of the protocol subclass will thus use the new
1949 # `__init__` and no longer call `_no_init_or_replace_init`.
1950 for base in cls.__mro__:
1951 init = base.__dict__.get('__init__', _no_init_or_replace_init)
1952 if init is not _no_init_or_replace_init:
1953 cls.__init__ = init
1954 break
1955 else:
1956 # should not happen
1957 cls.__init__ = object.__init__
1958
1959 cls.__init__(self, *args, **kwargs)
1960
1961
1962 def _caller(depth=1, default='__main__'):
1963 try:
1964 return sys._getframe(depth + 1).f_globals.get('__name__', default)
1965 except (AttributeError, ValueError): # For platforms without _getframe()
1966 return None
1967
1968
1969 def _allow_reckless_class_checks(depth=3):
1970 """Allow instance and class checks for special stdlib modules.
1971
1972 The abc and functools modules indiscriminately call isinstance() and
1973 issubclass() on the whole MRO of a user class, which may contain protocols.
1974 """
1975 return _caller(depth) in {'abc', 'functools', None}
1976
1977
1978 _PROTO_ALLOWLIST = {
1979 'collections.abc': [
1980 'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable',
1981 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible',
1982 ],
1983 'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'],
1984 }
1985
1986
1987 class ESC[4;38;5;81m_ProtocolMeta(ESC[4;38;5;149mABCMeta):
1988 # This metaclass is really unfortunate and exists only because of
1989 # the lack of __instancehook__.
1990 def __instancecheck__(cls, instance):
1991 # We need this method for situations where attributes are
1992 # assigned in __init__.
1993 if (
1994 getattr(cls, '_is_protocol', False) and
1995 not getattr(cls, '_is_runtime_protocol', False) and
1996 not _allow_reckless_class_checks(depth=2)
1997 ):
1998 raise TypeError("Instance and class checks can only be used with"
1999 " @runtime_checkable protocols")
2000
2001 if ((not getattr(cls, '_is_protocol', False) or
2002 _is_callable_members_only(cls)) and
2003 issubclass(instance.__class__, cls)):
2004 return True
2005 if cls._is_protocol:
2006 if all(hasattr(instance, attr) and
2007 # All *methods* can be blocked by setting them to None.
2008 (not callable(getattr(cls, attr, None)) or
2009 getattr(instance, attr) is not None)
2010 for attr in _get_protocol_attrs(cls)):
2011 return True
2012 return super().__instancecheck__(instance)
2013
2014
2015 class ESC[4;38;5;81mProtocol(ESC[4;38;5;149mGeneric, metaclass=ESC[4;38;5;149m_ProtocolMeta):
2016 """Base class for protocol classes.
2017
2018 Protocol classes are defined as::
2019
2020 class Proto(Protocol):
2021 def meth(self) -> int:
2022 ...
2023
2024 Such classes are primarily used with static type checkers that recognize
2025 structural subtyping (static duck-typing).
2026
2027 For example::
2028
2029 class C:
2030 def meth(self) -> int:
2031 return 0
2032
2033 def func(x: Proto) -> int:
2034 return x.meth()
2035
2036 func(C()) # Passes static type check
2037
2038 See PEP 544 for details. Protocol classes decorated with
2039 @typing.runtime_checkable act as simple-minded runtime protocols that check
2040 only the presence of given attributes, ignoring their type signatures.
2041 Protocol classes can be generic, they are defined as::
2042
2043 class GenProto(Protocol[T]):
2044 def meth(self) -> T:
2045 ...
2046 """
2047
2048 __slots__ = ()
2049 _is_protocol = True
2050 _is_runtime_protocol = False
2051
2052 def __init_subclass__(cls, *args, **kwargs):
2053 super().__init_subclass__(*args, **kwargs)
2054
2055 # Determine if this is a protocol or a concrete subclass.
2056 if not cls.__dict__.get('_is_protocol', False):
2057 cls._is_protocol = any(b is Protocol for b in cls.__bases__)
2058
2059 # Set (or override) the protocol subclass hook.
2060 def _proto_hook(other):
2061 if not cls.__dict__.get('_is_protocol', False):
2062 return NotImplemented
2063
2064 # First, perform various sanity checks.
2065 if not getattr(cls, '_is_runtime_protocol', False):
2066 if _allow_reckless_class_checks():
2067 return NotImplemented
2068 raise TypeError("Instance and class checks can only be used with"
2069 " @runtime_checkable protocols")
2070 if not _is_callable_members_only(cls):
2071 if _allow_reckless_class_checks():
2072 return NotImplemented
2073 raise TypeError("Protocols with non-method members"
2074 " don't support issubclass()")
2075 if not isinstance(other, type):
2076 # Same error message as for issubclass(1, int).
2077 raise TypeError('issubclass() arg 1 must be a class')
2078
2079 # Second, perform the actual structural compatibility check.
2080 for attr in _get_protocol_attrs(cls):
2081 for base in other.__mro__:
2082 # Check if the members appears in the class dictionary...
2083 if attr in base.__dict__:
2084 if base.__dict__[attr] is None:
2085 return NotImplemented
2086 break
2087
2088 # ...or in annotations, if it is a sub-protocol.
2089 annotations = getattr(base, '__annotations__', {})
2090 if (isinstance(annotations, collections.abc.Mapping) and
2091 attr in annotations and
2092 issubclass(other, Generic) and other._is_protocol):
2093 break
2094 else:
2095 return NotImplemented
2096 return True
2097
2098 if '__subclasshook__' not in cls.__dict__:
2099 cls.__subclasshook__ = _proto_hook
2100
2101 # We have nothing more to do for non-protocols...
2102 if not cls._is_protocol:
2103 return
2104
2105 # ... otherwise check consistency of bases, and prohibit instantiation.
2106 for base in cls.__bases__:
2107 if not (base in (object, Generic) or
2108 base.__module__ in _PROTO_ALLOWLIST and
2109 base.__name__ in _PROTO_ALLOWLIST[base.__module__] or
2110 issubclass(base, Generic) and base._is_protocol):
2111 raise TypeError('Protocols can only inherit from other'
2112 ' protocols, got %r' % base)
2113 if cls.__init__ is Protocol.__init__:
2114 cls.__init__ = _no_init_or_replace_init
2115
2116
2117 class ESC[4;38;5;81m_AnnotatedAlias(ESC[4;38;5;149m_NotIterable, ESC[4;38;5;149m_GenericAlias, _root=ESC[4;38;5;149mTrue):
2118 """Runtime representation of an annotated type.
2119
2120 At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
2121 with extra annotations. The alias behaves like a normal typing alias.
2122 Instantiating is the same as instantiating the underlying type; binding
2123 it to types is also the same.
2124
2125 The metadata itself is stored in a '__metadata__' attribute as a tuple.
2126 """
2127
2128 def __init__(self, origin, metadata):
2129 if isinstance(origin, _AnnotatedAlias):
2130 metadata = origin.__metadata__ + metadata
2131 origin = origin.__origin__
2132 super().__init__(origin, origin)
2133 self.__metadata__ = metadata
2134
2135 def copy_with(self, params):
2136 assert len(params) == 1
2137 new_type = params[0]
2138 return _AnnotatedAlias(new_type, self.__metadata__)
2139
2140 def __repr__(self):
2141 return "typing.Annotated[{}, {}]".format(
2142 _type_repr(self.__origin__),
2143 ", ".join(repr(a) for a in self.__metadata__)
2144 )
2145
2146 def __reduce__(self):
2147 return operator.getitem, (
2148 Annotated, (self.__origin__,) + self.__metadata__
2149 )
2150
2151 def __eq__(self, other):
2152 if not isinstance(other, _AnnotatedAlias):
2153 return NotImplemented
2154 return (self.__origin__ == other.__origin__
2155 and self.__metadata__ == other.__metadata__)
2156
2157 def __hash__(self):
2158 return hash((self.__origin__, self.__metadata__))
2159
2160 def __getattr__(self, attr):
2161 if attr in {'__name__', '__qualname__'}:
2162 return 'Annotated'
2163 return super().__getattr__(attr)
2164
2165
2166 class ESC[4;38;5;81mAnnotated:
2167 """Add context-specific metadata to a type.
2168
2169 Example: Annotated[int, runtime_check.Unsigned] indicates to the
2170 hypothetical runtime_check module that this type is an unsigned int.
2171 Every other consumer of this type can ignore this metadata and treat
2172 this type as int.
2173
2174 The first argument to Annotated must be a valid type.
2175
2176 Details:
2177
2178 - It's an error to call `Annotated` with less than two arguments.
2179 - Access the metadata via the ``__metadata__`` attribute::
2180
2181 assert Annotated[int, '$'].__metadata__ == ('$',)
2182
2183 - Nested Annotated types are flattened::
2184
2185 assert Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
2186
2187 - Instantiating an annotated type is equivalent to instantiating the
2188 underlying type::
2189
2190 assert Annotated[C, Ann1](5) == C(5)
2191
2192 - Annotated can be used as a generic type alias::
2193
2194 Optimized: TypeAlias = Annotated[T, runtime.Optimize()]
2195 assert Optimized[int] == Annotated[int, runtime.Optimize()]
2196
2197 OptimizedList: TypeAlias = Annotated[list[T], runtime.Optimize()]
2198 assert OptimizedList[int] == Annotated[list[int], runtime.Optimize()]
2199
2200 - Annotated cannot be used with an unpacked TypeVarTuple::
2201
2202 Variadic: TypeAlias = Annotated[*Ts, Ann1] # NOT valid
2203
2204 This would be equivalent to::
2205
2206 Annotated[T1, T2, T3, ..., Ann1]
2207
2208 where T1, T2 etc. are TypeVars, which would be invalid, because
2209 only one type should be passed to Annotated.
2210 """
2211
2212 __slots__ = ()
2213
2214 def __new__(cls, *args, **kwargs):
2215 raise TypeError("Type Annotated cannot be instantiated.")
2216
2217 def __class_getitem__(cls, params):
2218 if not isinstance(params, tuple):
2219 params = (params,)
2220 return cls._class_getitem_inner(cls, *params)
2221
2222 @_tp_cache(typed=True)
2223 def _class_getitem_inner(cls, *params):
2224 if len(params) < 2:
2225 raise TypeError("Annotated[...] should be used "
2226 "with at least two arguments (a type and an "
2227 "annotation).")
2228 if _is_unpacked_typevartuple(params[0]):
2229 raise TypeError("Annotated[...] should not be used with an "
2230 "unpacked TypeVarTuple")
2231 msg = "Annotated[t, ...]: t must be a type."
2232 origin = _type_check(params[0], msg, allow_special_forms=True)
2233 metadata = tuple(params[1:])
2234 return _AnnotatedAlias(origin, metadata)
2235
2236 def __init_subclass__(cls, *args, **kwargs):
2237 raise TypeError(
2238 "Cannot subclass {}.Annotated".format(cls.__module__)
2239 )
2240
2241
2242 def runtime_checkable(cls):
2243 """Mark a protocol class as a runtime protocol.
2244
2245 Such protocol can be used with isinstance() and issubclass().
2246 Raise TypeError if applied to a non-protocol class.
2247 This allows a simple-minded structural check very similar to
2248 one trick ponies in collections.abc such as Iterable.
2249
2250 For example::
2251
2252 @runtime_checkable
2253 class Closable(Protocol):
2254 def close(self): ...
2255
2256 assert isinstance(open('/some/file'), Closable)
2257
2258 Warning: this will check only the presence of the required methods,
2259 not their type signatures!
2260 """
2261 if not issubclass(cls, Generic) or not cls._is_protocol:
2262 raise TypeError('@runtime_checkable can be only applied to protocol classes,'
2263 ' got %r' % cls)
2264 cls._is_runtime_protocol = True
2265 return cls
2266
2267
2268 def cast(typ, val):
2269 """Cast a value to a type.
2270
2271 This returns the value unchanged. To the type checker this
2272 signals that the return value has the designated type, but at
2273 runtime we intentionally don't check anything (we want this
2274 to be as fast as possible).
2275 """
2276 return val
2277
2278
2279 def assert_type(val, typ, /):
2280 """Ask a static type checker to confirm that the value is of the given type.
2281
2282 At runtime this does nothing: it returns the first argument unchanged with no
2283 checks or side effects, no matter the actual type of the argument.
2284
2285 When a static type checker encounters a call to assert_type(), it
2286 emits an error if the value is not of the specified type::
2287
2288 def greet(name: str) -> None:
2289 assert_type(name, str) # OK
2290 assert_type(name, int) # type checker error
2291 """
2292 return val
2293
2294
2295 _allowed_types = (types.FunctionType, types.BuiltinFunctionType,
2296 types.MethodType, types.ModuleType,
2297 WrapperDescriptorType, MethodWrapperType, MethodDescriptorType)
2298
2299
2300 def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
2301 """Return type hints for an object.
2302
2303 This is often the same as obj.__annotations__, but it handles
2304 forward references encoded as string literals and recursively replaces all
2305 'Annotated[T, ...]' with 'T' (unless 'include_extras=True').
2306
2307 The argument may be a module, class, method, or function. The annotations
2308 are returned as a dictionary. For classes, annotations include also
2309 inherited members.
2310
2311 TypeError is raised if the argument is not of a type that can contain
2312 annotations, and an empty dictionary is returned if no annotations are
2313 present.
2314
2315 BEWARE -- the behavior of globalns and localns is counterintuitive
2316 (unless you are familiar with how eval() and exec() work). The
2317 search order is locals first, then globals.
2318
2319 - If no dict arguments are passed, an attempt is made to use the
2320 globals from obj (or the respective module's globals for classes),
2321 and these are also used as the locals. If the object does not appear
2322 to have globals, an empty dictionary is used. For classes, the search
2323 order is globals first then locals.
2324
2325 - If one dict argument is passed, it is used for both globals and
2326 locals.
2327
2328 - If two dict arguments are passed, they specify globals and
2329 locals, respectively.
2330 """
2331 if getattr(obj, '__no_type_check__', None):
2332 return {}
2333 # Classes require a special treatment.
2334 if isinstance(obj, type):
2335 hints = {}
2336 for base in reversed(obj.__mro__):
2337 if globalns is None:
2338 base_globals = getattr(sys.modules.get(base.__module__, None), '__dict__', {})
2339 else:
2340 base_globals = globalns
2341 ann = base.__dict__.get('__annotations__', {})
2342 if isinstance(ann, types.GetSetDescriptorType):
2343 ann = {}
2344 base_locals = dict(vars(base)) if localns is None else localns
2345 if localns is None and globalns is None:
2346 # This is surprising, but required. Before Python 3.10,
2347 # get_type_hints only evaluated the globalns of
2348 # a class. To maintain backwards compatibility, we reverse
2349 # the globalns and localns order so that eval() looks into
2350 # *base_globals* first rather than *base_locals*.
2351 # This only affects ForwardRefs.
2352 base_globals, base_locals = base_locals, base_globals
2353 for name, value in ann.items():
2354 if value is None:
2355 value = type(None)
2356 if isinstance(value, str):
2357 value = ForwardRef(value, is_argument=False, is_class=True)
2358 value = _eval_type(value, base_globals, base_locals)
2359 hints[name] = value
2360 return hints if include_extras else {k: _strip_annotations(t) for k, t in hints.items()}
2361
2362 if globalns is None:
2363 if isinstance(obj, types.ModuleType):
2364 globalns = obj.__dict__
2365 else:
2366 nsobj = obj
2367 # Find globalns for the unwrapped object.
2368 while hasattr(nsobj, '__wrapped__'):
2369 nsobj = nsobj.__wrapped__
2370 globalns = getattr(nsobj, '__globals__', {})
2371 if localns is None:
2372 localns = globalns
2373 elif localns is None:
2374 localns = globalns
2375 hints = getattr(obj, '__annotations__', None)
2376 if hints is None:
2377 # Return empty annotations for something that _could_ have them.
2378 if isinstance(obj, _allowed_types):
2379 return {}
2380 else:
2381 raise TypeError('{!r} is not a module, class, method, '
2382 'or function.'.format(obj))
2383 hints = dict(hints)
2384 for name, value in hints.items():
2385 if value is None:
2386 value = type(None)
2387 if isinstance(value, str):
2388 # class-level forward refs were handled above, this must be either
2389 # a module-level annotation or a function argument annotation
2390 value = ForwardRef(
2391 value,
2392 is_argument=not isinstance(obj, types.ModuleType),
2393 is_class=False,
2394 )
2395 hints[name] = _eval_type(value, globalns, localns)
2396 return hints if include_extras else {k: _strip_annotations(t) for k, t in hints.items()}
2397
2398
2399 def _strip_annotations(t):
2400 """Strip the annotations from a given type."""
2401 if isinstance(t, _AnnotatedAlias):
2402 return _strip_annotations(t.__origin__)
2403 if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired):
2404 return _strip_annotations(t.__args__[0])
2405 if isinstance(t, _GenericAlias):
2406 stripped_args = tuple(_strip_annotations(a) for a in t.__args__)
2407 if stripped_args == t.__args__:
2408 return t
2409 return t.copy_with(stripped_args)
2410 if isinstance(t, GenericAlias):
2411 stripped_args = tuple(_strip_annotations(a) for a in t.__args__)
2412 if stripped_args == t.__args__:
2413 return t
2414 return GenericAlias(t.__origin__, stripped_args)
2415 if isinstance(t, types.UnionType):
2416 stripped_args = tuple(_strip_annotations(a) for a in t.__args__)
2417 if stripped_args == t.__args__:
2418 return t
2419 return functools.reduce(operator.or_, stripped_args)
2420
2421 return t
2422
2423
2424 def get_origin(tp):
2425 """Get the unsubscripted version of a type.
2426
2427 This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar,
2428 Annotated, and others. Return None for unsupported types.
2429
2430 Examples::
2431
2432 >>> P = ParamSpec('P')
2433 >>> assert get_origin(Literal[42]) is Literal
2434 >>> assert get_origin(int) is None
2435 >>> assert get_origin(ClassVar[int]) is ClassVar
2436 >>> assert get_origin(Generic) is Generic
2437 >>> assert get_origin(Generic[T]) is Generic
2438 >>> assert get_origin(Union[T, int]) is Union
2439 >>> assert get_origin(List[Tuple[T, T]][int]) is list
2440 >>> assert get_origin(P.args) is P
2441 """
2442 if isinstance(tp, _AnnotatedAlias):
2443 return Annotated
2444 if isinstance(tp, (_BaseGenericAlias, GenericAlias,
2445 ParamSpecArgs, ParamSpecKwargs)):
2446 return tp.__origin__
2447 if tp is Generic:
2448 return Generic
2449 if isinstance(tp, types.UnionType):
2450 return types.UnionType
2451 return None
2452
2453
2454 def get_args(tp):
2455 """Get type arguments with all substitutions performed.
2456
2457 For unions, basic simplifications used by Union constructor are performed.
2458
2459 Examples::
2460
2461 >>> T = TypeVar('T')
2462 >>> assert get_args(Dict[str, int]) == (str, int)
2463 >>> assert get_args(int) == ()
2464 >>> assert get_args(Union[int, Union[T, int], str][int]) == (int, str)
2465 >>> assert get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
2466 >>> assert get_args(Callable[[], T][int]) == ([], int)
2467 """
2468 if isinstance(tp, _AnnotatedAlias):
2469 return (tp.__origin__,) + tp.__metadata__
2470 if isinstance(tp, (_GenericAlias, GenericAlias)):
2471 res = tp.__args__
2472 if _should_unflatten_callable_args(tp, res):
2473 res = (list(res[:-1]), res[-1])
2474 return res
2475 if isinstance(tp, types.UnionType):
2476 return tp.__args__
2477 return ()
2478
2479
2480 def is_typeddict(tp):
2481 """Check if an annotation is a TypedDict class.
2482
2483 For example::
2484
2485 >>> from typing import TypedDict
2486 >>> class Film(TypedDict):
2487 ... title: str
2488 ... year: int
2489 ...
2490 >>> is_typeddict(Film)
2491 True
2492 >>> is_typeddict(dict)
2493 False
2494 """
2495 return isinstance(tp, _TypedDictMeta)
2496
2497
2498 _ASSERT_NEVER_REPR_MAX_LENGTH = 100
2499
2500
2501 def assert_never(arg: Never, /) -> Never:
2502 """Statically assert that a line of code is unreachable.
2503
2504 Example::
2505
2506 def int_or_str(arg: int | str) -> None:
2507 match arg:
2508 case int():
2509 print("It's an int")
2510 case str():
2511 print("It's a str")
2512 case _:
2513 assert_never(arg)
2514
2515 If a type checker finds that a call to assert_never() is
2516 reachable, it will emit an error.
2517
2518 At runtime, this throws an exception when called.
2519 """
2520 value = repr(arg)
2521 if len(value) > _ASSERT_NEVER_REPR_MAX_LENGTH:
2522 value = value[:_ASSERT_NEVER_REPR_MAX_LENGTH] + '...'
2523 raise AssertionError(f"Expected code to be unreachable, but got: {value}")
2524
2525
2526 def no_type_check(arg):
2527 """Decorator to indicate that annotations are not type hints.
2528
2529 The argument must be a class or function; if it is a class, it
2530 applies recursively to all methods and classes defined in that class
2531 (but not to methods defined in its superclasses or subclasses).
2532
2533 This mutates the function(s) or class(es) in place.
2534 """
2535 if isinstance(arg, type):
2536 for key in dir(arg):
2537 obj = getattr(arg, key)
2538 if (
2539 not hasattr(obj, '__qualname__')
2540 or obj.__qualname__ != f'{arg.__qualname__}.{obj.__name__}'
2541 or getattr(obj, '__module__', None) != arg.__module__
2542 ):
2543 # We only modify objects that are defined in this type directly.
2544 # If classes / methods are nested in multiple layers,
2545 # we will modify them when processing their direct holders.
2546 continue
2547 # Instance, class, and static methods:
2548 if isinstance(obj, types.FunctionType):
2549 obj.__no_type_check__ = True
2550 if isinstance(obj, types.MethodType):
2551 obj.__func__.__no_type_check__ = True
2552 # Nested types:
2553 if isinstance(obj, type):
2554 no_type_check(obj)
2555 try:
2556 arg.__no_type_check__ = True
2557 except TypeError: # built-in classes
2558 pass
2559 return arg
2560
2561
2562 def no_type_check_decorator(decorator):
2563 """Decorator to give another decorator the @no_type_check effect.
2564
2565 This wraps the decorator with something that wraps the decorated
2566 function in @no_type_check.
2567 """
2568 @functools.wraps(decorator)
2569 def wrapped_decorator(*args, **kwds):
2570 func = decorator(*args, **kwds)
2571 func = no_type_check(func)
2572 return func
2573
2574 return wrapped_decorator
2575
2576
2577 def _overload_dummy(*args, **kwds):
2578 """Helper for @overload to raise when called."""
2579 raise NotImplementedError(
2580 "You should not call an overloaded function. "
2581 "A series of @overload-decorated functions "
2582 "outside a stub module should always be followed "
2583 "by an implementation that is not @overload-ed.")
2584
2585
2586 # {module: {qualname: {firstlineno: func}}}
2587 _overload_registry = defaultdict(functools.partial(defaultdict, dict))
2588
2589
2590 def overload(func):
2591 """Decorator for overloaded functions/methods.
2592
2593 In a stub file, place two or more stub definitions for the same
2594 function in a row, each decorated with @overload.
2595
2596 For example::
2597
2598 @overload
2599 def utf8(value: None) -> None: ...
2600 @overload
2601 def utf8(value: bytes) -> bytes: ...
2602 @overload
2603 def utf8(value: str) -> bytes: ...
2604
2605 In a non-stub file (i.e. a regular .py file), do the same but
2606 follow it with an implementation. The implementation should *not*
2607 be decorated with @overload::
2608
2609 @overload
2610 def utf8(value: None) -> None: ...
2611 @overload
2612 def utf8(value: bytes) -> bytes: ...
2613 @overload
2614 def utf8(value: str) -> bytes: ...
2615 def utf8(value):
2616 ... # implementation goes here
2617
2618 The overloads for a function can be retrieved at runtime using the
2619 get_overloads() function.
2620 """
2621 # classmethod and staticmethod
2622 f = getattr(func, "__func__", func)
2623 try:
2624 _overload_registry[f.__module__][f.__qualname__][f.__code__.co_firstlineno] = func
2625 except AttributeError:
2626 # Not a normal function; ignore.
2627 pass
2628 return _overload_dummy
2629
2630
2631 def get_overloads(func):
2632 """Return all defined overloads for *func* as a sequence."""
2633 # classmethod and staticmethod
2634 f = getattr(func, "__func__", func)
2635 if f.__module__ not in _overload_registry:
2636 return []
2637 mod_dict = _overload_registry[f.__module__]
2638 if f.__qualname__ not in mod_dict:
2639 return []
2640 return list(mod_dict[f.__qualname__].values())
2641
2642
2643 def clear_overloads():
2644 """Clear all overloads in the registry."""
2645 _overload_registry.clear()
2646
2647
2648 def final(f):
2649 """Decorator to indicate final methods and final classes.
2650
2651 Use this decorator to indicate to type checkers that the decorated
2652 method cannot be overridden, and decorated class cannot be subclassed.
2653
2654 For example::
2655
2656 class Base:
2657 @final
2658 def done(self) -> None:
2659 ...
2660 class Sub(Base):
2661 def done(self) -> None: # Error reported by type checker
2662 ...
2663
2664 @final
2665 class Leaf:
2666 ...
2667 class Other(Leaf): # Error reported by type checker
2668 ...
2669
2670 There is no runtime checking of these properties. The decorator
2671 attempts to set the ``__final__`` attribute to ``True`` on the decorated
2672 object to allow runtime introspection.
2673 """
2674 try:
2675 f.__final__ = True
2676 except (AttributeError, TypeError):
2677 # Skip the attribute silently if it is not writable.
2678 # AttributeError happens if the object has __slots__ or a
2679 # read-only property, TypeError if it's a builtin class.
2680 pass
2681 return f
2682
2683
2684 # Some unconstrained type variables. These are used by the container types.
2685 # (These are not for export.)
2686 T = TypeVar('T') # Any type.
2687 KT = TypeVar('KT') # Key type.
2688 VT = TypeVar('VT') # Value type.
2689 T_co = TypeVar('T_co', covariant=True) # Any type covariant containers.
2690 V_co = TypeVar('V_co', covariant=True) # Any type covariant containers.
2691 VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
2692 T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
2693 # Internal type variable used for Type[].
2694 CT_co = TypeVar('CT_co', covariant=True, bound=type)
2695
2696 # A useful type variable with constraints. This represents string types.
2697 # (This one *is* for export!)
2698 AnyStr = TypeVar('AnyStr', bytes, str)
2699
2700
2701 # Various ABCs mimicking those in collections.abc.
2702 _alias = _SpecialGenericAlias
2703
2704 Hashable = _alias(collections.abc.Hashable, 0) # Not generic.
2705 Awaitable = _alias(collections.abc.Awaitable, 1)
2706 Coroutine = _alias(collections.abc.Coroutine, 3)
2707 AsyncIterable = _alias(collections.abc.AsyncIterable, 1)
2708 AsyncIterator = _alias(collections.abc.AsyncIterator, 1)
2709 Iterable = _alias(collections.abc.Iterable, 1)
2710 Iterator = _alias(collections.abc.Iterator, 1)
2711 Reversible = _alias(collections.abc.Reversible, 1)
2712 Sized = _alias(collections.abc.Sized, 0) # Not generic.
2713 Container = _alias(collections.abc.Container, 1)
2714 Collection = _alias(collections.abc.Collection, 1)
2715 Callable = _CallableType(collections.abc.Callable, 2)
2716 Callable.__doc__ = \
2717 """Deprecated alias to collections.abc.Callable.
2718
2719 Callable[[int], str] signifies a function that takes a single
2720 parameter of type int and returns a str.
2721
2722 The subscription syntax must always be used with exactly two
2723 values: the argument list and the return type.
2724 The argument list must be a list of types, a ParamSpec,
2725 Concatenate or ellipsis. The return type must be a single type.
2726
2727 There is no syntax to indicate optional or keyword arguments;
2728 such function types are rarely used as callback types.
2729 """
2730 AbstractSet = _alias(collections.abc.Set, 1, name='AbstractSet')
2731 MutableSet = _alias(collections.abc.MutableSet, 1)
2732 # NOTE: Mapping is only covariant in the value type.
2733 Mapping = _alias(collections.abc.Mapping, 2)
2734 MutableMapping = _alias(collections.abc.MutableMapping, 2)
2735 Sequence = _alias(collections.abc.Sequence, 1)
2736 MutableSequence = _alias(collections.abc.MutableSequence, 1)
2737 ByteString = _alias(collections.abc.ByteString, 0) # Not generic
2738 # Tuple accepts variable number of parameters.
2739 Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
2740 Tuple.__doc__ = \
2741 """Deprecated alias to builtins.tuple.
2742
2743 Tuple[X, Y] is the cross-product type of X and Y.
2744
2745 Example: Tuple[T1, T2] is a tuple of two elements corresponding
2746 to type variables T1 and T2. Tuple[int, float, str] is a tuple
2747 of an int, a float and a string.
2748
2749 To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
2750 """
2751 List = _alias(list, 1, inst=False, name='List')
2752 Deque = _alias(collections.deque, 1, name='Deque')
2753 Set = _alias(set, 1, inst=False, name='Set')
2754 FrozenSet = _alias(frozenset, 1, inst=False, name='FrozenSet')
2755 MappingView = _alias(collections.abc.MappingView, 1)
2756 KeysView = _alias(collections.abc.KeysView, 1)
2757 ItemsView = _alias(collections.abc.ItemsView, 2)
2758 ValuesView = _alias(collections.abc.ValuesView, 1)
2759 ContextManager = _alias(contextlib.AbstractContextManager, 1, name='ContextManager')
2760 AsyncContextManager = _alias(contextlib.AbstractAsyncContextManager, 1, name='AsyncContextManager')
2761 Dict = _alias(dict, 2, inst=False, name='Dict')
2762 DefaultDict = _alias(collections.defaultdict, 2, name='DefaultDict')
2763 OrderedDict = _alias(collections.OrderedDict, 2)
2764 Counter = _alias(collections.Counter, 1)
2765 ChainMap = _alias(collections.ChainMap, 2)
2766 Generator = _alias(collections.abc.Generator, 3)
2767 AsyncGenerator = _alias(collections.abc.AsyncGenerator, 2)
2768 Type = _alias(type, 1, inst=False, name='Type')
2769 Type.__doc__ = \
2770 """Deprecated alias to builtins.type.
2771
2772 builtins.type or typing.Type can be used to annotate class objects.
2773 For example, suppose we have the following classes::
2774
2775 class User: ... # Abstract base for User classes
2776 class BasicUser(User): ...
2777 class ProUser(User): ...
2778 class TeamUser(User): ...
2779
2780 And a function that takes a class argument that's a subclass of
2781 User and returns an instance of the corresponding class::
2782
2783 U = TypeVar('U', bound=User)
2784 def new_user(user_class: Type[U]) -> U:
2785 user = user_class()
2786 # (Here we could write the user object to a database)
2787 return user
2788
2789 joe = new_user(BasicUser)
2790
2791 At this point the type checker knows that joe has type BasicUser.
2792 """
2793
2794
2795 @runtime_checkable
2796 class ESC[4;38;5;81mSupportsInt(ESC[4;38;5;149mProtocol):
2797 """An ABC with one abstract method __int__."""
2798
2799 __slots__ = ()
2800
2801 @abstractmethod
2802 def __int__(self) -> int:
2803 pass
2804
2805
2806 @runtime_checkable
2807 class ESC[4;38;5;81mSupportsFloat(ESC[4;38;5;149mProtocol):
2808 """An ABC with one abstract method __float__."""
2809
2810 __slots__ = ()
2811
2812 @abstractmethod
2813 def __float__(self) -> float:
2814 pass
2815
2816
2817 @runtime_checkable
2818 class ESC[4;38;5;81mSupportsComplex(ESC[4;38;5;149mProtocol):
2819 """An ABC with one abstract method __complex__."""
2820
2821 __slots__ = ()
2822
2823 @abstractmethod
2824 def __complex__(self) -> complex:
2825 pass
2826
2827
2828 @runtime_checkable
2829 class ESC[4;38;5;81mSupportsBytes(ESC[4;38;5;149mProtocol):
2830 """An ABC with one abstract method __bytes__."""
2831
2832 __slots__ = ()
2833
2834 @abstractmethod
2835 def __bytes__(self) -> bytes:
2836 pass
2837
2838
2839 @runtime_checkable
2840 class ESC[4;38;5;81mSupportsIndex(ESC[4;38;5;149mProtocol):
2841 """An ABC with one abstract method __index__."""
2842
2843 __slots__ = ()
2844
2845 @abstractmethod
2846 def __index__(self) -> int:
2847 pass
2848
2849
2850 @runtime_checkable
2851 class ESC[4;38;5;81mSupportsAbs(ESC[4;38;5;149mProtocol[T_co]):
2852 """An ABC with one abstract method __abs__ that is covariant in its return type."""
2853
2854 __slots__ = ()
2855
2856 @abstractmethod
2857 def __abs__(self) -> T_co:
2858 pass
2859
2860
2861 @runtime_checkable
2862 class ESC[4;38;5;81mSupportsRound(ESC[4;38;5;149mProtocol[T_co]):
2863 """An ABC with one abstract method __round__ that is covariant in its return type."""
2864
2865 __slots__ = ()
2866
2867 @abstractmethod
2868 def __round__(self, ndigits: int = 0) -> T_co:
2869 pass
2870
2871
2872 def _make_nmtuple(name, types, module, defaults = ()):
2873 fields = [n for n, t in types]
2874 types = {n: _type_check(t, f"field {n} annotation must be a type")
2875 for n, t in types}
2876 nm_tpl = collections.namedtuple(name, fields,
2877 defaults=defaults, module=module)
2878 nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = types
2879 return nm_tpl
2880
2881
2882 # attributes prohibited to set in NamedTuple class syntax
2883 _prohibited = frozenset({'__new__', '__init__', '__slots__', '__getnewargs__',
2884 '_fields', '_field_defaults',
2885 '_make', '_replace', '_asdict', '_source'})
2886
2887 _special = frozenset({'__module__', '__name__', '__annotations__'})
2888
2889
2890 class ESC[4;38;5;81mNamedTupleMeta(ESC[4;38;5;149mtype):
2891 def __new__(cls, typename, bases, ns):
2892 assert _NamedTuple in bases
2893 for base in bases:
2894 if base is not _NamedTuple and base is not Generic:
2895 raise TypeError(
2896 'can only inherit from a NamedTuple type and Generic')
2897 bases = tuple(tuple if base is _NamedTuple else base for base in bases)
2898 types = ns.get('__annotations__', {})
2899 default_names = []
2900 for field_name in types:
2901 if field_name in ns:
2902 default_names.append(field_name)
2903 elif default_names:
2904 raise TypeError(f"Non-default namedtuple field {field_name} "
2905 f"cannot follow default field"
2906 f"{'s' if len(default_names) > 1 else ''} "
2907 f"{', '.join(default_names)}")
2908 nm_tpl = _make_nmtuple(typename, types.items(),
2909 defaults=[ns[n] for n in default_names],
2910 module=ns['__module__'])
2911 nm_tpl.__bases__ = bases
2912 if Generic in bases:
2913 class_getitem = Generic.__class_getitem__.__func__
2914 nm_tpl.__class_getitem__ = classmethod(class_getitem)
2915 # update from user namespace without overriding special namedtuple attributes
2916 for key in ns:
2917 if key in _prohibited:
2918 raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
2919 elif key not in _special and key not in nm_tpl._fields:
2920 setattr(nm_tpl, key, ns[key])
2921 if Generic in bases:
2922 nm_tpl.__init_subclass__()
2923 return nm_tpl
2924
2925
2926 def NamedTuple(typename, fields=None, /, **kwargs):
2927 """Typed version of namedtuple.
2928
2929 Usage::
2930
2931 class Employee(NamedTuple):
2932 name: str
2933 id: int
2934
2935 This is equivalent to::
2936
2937 Employee = collections.namedtuple('Employee', ['name', 'id'])
2938
2939 The resulting class has an extra __annotations__ attribute, giving a
2940 dict that maps field names to types. (The field names are also in
2941 the _fields attribute, which is part of the namedtuple API.)
2942 An alternative equivalent functional syntax is also accepted::
2943
2944 Employee = NamedTuple('Employee', [('name', str), ('id', int)])
2945 """
2946 if fields is None:
2947 fields = kwargs.items()
2948 elif kwargs:
2949 raise TypeError("Either list of fields or keywords"
2950 " can be provided to NamedTuple, not both")
2951 return _make_nmtuple(typename, fields, module=_caller())
2952
2953 _NamedTuple = type.__new__(NamedTupleMeta, 'NamedTuple', (), {})
2954
2955 def _namedtuple_mro_entries(bases):
2956 assert NamedTuple in bases
2957 return (_NamedTuple,)
2958
2959 NamedTuple.__mro_entries__ = _namedtuple_mro_entries
2960
2961
2962 class ESC[4;38;5;81m_TypedDictMeta(ESC[4;38;5;149mtype):
2963 def __new__(cls, name, bases, ns, total=True):
2964 """Create a new typed dict class object.
2965
2966 This method is called when TypedDict is subclassed,
2967 or when TypedDict is instantiated. This way
2968 TypedDict supports all three syntax forms described in its docstring.
2969 Subclasses and instances of TypedDict return actual dictionaries.
2970 """
2971 for base in bases:
2972 if type(base) is not _TypedDictMeta and base is not Generic:
2973 raise TypeError('cannot inherit from both a TypedDict type '
2974 'and a non-TypedDict base class')
2975
2976 if any(issubclass(b, Generic) for b in bases):
2977 generic_base = (Generic,)
2978 else:
2979 generic_base = ()
2980
2981 tp_dict = type.__new__(_TypedDictMeta, name, (*generic_base, dict), ns)
2982
2983 annotations = {}
2984 own_annotations = ns.get('__annotations__', {})
2985 msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
2986 own_annotations = {
2987 n: _type_check(tp, msg, module=tp_dict.__module__)
2988 for n, tp in own_annotations.items()
2989 }
2990 required_keys = set()
2991 optional_keys = set()
2992
2993 for base in bases:
2994 annotations.update(base.__dict__.get('__annotations__', {}))
2995
2996 base_required = base.__dict__.get('__required_keys__', set())
2997 required_keys |= base_required
2998 optional_keys -= base_required
2999
3000 base_optional = base.__dict__.get('__optional_keys__', set())
3001 required_keys -= base_optional
3002 optional_keys |= base_optional
3003
3004 annotations.update(own_annotations)
3005 for annotation_key, annotation_type in own_annotations.items():
3006 annotation_origin = get_origin(annotation_type)
3007 if annotation_origin is Annotated:
3008 annotation_args = get_args(annotation_type)
3009 if annotation_args:
3010 annotation_type = annotation_args[0]
3011 annotation_origin = get_origin(annotation_type)
3012
3013 if annotation_origin is Required:
3014 is_required = True
3015 elif annotation_origin is NotRequired:
3016 is_required = False
3017 else:
3018 is_required = total
3019
3020 if is_required:
3021 required_keys.add(annotation_key)
3022 optional_keys.discard(annotation_key)
3023 else:
3024 optional_keys.add(annotation_key)
3025 required_keys.discard(annotation_key)
3026
3027 assert required_keys.isdisjoint(optional_keys), (
3028 f"Required keys overlap with optional keys in {name}:"
3029 f" {required_keys=}, {optional_keys=}"
3030 )
3031 tp_dict.__annotations__ = annotations
3032 tp_dict.__required_keys__ = frozenset(required_keys)
3033 tp_dict.__optional_keys__ = frozenset(optional_keys)
3034 if not hasattr(tp_dict, '__total__'):
3035 tp_dict.__total__ = total
3036 return tp_dict
3037
3038 __call__ = dict # static method
3039
3040 def __subclasscheck__(cls, other):
3041 # Typed dicts are only for static structural subtyping.
3042 raise TypeError('TypedDict does not support instance and class checks')
3043
3044 __instancecheck__ = __subclasscheck__
3045
3046
3047 def TypedDict(typename, fields=None, /, *, total=True, **kwargs):
3048 """A simple typed namespace. At runtime it is equivalent to a plain dict.
3049
3050 TypedDict creates a dictionary type such that a type checker will expect all
3051 instances to have a certain set of keys, where each key is
3052 associated with a value of a consistent type. This expectation
3053 is not checked at runtime.
3054
3055 Usage::
3056
3057 >>> class Point2D(TypedDict):
3058 ... x: int
3059 ... y: int
3060 ... label: str
3061 ...
3062 >>> a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
3063 >>> b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
3064 >>> Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
3065 True
3066
3067 The type info can be accessed via the Point2D.__annotations__ dict, and
3068 the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
3069 TypedDict supports an additional equivalent form::
3070
3071 Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
3072
3073 By default, all keys must be present in a TypedDict. It is possible
3074 to override this by specifying totality::
3075
3076 class Point2D(TypedDict, total=False):
3077 x: int
3078 y: int
3079
3080 This means that a Point2D TypedDict can have any of the keys omitted. A type
3081 checker is only expected to support a literal False or True as the value of
3082 the total argument. True is the default, and makes all items defined in the
3083 class body be required.
3084
3085 The Required and NotRequired special forms can also be used to mark
3086 individual keys as being required or not required::
3087
3088 class Point2D(TypedDict):
3089 x: int # the "x" key must always be present (Required is the default)
3090 y: NotRequired[int] # the "y" key can be omitted
3091
3092 See PEP 655 for more details on Required and NotRequired.
3093 """
3094 if fields is None:
3095 fields = kwargs
3096 elif kwargs:
3097 raise TypeError("TypedDict takes either a dict or keyword arguments,"
3098 " but not both")
3099 if kwargs:
3100 warnings.warn(
3101 "The kwargs-based syntax for TypedDict definitions is deprecated "
3102 "in Python 3.11, will be removed in Python 3.13, and may not be "
3103 "understood by third-party type checkers.",
3104 DeprecationWarning,
3105 stacklevel=2,
3106 )
3107
3108 ns = {'__annotations__': dict(fields)}
3109 module = _caller()
3110 if module is not None:
3111 # Setting correct module is necessary to make typed dict classes pickleable.
3112 ns['__module__'] = module
3113
3114 return _TypedDictMeta(typename, (), ns, total=total)
3115
3116 _TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {})
3117 TypedDict.__mro_entries__ = lambda bases: (_TypedDict,)
3118
3119
3120 @_SpecialForm
3121 def Required(self, parameters):
3122 """Special typing construct to mark a TypedDict key as required.
3123
3124 This is mainly useful for total=False TypedDicts.
3125
3126 For example::
3127
3128 class Movie(TypedDict, total=False):
3129 title: Required[str]
3130 year: int
3131
3132 m = Movie(
3133 title='The Matrix', # typechecker error if key is omitted
3134 year=1999,
3135 )
3136
3137 There is no runtime checking that a required key is actually provided
3138 when instantiating a related TypedDict.
3139 """
3140 item = _type_check(parameters, f'{self._name} accepts only a single type.')
3141 return _GenericAlias(self, (item,))
3142
3143
3144 @_SpecialForm
3145 def NotRequired(self, parameters):
3146 """Special typing construct to mark a TypedDict key as potentially missing.
3147
3148 For example::
3149
3150 class Movie(TypedDict):
3151 title: str
3152 year: NotRequired[int]
3153
3154 m = Movie(
3155 title='The Matrix', # typechecker error if key is omitted
3156 year=1999,
3157 )
3158 """
3159 item = _type_check(parameters, f'{self._name} accepts only a single type.')
3160 return _GenericAlias(self, (item,))
3161
3162
3163 class ESC[4;38;5;81mNewType:
3164 """NewType creates simple unique types with almost zero runtime overhead.
3165
3166 NewType(name, tp) is considered a subtype of tp
3167 by static type checkers. At runtime, NewType(name, tp) returns
3168 a dummy callable that simply returns its argument.
3169
3170 Usage::
3171
3172 UserId = NewType('UserId', int)
3173
3174 def name_by_id(user_id: UserId) -> str:
3175 ...
3176
3177 UserId('user') # Fails type check
3178
3179 name_by_id(42) # Fails type check
3180 name_by_id(UserId(42)) # OK
3181
3182 num = UserId(5) + 1 # type: int
3183 """
3184
3185 __call__ = _idfunc
3186
3187 def __init__(self, name, tp):
3188 self.__qualname__ = name
3189 if '.' in name:
3190 name = name.rpartition('.')[-1]
3191 self.__name__ = name
3192 self.__supertype__ = tp
3193 def_mod = _caller()
3194 if def_mod != 'typing':
3195 self.__module__ = def_mod
3196
3197 def __mro_entries__(self, bases):
3198 # We defined __mro_entries__ to get a better error message
3199 # if a user attempts to subclass a NewType instance. bpo-46170
3200 superclass_name = self.__name__
3201
3202 class ESC[4;38;5;81mDummy:
3203 def __init_subclass__(cls):
3204 subclass_name = cls.__name__
3205 raise TypeError(
3206 f"Cannot subclass an instance of NewType. Perhaps you were looking for: "
3207 f"`{subclass_name} = NewType({subclass_name!r}, {superclass_name})`"
3208 )
3209
3210 return (Dummy,)
3211
3212 def __repr__(self):
3213 return f'{self.__module__}.{self.__qualname__}'
3214
3215 def __reduce__(self):
3216 return self.__qualname__
3217
3218 def __or__(self, other):
3219 return Union[self, other]
3220
3221 def __ror__(self, other):
3222 return Union[other, self]
3223
3224
3225 # Python-version-specific alias (Python 2: unicode; Python 3: str)
3226 Text = str
3227
3228
3229 # Constant that's True when type checking, but False here.
3230 TYPE_CHECKING = False
3231
3232
3233 class ESC[4;38;5;81mIO(ESC[4;38;5;149mGeneric[AnyStr]):
3234 """Generic base class for TextIO and BinaryIO.
3235
3236 This is an abstract, generic version of the return of open().
3237
3238 NOTE: This does not distinguish between the different possible
3239 classes (text vs. binary, read vs. write vs. read/write,
3240 append-only, unbuffered). The TextIO and BinaryIO subclasses
3241 below capture the distinctions between text vs. binary, which is
3242 pervasive in the interface; however we currently do not offer a
3243 way to track the other distinctions in the type system.
3244 """
3245
3246 __slots__ = ()
3247
3248 @property
3249 @abstractmethod
3250 def mode(self) -> str:
3251 pass
3252
3253 @property
3254 @abstractmethod
3255 def name(self) -> str:
3256 pass
3257
3258 @abstractmethod
3259 def close(self) -> None:
3260 pass
3261
3262 @property
3263 @abstractmethod
3264 def closed(self) -> bool:
3265 pass
3266
3267 @abstractmethod
3268 def fileno(self) -> int:
3269 pass
3270
3271 @abstractmethod
3272 def flush(self) -> None:
3273 pass
3274
3275 @abstractmethod
3276 def isatty(self) -> bool:
3277 pass
3278
3279 @abstractmethod
3280 def read(self, n: int = -1) -> AnyStr:
3281 pass
3282
3283 @abstractmethod
3284 def readable(self) -> bool:
3285 pass
3286
3287 @abstractmethod
3288 def readline(self, limit: int = -1) -> AnyStr:
3289 pass
3290
3291 @abstractmethod
3292 def readlines(self, hint: int = -1) -> List[AnyStr]:
3293 pass
3294
3295 @abstractmethod
3296 def seek(self, offset: int, whence: int = 0) -> int:
3297 pass
3298
3299 @abstractmethod
3300 def seekable(self) -> bool:
3301 pass
3302
3303 @abstractmethod
3304 def tell(self) -> int:
3305 pass
3306
3307 @abstractmethod
3308 def truncate(self, size: int = None) -> int:
3309 pass
3310
3311 @abstractmethod
3312 def writable(self) -> bool:
3313 pass
3314
3315 @abstractmethod
3316 def write(self, s: AnyStr) -> int:
3317 pass
3318
3319 @abstractmethod
3320 def writelines(self, lines: List[AnyStr]) -> None:
3321 pass
3322
3323 @abstractmethod
3324 def __enter__(self) -> 'IO[AnyStr]':
3325 pass
3326
3327 @abstractmethod
3328 def __exit__(self, type, value, traceback) -> None:
3329 pass
3330
3331
3332 class ESC[4;38;5;81mBinaryIO(ESC[4;38;5;149mIO[bytes]):
3333 """Typed version of the return of open() in binary mode."""
3334
3335 __slots__ = ()
3336
3337 @abstractmethod
3338 def write(self, s: Union[bytes, bytearray]) -> int:
3339 pass
3340
3341 @abstractmethod
3342 def __enter__(self) -> 'BinaryIO':
3343 pass
3344
3345
3346 class ESC[4;38;5;81mTextIO(ESC[4;38;5;149mIO[str]):
3347 """Typed version of the return of open() in text mode."""
3348
3349 __slots__ = ()
3350
3351 @property
3352 @abstractmethod
3353 def buffer(self) -> BinaryIO:
3354 pass
3355
3356 @property
3357 @abstractmethod
3358 def encoding(self) -> str:
3359 pass
3360
3361 @property
3362 @abstractmethod
3363 def errors(self) -> Optional[str]:
3364 pass
3365
3366 @property
3367 @abstractmethod
3368 def line_buffering(self) -> bool:
3369 pass
3370
3371 @property
3372 @abstractmethod
3373 def newlines(self) -> Any:
3374 pass
3375
3376 @abstractmethod
3377 def __enter__(self) -> 'TextIO':
3378 pass
3379
3380
3381 class ESC[4;38;5;81m_DeprecatedType(ESC[4;38;5;149mtype):
3382 def __getattribute__(cls, name):
3383 if name not in ("__dict__", "__module__") and name in cls.__dict__:
3384 warnings.warn(
3385 f"{cls.__name__} is deprecated, import directly "
3386 f"from typing instead. {cls.__name__} will be removed "
3387 "in Python 3.12.",
3388 DeprecationWarning,
3389 stacklevel=2,
3390 )
3391 return super().__getattribute__(name)
3392
3393
3394 class ESC[4;38;5;81mio(metaclass=ESC[4;38;5;149m_DeprecatedType):
3395 """Wrapper namespace for IO generic classes."""
3396
3397 __all__ = ['IO', 'TextIO', 'BinaryIO']
3398 IO = IO
3399 TextIO = TextIO
3400 BinaryIO = BinaryIO
3401
3402
3403 io.__name__ = __name__ + '.io'
3404 sys.modules[io.__name__] = io
3405
3406 Pattern = _alias(stdlib_re.Pattern, 1)
3407 Match = _alias(stdlib_re.Match, 1)
3408
3409 class ESC[4;38;5;81mre(metaclass=ESC[4;38;5;149m_DeprecatedType):
3410 """Wrapper namespace for re type aliases."""
3411
3412 __all__ = ['Pattern', 'Match']
3413 Pattern = Pattern
3414 Match = Match
3415
3416
3417 re.__name__ = __name__ + '.re'
3418 sys.modules[re.__name__] = re
3419
3420
3421 def reveal_type(obj: T, /) -> T:
3422 """Reveal the inferred type of a variable.
3423
3424 When a static type checker encounters a call to ``reveal_type()``,
3425 it will emit the inferred type of the argument::
3426
3427 x: int = 1
3428 reveal_type(x)
3429
3430 Running a static type checker (e.g., mypy) on this example
3431 will produce output similar to 'Revealed type is "builtins.int"'.
3432
3433 At runtime, the function prints the runtime type of the
3434 argument and returns it unchanged.
3435 """
3436 print(f"Runtime type is {type(obj).__name__!r}", file=sys.stderr)
3437 return obj
3438
3439
3440 def dataclass_transform(
3441 *,
3442 eq_default: bool = True,
3443 order_default: bool = False,
3444 kw_only_default: bool = False,
3445 field_specifiers: tuple[type[Any] | Callable[..., Any], ...] = (),
3446 **kwargs: Any,
3447 ) -> Callable[[T], T]:
3448 """Decorator to mark an object as providing dataclass-like behaviour.
3449
3450 The decorator can be applied to a function, class, or metaclass.
3451
3452 Example usage with a decorator function::
3453
3454 T = TypeVar("T")
3455
3456 @dataclass_transform()
3457 def create_model(cls: type[T]) -> type[T]:
3458 ...
3459 return cls
3460
3461 @create_model
3462 class CustomerModel:
3463 id: int
3464 name: str
3465
3466 On a base class::
3467
3468 @dataclass_transform()
3469 class ModelBase: ...
3470
3471 class CustomerModel(ModelBase):
3472 id: int
3473 name: str
3474
3475 On a metaclass::
3476
3477 @dataclass_transform()
3478 class ModelMeta(type): ...
3479
3480 class ModelBase(metaclass=ModelMeta): ...
3481
3482 class CustomerModel(ModelBase):
3483 id: int
3484 name: str
3485
3486 The ``CustomerModel`` classes defined above will
3487 be treated by type checkers similarly to classes created with
3488 ``@dataclasses.dataclass``.
3489 For example, type checkers will assume these classes have
3490 ``__init__`` methods that accept ``id`` and ``name``.
3491
3492 The arguments to this decorator can be used to customize this behavior:
3493 - ``eq_default`` indicates whether the ``eq`` parameter is assumed to be
3494 ``True`` or ``False`` if it is omitted by the caller.
3495 - ``order_default`` indicates whether the ``order`` parameter is
3496 assumed to be True or False if it is omitted by the caller.
3497 - ``kw_only_default`` indicates whether the ``kw_only`` parameter is
3498 assumed to be True or False if it is omitted by the caller.
3499 - ``field_specifiers`` specifies a static list of supported classes
3500 or functions that describe fields, similar to ``dataclasses.field()``.
3501 - Arbitrary other keyword arguments are accepted in order to allow for
3502 possible future extensions.
3503
3504 At runtime, this decorator records its arguments in the
3505 ``__dataclass_transform__`` attribute on the decorated object.
3506 It has no other runtime effect.
3507
3508 See PEP 681 for more details.
3509 """
3510 def decorator(cls_or_fn):
3511 cls_or_fn.__dataclass_transform__ = {
3512 "eq_default": eq_default,
3513 "order_default": order_default,
3514 "kw_only_default": kw_only_default,
3515 "field_specifiers": field_specifiers,
3516 "kwargs": kwargs,
3517 }
3518 return cls_or_fn
3519 return decorator