ccxt 4.3.76__py2.py3-none-any.whl → 4.3.77__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3839 +0,0 @@
1
- import abc
2
- import collections
3
- import collections.abc
4
- import contextlib
5
- import enum
6
- import functools
7
- import inspect
8
- import operator
9
- import sys
10
- import types as _types
11
- import typing
12
- import warnings
13
-
14
- __all__ = [
15
- # Super-special typing primitives.
16
- 'Any',
17
- 'ClassVar',
18
- 'Concatenate',
19
- 'Final',
20
- 'LiteralString',
21
- 'ParamSpec',
22
- 'ParamSpecArgs',
23
- 'ParamSpecKwargs',
24
- 'Self',
25
- 'Type',
26
- 'TypeVar',
27
- 'TypeVarTuple',
28
- 'Unpack',
29
-
30
- # ABCs (from collections.abc).
31
- 'Awaitable',
32
- 'AsyncIterator',
33
- 'AsyncIterable',
34
- 'Coroutine',
35
- 'AsyncGenerator',
36
- 'AsyncContextManager',
37
- 'Buffer',
38
- 'ChainMap',
39
-
40
- # Concrete collection types.
41
- 'ContextManager',
42
- 'Counter',
43
- 'Deque',
44
- 'DefaultDict',
45
- 'NamedTuple',
46
- 'OrderedDict',
47
- 'TypedDict',
48
-
49
- # Structural checks, a.k.a. protocols.
50
- 'SupportsAbs',
51
- 'SupportsBytes',
52
- 'SupportsComplex',
53
- 'SupportsFloat',
54
- 'SupportsIndex',
55
- 'SupportsInt',
56
- 'SupportsRound',
57
-
58
- # One-off things.
59
- 'Annotated',
60
- 'assert_never',
61
- 'assert_type',
62
- 'clear_overloads',
63
- 'dataclass_transform',
64
- 'deprecated',
65
- 'Doc',
66
- 'get_overloads',
67
- 'final',
68
- 'Format',
69
- 'get_annotations',
70
- 'get_args',
71
- 'get_origin',
72
- 'get_original_bases',
73
- 'get_protocol_members',
74
- 'get_type_hints',
75
- 'IntVar',
76
- 'is_protocol',
77
- 'is_typeddict',
78
- 'Literal',
79
- 'NewType',
80
- 'overload',
81
- 'override',
82
- 'Protocol',
83
- 'reveal_type',
84
- 'runtime',
85
- 'runtime_checkable',
86
- 'Text',
87
- 'TypeAlias',
88
- 'TypeAliasType',
89
- 'TypeExpr',
90
- 'TypeGuard',
91
- 'TypeIs',
92
- 'TYPE_CHECKING',
93
- 'Never',
94
- 'NoReturn',
95
- 'ReadOnly',
96
- 'Required',
97
- 'NotRequired',
98
-
99
- # Pure aliases, have always been in typing
100
- 'AbstractSet',
101
- 'AnyStr',
102
- 'BinaryIO',
103
- 'Callable',
104
- 'Collection',
105
- 'Container',
106
- 'Dict',
107
- 'ForwardRef',
108
- 'FrozenSet',
109
- 'Generator',
110
- 'Generic',
111
- 'Hashable',
112
- 'IO',
113
- 'ItemsView',
114
- 'Iterable',
115
- 'Iterator',
116
- 'KeysView',
117
- 'List',
118
- 'Mapping',
119
- 'MappingView',
120
- 'Match',
121
- 'MutableMapping',
122
- 'MutableSequence',
123
- 'MutableSet',
124
- 'NoDefault',
125
- 'Optional',
126
- 'Pattern',
127
- 'Reversible',
128
- 'Sequence',
129
- 'Set',
130
- 'Sized',
131
- 'TextIO',
132
- 'Tuple',
133
- 'Union',
134
- 'ValuesView',
135
- 'cast',
136
- 'no_type_check',
137
- 'no_type_check_decorator',
138
- ]
139
-
140
- # for backward compatibility
141
- PEP_560 = True
142
- GenericMeta = type
143
- _PEP_696_IMPLEMENTED = sys.version_info >= (3, 13, 0, "beta")
144
-
145
- # The functions below are modified copies of typing internal helpers.
146
- # They are needed by _ProtocolMeta and they provide support for PEP 646.
147
-
148
-
149
- class _Sentinel:
150
- def __repr__(self):
151
- return "<sentinel>"
152
-
153
-
154
- _marker = _Sentinel()
155
-
156
-
157
- if sys.version_info >= (3, 10):
158
- def _should_collect_from_parameters(t):
159
- return isinstance(
160
- t, (typing._GenericAlias, _types.GenericAlias, _types.UnionType)
161
- )
162
- elif sys.version_info >= (3, 9):
163
- def _should_collect_from_parameters(t):
164
- return isinstance(t, (typing._GenericAlias, _types.GenericAlias))
165
- else:
166
- def _should_collect_from_parameters(t):
167
- return isinstance(t, typing._GenericAlias) and not t._special
168
-
169
-
170
- NoReturn = typing.NoReturn
171
-
172
- # Some unconstrained type variables. These are used by the container types.
173
- # (These are not for export.)
174
- T = typing.TypeVar('T') # Any type.
175
- KT = typing.TypeVar('KT') # Key type.
176
- VT = typing.TypeVar('VT') # Value type.
177
- T_co = typing.TypeVar('T_co', covariant=True) # Any type covariant containers.
178
- T_contra = typing.TypeVar('T_contra', contravariant=True) # Ditto contravariant.
179
-
180
-
181
- if sys.version_info >= (3, 11):
182
- from typing import Any
183
- else:
184
-
185
- class _AnyMeta(type):
186
- def __instancecheck__(self, obj):
187
- if self is Any:
188
- raise TypeError("typing_extensions.Any cannot be used with isinstance()")
189
- return super().__instancecheck__(obj)
190
-
191
- def __repr__(self):
192
- if self is Any:
193
- return "typing_extensions.Any"
194
- return super().__repr__()
195
-
196
- class Any(metaclass=_AnyMeta):
197
- """Special type indicating an unconstrained type.
198
- - Any is compatible with every type.
199
- - Any assumed to have all methods.
200
- - All values assumed to be instances of Any.
201
- Note that all the above statements are true from the point of view of
202
- static type checkers. At runtime, Any should not be used with instance
203
- checks.
204
- """
205
- def __new__(cls, *args, **kwargs):
206
- if cls is Any:
207
- raise TypeError("Any cannot be instantiated")
208
- return super().__new__(cls, *args, **kwargs)
209
-
210
-
211
- ClassVar = typing.ClassVar
212
-
213
-
214
- class _ExtensionsSpecialForm(typing._SpecialForm, _root=True):
215
- def __repr__(self):
216
- return 'typing_extensions.' + self._name
217
-
218
-
219
- Final = typing.Final
220
-
221
- if sys.version_info >= (3, 11):
222
- final = typing.final
223
- else:
224
- # @final exists in 3.8+, but we backport it for all versions
225
- # before 3.11 to keep support for the __final__ attribute.
226
- # See https://bugs.python.org/issue46342
227
- def final(f):
228
- """This decorator can be used to indicate to type checkers that
229
- the decorated method cannot be overridden, and decorated class
230
- cannot be subclassed. For example:
231
-
232
- class Base:
233
- @final
234
- def done(self) -> None:
235
- ...
236
- class Sub(Base):
237
- def done(self) -> None: # Error reported by type checker
238
- ...
239
- @final
240
- class Leaf:
241
- ...
242
- class Other(Leaf): # Error reported by type checker
243
- ...
244
-
245
- There is no runtime checking of these properties. The decorator
246
- sets the ``__final__`` attribute to ``True`` on the decorated object
247
- to allow runtime introspection.
248
- """
249
- try:
250
- f.__final__ = True
251
- except (AttributeError, TypeError):
252
- # Skip the attribute silently if it is not writable.
253
- # AttributeError happens if the object has __slots__ or a
254
- # read-only property, TypeError if it's a builtin class.
255
- pass
256
- return f
257
-
258
-
259
- def IntVar(name):
260
- return typing.TypeVar(name)
261
-
262
-
263
- # A Literal bug was fixed in 3.11.0, 3.10.1 and 3.9.8
264
- if sys.version_info >= (3, 10, 1):
265
- Literal = typing.Literal
266
- else:
267
- def _flatten_literal_params(parameters):
268
- """An internal helper for Literal creation: flatten Literals among parameters"""
269
- params = []
270
- for p in parameters:
271
- if isinstance(p, _LiteralGenericAlias):
272
- params.extend(p.__args__)
273
- else:
274
- params.append(p)
275
- return tuple(params)
276
-
277
- def _value_and_type_iter(params):
278
- for p in params:
279
- yield p, type(p)
280
-
281
- class _LiteralGenericAlias(typing._GenericAlias, _root=True):
282
- def __eq__(self, other):
283
- if not isinstance(other, _LiteralGenericAlias):
284
- return NotImplemented
285
- these_args_deduped = set(_value_and_type_iter(self.__args__))
286
- other_args_deduped = set(_value_and_type_iter(other.__args__))
287
- return these_args_deduped == other_args_deduped
288
-
289
- def __hash__(self):
290
- return hash(frozenset(_value_and_type_iter(self.__args__)))
291
-
292
- class _LiteralForm(_ExtensionsSpecialForm, _root=True):
293
- def __init__(self, doc: str):
294
- self._name = 'Literal'
295
- self._doc = self.__doc__ = doc
296
-
297
- def __getitem__(self, parameters):
298
- if not isinstance(parameters, tuple):
299
- parameters = (parameters,)
300
-
301
- parameters = _flatten_literal_params(parameters)
302
-
303
- val_type_pairs = list(_value_and_type_iter(parameters))
304
- try:
305
- deduped_pairs = set(val_type_pairs)
306
- except TypeError:
307
- # unhashable parameters
308
- pass
309
- else:
310
- # similar logic to typing._deduplicate on Python 3.9+
311
- if len(deduped_pairs) < len(val_type_pairs):
312
- new_parameters = []
313
- for pair in val_type_pairs:
314
- if pair in deduped_pairs:
315
- new_parameters.append(pair[0])
316
- deduped_pairs.remove(pair)
317
- assert not deduped_pairs, deduped_pairs
318
- parameters = tuple(new_parameters)
319
-
320
- return _LiteralGenericAlias(self, parameters)
321
-
322
- Literal = _LiteralForm(doc="""\
323
- A type that can be used to indicate to type checkers
324
- that the corresponding value has a value literally equivalent
325
- to the provided parameter. For example:
326
-
327
- var: Literal[4] = 4
328
-
329
- The type checker understands that 'var' is literally equal to
330
- the value 4 and no other value.
331
-
332
- Literal[...] cannot be subclassed. There is no runtime
333
- checking verifying that the parameter is actually a value
334
- instead of a type.""")
335
-
336
-
337
- _overload_dummy = typing._overload_dummy
338
-
339
-
340
- if hasattr(typing, "get_overloads"): # 3.11+
341
- overload = typing.overload
342
- get_overloads = typing.get_overloads
343
- clear_overloads = typing.clear_overloads
344
- else:
345
- # {module: {qualname: {firstlineno: func}}}
346
- _overload_registry = collections.defaultdict(
347
- functools.partial(collections.defaultdict, dict)
348
- )
349
-
350
- def overload(func):
351
- """Decorator for overloaded functions/methods.
352
-
353
- In a stub file, place two or more stub definitions for the same
354
- function in a row, each decorated with @overload. For example:
355
-
356
- @overload
357
- def utf8(value: None) -> None: ...
358
- @overload
359
- def utf8(value: bytes) -> bytes: ...
360
- @overload
361
- def utf8(value: str) -> bytes: ...
362
-
363
- In a non-stub file (i.e. a regular .py file), do the same but
364
- follow it with an implementation. The implementation should *not*
365
- be decorated with @overload. For example:
366
-
367
- @overload
368
- def utf8(value: None) -> None: ...
369
- @overload
370
- def utf8(value: bytes) -> bytes: ...
371
- @overload
372
- def utf8(value: str) -> bytes: ...
373
- def utf8(value):
374
- # implementation goes here
375
-
376
- The overloads for a function can be retrieved at runtime using the
377
- get_overloads() function.
378
- """
379
- # classmethod and staticmethod
380
- f = getattr(func, "__func__", func)
381
- try:
382
- _overload_registry[f.__module__][f.__qualname__][
383
- f.__code__.co_firstlineno
384
- ] = func
385
- except AttributeError:
386
- # Not a normal function; ignore.
387
- pass
388
- return _overload_dummy
389
-
390
- def get_overloads(func):
391
- """Return all defined overloads for *func* as a sequence."""
392
- # classmethod and staticmethod
393
- f = getattr(func, "__func__", func)
394
- if f.__module__ not in _overload_registry:
395
- return []
396
- mod_dict = _overload_registry[f.__module__]
397
- if f.__qualname__ not in mod_dict:
398
- return []
399
- return list(mod_dict[f.__qualname__].values())
400
-
401
- def clear_overloads():
402
- """Clear all overloads in the registry."""
403
- _overload_registry.clear()
404
-
405
-
406
- # This is not a real generic class. Don't use outside annotations.
407
- Type = typing.Type
408
-
409
- # Various ABCs mimicking those in collections.abc.
410
- # A few are simply re-exported for completeness.
411
- Awaitable = typing.Awaitable
412
- Coroutine = typing.Coroutine
413
- AsyncIterable = typing.AsyncIterable
414
- AsyncIterator = typing.AsyncIterator
415
- Deque = typing.Deque
416
- DefaultDict = typing.DefaultDict
417
- OrderedDict = typing.OrderedDict
418
- Counter = typing.Counter
419
- ChainMap = typing.ChainMap
420
- Text = typing.Text
421
- TYPE_CHECKING = typing.TYPE_CHECKING
422
-
423
-
424
- if sys.version_info >= (3, 13, 0, "beta"):
425
- from typing import AsyncContextManager, AsyncGenerator, ContextManager, Generator
426
- else:
427
- def _is_dunder(attr):
428
- return attr.startswith('__') and attr.endswith('__')
429
-
430
- # Python <3.9 doesn't have typing._SpecialGenericAlias
431
- _special_generic_alias_base = getattr(
432
- typing, "_SpecialGenericAlias", typing._GenericAlias
433
- )
434
-
435
- class _SpecialGenericAlias(_special_generic_alias_base, _root=True):
436
- def __init__(self, origin, nparams, *, inst=True, name=None, defaults=()):
437
- if _special_generic_alias_base is typing._GenericAlias:
438
- # Python <3.9
439
- self.__origin__ = origin
440
- self._nparams = nparams
441
- super().__init__(origin, nparams, special=True, inst=inst, name=name)
442
- else:
443
- # Python >= 3.9
444
- super().__init__(origin, nparams, inst=inst, name=name)
445
- self._defaults = defaults
446
-
447
- def __setattr__(self, attr, val):
448
- allowed_attrs = {'_name', '_inst', '_nparams', '_defaults'}
449
- if _special_generic_alias_base is typing._GenericAlias:
450
- # Python <3.9
451
- allowed_attrs.add("__origin__")
452
- if _is_dunder(attr) or attr in allowed_attrs:
453
- object.__setattr__(self, attr, val)
454
- else:
455
- setattr(self.__origin__, attr, val)
456
-
457
- @typing._tp_cache
458
- def __getitem__(self, params):
459
- if not isinstance(params, tuple):
460
- params = (params,)
461
- msg = "Parameters to generic types must be types."
462
- params = tuple(typing._type_check(p, msg) for p in params)
463
- if (
464
- self._defaults
465
- and len(params) < self._nparams
466
- and len(params) + len(self._defaults) >= self._nparams
467
- ):
468
- params = (*params, *self._defaults[len(params) - self._nparams:])
469
- actual_len = len(params)
470
-
471
- if actual_len != self._nparams:
472
- if self._defaults:
473
- expected = f"at least {self._nparams - len(self._defaults)}"
474
- else:
475
- expected = str(self._nparams)
476
- if not self._nparams:
477
- raise TypeError(f"{self} is not a generic class")
478
- raise TypeError(
479
- f"Too {'many' if actual_len > self._nparams else 'few'}"
480
- f" arguments for {self};"
481
- f" actual {actual_len}, expected {expected}"
482
- )
483
- return self.copy_with(params)
484
-
485
- _NoneType = type(None)
486
- Generator = _SpecialGenericAlias(
487
- collections.abc.Generator, 3, defaults=(_NoneType, _NoneType)
488
- )
489
- AsyncGenerator = _SpecialGenericAlias(
490
- collections.abc.AsyncGenerator, 2, defaults=(_NoneType,)
491
- )
492
- ContextManager = _SpecialGenericAlias(
493
- contextlib.AbstractContextManager,
494
- 2,
495
- name="ContextManager",
496
- defaults=(typing.Optional[bool],)
497
- )
498
- AsyncContextManager = _SpecialGenericAlias(
499
- contextlib.AbstractAsyncContextManager,
500
- 2,
501
- name="AsyncContextManager",
502
- defaults=(typing.Optional[bool],)
503
- )
504
-
505
-
506
- _PROTO_ALLOWLIST = {
507
- 'collections.abc': [
508
- 'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable',
509
- 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible', 'Buffer',
510
- ],
511
- 'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'],
512
- 'typing_extensions': ['Buffer'],
513
- }
514
-
515
-
516
- _EXCLUDED_ATTRS = frozenset(typing.EXCLUDED_ATTRIBUTES) | {
517
- "__match_args__", "__protocol_attrs__", "__non_callable_proto_members__",
518
- "__final__",
519
- }
520
-
521
-
522
- def _get_protocol_attrs(cls):
523
- attrs = set()
524
- for base in cls.__mro__[:-1]: # without object
525
- if base.__name__ in {'Protocol', 'Generic'}:
526
- continue
527
- annotations = getattr(base, '__annotations__', {})
528
- for attr in (*base.__dict__, *annotations):
529
- if (not attr.startswith('_abc_') and attr not in _EXCLUDED_ATTRS):
530
- attrs.add(attr)
531
- return attrs
532
-
533
-
534
- def _caller(depth=2):
535
- try:
536
- return sys._getframe(depth).f_globals.get('__name__', '__main__')
537
- except (AttributeError, ValueError): # For platforms without _getframe()
538
- return None
539
-
540
-
541
- # `__match_args__` attribute was removed from protocol members in 3.13,
542
- # we want to backport this change to older Python versions.
543
- if sys.version_info >= (3, 13):
544
- Protocol = typing.Protocol
545
- else:
546
- def _allow_reckless_class_checks(depth=3):
547
- """Allow instance and class checks for special stdlib modules.
548
- The abc and functools modules indiscriminately call isinstance() and
549
- issubclass() on the whole MRO of a user class, which may contain protocols.
550
- """
551
- return _caller(depth) in {'abc', 'functools', None}
552
-
553
- def _no_init(self, *args, **kwargs):
554
- if type(self)._is_protocol:
555
- raise TypeError('Protocols cannot be instantiated')
556
-
557
- def _type_check_issubclass_arg_1(arg):
558
- """Raise TypeError if `arg` is not an instance of `type`
559
- in `issubclass(arg, <protocol>)`.
560
-
561
- In most cases, this is verified by type.__subclasscheck__.
562
- Checking it again unnecessarily would slow down issubclass() checks,
563
- so, we don't perform this check unless we absolutely have to.
564
-
565
- For various error paths, however,
566
- we want to ensure that *this* error message is shown to the user
567
- where relevant, rather than a typing.py-specific error message.
568
- """
569
- if not isinstance(arg, type):
570
- # Same error message as for issubclass(1, int).
571
- raise TypeError('issubclass() arg 1 must be a class')
572
-
573
- # Inheriting from typing._ProtocolMeta isn't actually desirable,
574
- # but is necessary to allow typing.Protocol and typing_extensions.Protocol
575
- # to mix without getting TypeErrors about "metaclass conflict"
576
- class _ProtocolMeta(type(typing.Protocol)):
577
- # This metaclass is somewhat unfortunate,
578
- # but is necessary for several reasons...
579
- #
580
- # NOTE: DO NOT call super() in any methods in this class
581
- # That would call the methods on typing._ProtocolMeta on Python 3.8-3.11
582
- # and those are slow
583
- def __new__(mcls, name, bases, namespace, **kwargs):
584
- if name == "Protocol" and len(bases) < 2:
585
- pass
586
- elif {Protocol, typing.Protocol} & set(bases):
587
- for base in bases:
588
- if not (
589
- base in {object, typing.Generic, Protocol, typing.Protocol}
590
- or base.__name__ in _PROTO_ALLOWLIST.get(base.__module__, [])
591
- or is_protocol(base)
592
- ):
593
- raise TypeError(
594
- f"Protocols can only inherit from other protocols, "
595
- f"got {base!r}"
596
- )
597
- return abc.ABCMeta.__new__(mcls, name, bases, namespace, **kwargs)
598
-
599
- def __init__(cls, *args, **kwargs):
600
- abc.ABCMeta.__init__(cls, *args, **kwargs)
601
- if getattr(cls, "_is_protocol", False):
602
- cls.__protocol_attrs__ = _get_protocol_attrs(cls)
603
-
604
- def __subclasscheck__(cls, other):
605
- if cls is Protocol:
606
- return type.__subclasscheck__(cls, other)
607
- if (
608
- getattr(cls, '_is_protocol', False)
609
- and not _allow_reckless_class_checks()
610
- ):
611
- if not getattr(cls, '_is_runtime_protocol', False):
612
- _type_check_issubclass_arg_1(other)
613
- raise TypeError(
614
- "Instance and class checks can only be used with "
615
- "@runtime_checkable protocols"
616
- )
617
- if (
618
- # this attribute is set by @runtime_checkable:
619
- cls.__non_callable_proto_members__
620
- and cls.__dict__.get("__subclasshook__") is _proto_hook
621
- ):
622
- _type_check_issubclass_arg_1(other)
623
- non_method_attrs = sorted(cls.__non_callable_proto_members__)
624
- raise TypeError(
625
- "Protocols with non-method members don't support issubclass()."
626
- f" Non-method members: {str(non_method_attrs)[1:-1]}."
627
- )
628
- return abc.ABCMeta.__subclasscheck__(cls, other)
629
-
630
- def __instancecheck__(cls, instance):
631
- # We need this method for situations where attributes are
632
- # assigned in __init__.
633
- if cls is Protocol:
634
- return type.__instancecheck__(cls, instance)
635
- if not getattr(cls, "_is_protocol", False):
636
- # i.e., it's a concrete subclass of a protocol
637
- return abc.ABCMeta.__instancecheck__(cls, instance)
638
-
639
- if (
640
- not getattr(cls, '_is_runtime_protocol', False) and
641
- not _allow_reckless_class_checks()
642
- ):
643
- raise TypeError("Instance and class checks can only be used with"
644
- " @runtime_checkable protocols")
645
-
646
- if abc.ABCMeta.__instancecheck__(cls, instance):
647
- return True
648
-
649
- for attr in cls.__protocol_attrs__:
650
- try:
651
- val = inspect.getattr_static(instance, attr)
652
- except AttributeError:
653
- break
654
- # this attribute is set by @runtime_checkable:
655
- if val is None and attr not in cls.__non_callable_proto_members__:
656
- break
657
- else:
658
- return True
659
-
660
- return False
661
-
662
- def __eq__(cls, other):
663
- # Hack so that typing.Generic.__class_getitem__
664
- # treats typing_extensions.Protocol
665
- # as equivalent to typing.Protocol
666
- if abc.ABCMeta.__eq__(cls, other) is True:
667
- return True
668
- return cls is Protocol and other is typing.Protocol
669
-
670
- # This has to be defined, or the abc-module cache
671
- # complains about classes with this metaclass being unhashable,
672
- # if we define only __eq__!
673
- def __hash__(cls) -> int:
674
- return type.__hash__(cls)
675
-
676
- @classmethod
677
- def _proto_hook(cls, other):
678
- if not cls.__dict__.get('_is_protocol', False):
679
- return NotImplemented
680
-
681
- for attr in cls.__protocol_attrs__:
682
- for base in other.__mro__:
683
- # Check if the members appears in the class dictionary...
684
- if attr in base.__dict__:
685
- if base.__dict__[attr] is None:
686
- return NotImplemented
687
- break
688
-
689
- # ...or in annotations, if it is a sub-protocol.
690
- annotations = getattr(base, '__annotations__', {})
691
- if (
692
- isinstance(annotations, collections.abc.Mapping)
693
- and attr in annotations
694
- and is_protocol(other)
695
- ):
696
- break
697
- else:
698
- return NotImplemented
699
- return True
700
-
701
- class Protocol(typing.Generic, metaclass=_ProtocolMeta):
702
- __doc__ = typing.Protocol.__doc__
703
- __slots__ = ()
704
- _is_protocol = True
705
- _is_runtime_protocol = False
706
-
707
- def __init_subclass__(cls, *args, **kwargs):
708
- super().__init_subclass__(*args, **kwargs)
709
-
710
- # Determine if this is a protocol or a concrete subclass.
711
- if not cls.__dict__.get('_is_protocol', False):
712
- cls._is_protocol = any(b is Protocol for b in cls.__bases__)
713
-
714
- # Set (or override) the protocol subclass hook.
715
- if '__subclasshook__' not in cls.__dict__:
716
- cls.__subclasshook__ = _proto_hook
717
-
718
- # Prohibit instantiation for protocol classes
719
- if cls._is_protocol and cls.__init__ is Protocol.__init__:
720
- cls.__init__ = _no_init
721
-
722
-
723
- if sys.version_info >= (3, 13):
724
- runtime_checkable = typing.runtime_checkable
725
- else:
726
- def runtime_checkable(cls):
727
- """Mark a protocol class as a runtime protocol.
728
-
729
- Such protocol can be used with isinstance() and issubclass().
730
- Raise TypeError if applied to a non-protocol class.
731
- This allows a simple-minded structural check very similar to
732
- one trick ponies in collections.abc such as Iterable.
733
-
734
- For example::
735
-
736
- @runtime_checkable
737
- class Closable(Protocol):
738
- def close(self): ...
739
-
740
- assert isinstance(open('/some/file'), Closable)
741
-
742
- Warning: this will check only the presence of the required methods,
743
- not their type signatures!
744
- """
745
- if not issubclass(cls, typing.Generic) or not getattr(cls, '_is_protocol', False):
746
- raise TypeError(f'@runtime_checkable can be only applied to protocol classes,'
747
- f' got {cls!r}')
748
- cls._is_runtime_protocol = True
749
-
750
- # typing.Protocol classes on <=3.11 break if we execute this block,
751
- # because typing.Protocol classes on <=3.11 don't have a
752
- # `__protocol_attrs__` attribute, and this block relies on the
753
- # `__protocol_attrs__` attribute. Meanwhile, typing.Protocol classes on 3.12.2+
754
- # break if we *don't* execute this block, because *they* assume that all
755
- # protocol classes have a `__non_callable_proto_members__` attribute
756
- # (which this block sets)
757
- if isinstance(cls, _ProtocolMeta) or sys.version_info >= (3, 12, 2):
758
- # PEP 544 prohibits using issubclass()
759
- # with protocols that have non-method members.
760
- # See gh-113320 for why we compute this attribute here,
761
- # rather than in `_ProtocolMeta.__init__`
762
- cls.__non_callable_proto_members__ = set()
763
- for attr in cls.__protocol_attrs__:
764
- try:
765
- is_callable = callable(getattr(cls, attr, None))
766
- except Exception as e:
767
- raise TypeError(
768
- f"Failed to determine whether protocol member {attr!r} "
769
- "is a method member"
770
- ) from e
771
- else:
772
- if not is_callable:
773
- cls.__non_callable_proto_members__.add(attr)
774
-
775
- return cls
776
-
777
-
778
- # The "runtime" alias exists for backwards compatibility.
779
- runtime = runtime_checkable
780
-
781
-
782
- # Our version of runtime-checkable protocols is faster on Python 3.8-3.11
783
- if sys.version_info >= (3, 12):
784
- SupportsInt = typing.SupportsInt
785
- SupportsFloat = typing.SupportsFloat
786
- SupportsComplex = typing.SupportsComplex
787
- SupportsBytes = typing.SupportsBytes
788
- SupportsIndex = typing.SupportsIndex
789
- SupportsAbs = typing.SupportsAbs
790
- SupportsRound = typing.SupportsRound
791
- else:
792
- @runtime_checkable
793
- class SupportsInt(Protocol):
794
- """An ABC with one abstract method __int__."""
795
- __slots__ = ()
796
-
797
- @abc.abstractmethod
798
- def __int__(self) -> int:
799
- pass
800
-
801
- @runtime_checkable
802
- class SupportsFloat(Protocol):
803
- """An ABC with one abstract method __float__."""
804
- __slots__ = ()
805
-
806
- @abc.abstractmethod
807
- def __float__(self) -> float:
808
- pass
809
-
810
- @runtime_checkable
811
- class SupportsComplex(Protocol):
812
- """An ABC with one abstract method __complex__."""
813
- __slots__ = ()
814
-
815
- @abc.abstractmethod
816
- def __complex__(self) -> complex:
817
- pass
818
-
819
- @runtime_checkable
820
- class SupportsBytes(Protocol):
821
- """An ABC with one abstract method __bytes__."""
822
- __slots__ = ()
823
-
824
- @abc.abstractmethod
825
- def __bytes__(self) -> bytes:
826
- pass
827
-
828
- @runtime_checkable
829
- class SupportsIndex(Protocol):
830
- __slots__ = ()
831
-
832
- @abc.abstractmethod
833
- def __index__(self) -> int:
834
- pass
835
-
836
- @runtime_checkable
837
- class SupportsAbs(Protocol[T_co]):
838
- """
839
- An ABC with one abstract method __abs__ that is covariant in its return type.
840
- """
841
- __slots__ = ()
842
-
843
- @abc.abstractmethod
844
- def __abs__(self) -> T_co:
845
- pass
846
-
847
- @runtime_checkable
848
- class SupportsRound(Protocol[T_co]):
849
- """
850
- An ABC with one abstract method __round__ that is covariant in its return type.
851
- """
852
- __slots__ = ()
853
-
854
- @abc.abstractmethod
855
- def __round__(self, ndigits: int = 0) -> T_co:
856
- pass
857
-
858
-
859
- def _ensure_subclassable(mro_entries):
860
- def inner(func):
861
- if sys.implementation.name == "pypy" and sys.version_info < (3, 9):
862
- cls_dict = {
863
- "__call__": staticmethod(func),
864
- "__mro_entries__": staticmethod(mro_entries)
865
- }
866
- t = type(func.__name__, (), cls_dict)
867
- return functools.update_wrapper(t(), func)
868
- else:
869
- func.__mro_entries__ = mro_entries
870
- return func
871
- return inner
872
-
873
-
874
- # Update this to something like >=3.13.0b1 if and when
875
- # PEP 728 is implemented in CPython
876
- _PEP_728_IMPLEMENTED = False
877
-
878
- if _PEP_728_IMPLEMENTED:
879
- # The standard library TypedDict in Python 3.8 does not store runtime information
880
- # about which (if any) keys are optional. See https://bugs.python.org/issue38834
881
- # The standard library TypedDict in Python 3.9.0/1 does not honour the "total"
882
- # keyword with old-style TypedDict(). See https://bugs.python.org/issue42059
883
- # The standard library TypedDict below Python 3.11 does not store runtime
884
- # information about optional and required keys when using Required or NotRequired.
885
- # Generic TypedDicts are also impossible using typing.TypedDict on Python <3.11.
886
- # Aaaand on 3.12 we add __orig_bases__ to TypedDict
887
- # to enable better runtime introspection.
888
- # On 3.13 we deprecate some odd ways of creating TypedDicts.
889
- # Also on 3.13, PEP 705 adds the ReadOnly[] qualifier.
890
- # PEP 728 (still pending) makes more changes.
891
- TypedDict = typing.TypedDict
892
- _TypedDictMeta = typing._TypedDictMeta
893
- is_typeddict = typing.is_typeddict
894
- else:
895
- # 3.10.0 and later
896
- _TAKES_MODULE = "module" in inspect.signature(typing._type_check).parameters
897
-
898
- def _get_typeddict_qualifiers(annotation_type):
899
- while True:
900
- annotation_origin = get_origin(annotation_type)
901
- if annotation_origin is Annotated:
902
- annotation_args = get_args(annotation_type)
903
- if annotation_args:
904
- annotation_type = annotation_args[0]
905
- else:
906
- break
907
- elif annotation_origin is Required:
908
- yield Required
909
- annotation_type, = get_args(annotation_type)
910
- elif annotation_origin is NotRequired:
911
- yield NotRequired
912
- annotation_type, = get_args(annotation_type)
913
- elif annotation_origin is ReadOnly:
914
- yield ReadOnly
915
- annotation_type, = get_args(annotation_type)
916
- else:
917
- break
918
-
919
- class _TypedDictMeta(type):
920
- def __new__(cls, name, bases, ns, *, total=True, closed=False):
921
- """Create new typed dict class object.
922
-
923
- This method is called when TypedDict is subclassed,
924
- or when TypedDict is instantiated. This way
925
- TypedDict supports all three syntax forms described in its docstring.
926
- Subclasses and instances of TypedDict return actual dictionaries.
927
- """
928
- for base in bases:
929
- if type(base) is not _TypedDictMeta and base is not typing.Generic:
930
- raise TypeError('cannot inherit from both a TypedDict type '
931
- 'and a non-TypedDict base class')
932
-
933
- if any(issubclass(b, typing.Generic) for b in bases):
934
- generic_base = (typing.Generic,)
935
- else:
936
- generic_base = ()
937
-
938
- # typing.py generally doesn't let you inherit from plain Generic, unless
939
- # the name of the class happens to be "Protocol"
940
- tp_dict = type.__new__(_TypedDictMeta, "Protocol", (*generic_base, dict), ns)
941
- tp_dict.__name__ = name
942
- if tp_dict.__qualname__ == "Protocol":
943
- tp_dict.__qualname__ = name
944
-
945
- if not hasattr(tp_dict, '__orig_bases__'):
946
- tp_dict.__orig_bases__ = bases
947
-
948
- annotations = {}
949
- if "__annotations__" in ns:
950
- own_annotations = ns["__annotations__"]
951
- elif "__annotate__" in ns:
952
- # TODO: Use inspect.VALUE here, and make the annotations lazily evaluated
953
- own_annotations = ns["__annotate__"](1)
954
- else:
955
- own_annotations = {}
956
- msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
957
- if _TAKES_MODULE:
958
- own_annotations = {
959
- n: typing._type_check(tp, msg, module=tp_dict.__module__)
960
- for n, tp in own_annotations.items()
961
- }
962
- else:
963
- own_annotations = {
964
- n: typing._type_check(tp, msg)
965
- for n, tp in own_annotations.items()
966
- }
967
- required_keys = set()
968
- optional_keys = set()
969
- readonly_keys = set()
970
- mutable_keys = set()
971
- extra_items_type = None
972
-
973
- for base in bases:
974
- base_dict = base.__dict__
975
-
976
- annotations.update(base_dict.get('__annotations__', {}))
977
- required_keys.update(base_dict.get('__required_keys__', ()))
978
- optional_keys.update(base_dict.get('__optional_keys__', ()))
979
- readonly_keys.update(base_dict.get('__readonly_keys__', ()))
980
- mutable_keys.update(base_dict.get('__mutable_keys__', ()))
981
- base_extra_items_type = base_dict.get('__extra_items__', None)
982
- if base_extra_items_type is not None:
983
- extra_items_type = base_extra_items_type
984
-
985
- if closed and extra_items_type is None:
986
- extra_items_type = Never
987
- if closed and "__extra_items__" in own_annotations:
988
- annotation_type = own_annotations.pop("__extra_items__")
989
- qualifiers = set(_get_typeddict_qualifiers(annotation_type))
990
- if Required in qualifiers:
991
- raise TypeError(
992
- "Special key __extra_items__ does not support "
993
- "Required"
994
- )
995
- if NotRequired in qualifiers:
996
- raise TypeError(
997
- "Special key __extra_items__ does not support "
998
- "NotRequired"
999
- )
1000
- extra_items_type = annotation_type
1001
-
1002
- annotations.update(own_annotations)
1003
- for annotation_key, annotation_type in own_annotations.items():
1004
- qualifiers = set(_get_typeddict_qualifiers(annotation_type))
1005
-
1006
- if Required in qualifiers:
1007
- required_keys.add(annotation_key)
1008
- elif NotRequired in qualifiers:
1009
- optional_keys.add(annotation_key)
1010
- elif total:
1011
- required_keys.add(annotation_key)
1012
- else:
1013
- optional_keys.add(annotation_key)
1014
- if ReadOnly in qualifiers:
1015
- mutable_keys.discard(annotation_key)
1016
- readonly_keys.add(annotation_key)
1017
- else:
1018
- mutable_keys.add(annotation_key)
1019
- readonly_keys.discard(annotation_key)
1020
-
1021
- tp_dict.__annotations__ = annotations
1022
- tp_dict.__required_keys__ = frozenset(required_keys)
1023
- tp_dict.__optional_keys__ = frozenset(optional_keys)
1024
- tp_dict.__readonly_keys__ = frozenset(readonly_keys)
1025
- tp_dict.__mutable_keys__ = frozenset(mutable_keys)
1026
- if not hasattr(tp_dict, '__total__'):
1027
- tp_dict.__total__ = total
1028
- tp_dict.__closed__ = closed
1029
- tp_dict.__extra_items__ = extra_items_type
1030
- return tp_dict
1031
-
1032
- __call__ = dict # static method
1033
-
1034
- def __subclasscheck__(cls, other):
1035
- # Typed dicts are only for static structural subtyping.
1036
- raise TypeError('TypedDict does not support instance and class checks')
1037
-
1038
- __instancecheck__ = __subclasscheck__
1039
-
1040
- _TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {})
1041
-
1042
- @_ensure_subclassable(lambda bases: (_TypedDict,))
1043
- def TypedDict(typename, fields=_marker, /, *, total=True, closed=False, **kwargs):
1044
- """A simple typed namespace. At runtime it is equivalent to a plain dict.
1045
-
1046
- TypedDict creates a dictionary type such that a type checker will expect all
1047
- instances to have a certain set of keys, where each key is
1048
- associated with a value of a consistent type. This expectation
1049
- is not checked at runtime.
1050
-
1051
- Usage::
1052
-
1053
- class Point2D(TypedDict):
1054
- x: int
1055
- y: int
1056
- label: str
1057
-
1058
- a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
1059
- b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
1060
-
1061
- assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
1062
-
1063
- The type info can be accessed via the Point2D.__annotations__ dict, and
1064
- the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
1065
- TypedDict supports an additional equivalent form::
1066
-
1067
- Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
1068
-
1069
- By default, all keys must be present in a TypedDict. It is possible
1070
- to override this by specifying totality::
1071
-
1072
- class Point2D(TypedDict, total=False):
1073
- x: int
1074
- y: int
1075
-
1076
- This means that a Point2D TypedDict can have any of the keys omitted. A type
1077
- checker is only expected to support a literal False or True as the value of
1078
- the total argument. True is the default, and makes all items defined in the
1079
- class body be required.
1080
-
1081
- The Required and NotRequired special forms can also be used to mark
1082
- individual keys as being required or not required::
1083
-
1084
- class Point2D(TypedDict):
1085
- x: int # the "x" key must always be present (Required is the default)
1086
- y: NotRequired[int] # the "y" key can be omitted
1087
-
1088
- See PEP 655 for more details on Required and NotRequired.
1089
- """
1090
- if fields is _marker or fields is None:
1091
- if fields is _marker:
1092
- deprecated_thing = "Failing to pass a value for the 'fields' parameter"
1093
- else:
1094
- deprecated_thing = "Passing `None` as the 'fields' parameter"
1095
-
1096
- example = f"`{typename} = TypedDict({typename!r}, {{}})`"
1097
- deprecation_msg = (
1098
- f"{deprecated_thing} is deprecated and will be disallowed in "
1099
- "Python 3.15. To create a TypedDict class with 0 fields "
1100
- "using the functional syntax, pass an empty dictionary, e.g. "
1101
- ) + example + "."
1102
- warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2)
1103
- if closed is not False and closed is not True:
1104
- kwargs["closed"] = closed
1105
- closed = False
1106
- fields = kwargs
1107
- elif kwargs:
1108
- raise TypeError("TypedDict takes either a dict or keyword arguments,"
1109
- " but not both")
1110
- if kwargs:
1111
- if sys.version_info >= (3, 13):
1112
- raise TypeError("TypedDict takes no keyword arguments")
1113
- warnings.warn(
1114
- "The kwargs-based syntax for TypedDict definitions is deprecated "
1115
- "in Python 3.11, will be removed in Python 3.13, and may not be "
1116
- "understood by third-party type checkers.",
1117
- DeprecationWarning,
1118
- stacklevel=2,
1119
- )
1120
-
1121
- ns = {'__annotations__': dict(fields)}
1122
- module = _caller()
1123
- if module is not None:
1124
- # Setting correct module is necessary to make typed dict classes pickleable.
1125
- ns['__module__'] = module
1126
-
1127
- td = _TypedDictMeta(typename, (), ns, total=total, closed=closed)
1128
- td.__orig_bases__ = (TypedDict,)
1129
- return td
1130
-
1131
- if hasattr(typing, "_TypedDictMeta"):
1132
- _TYPEDDICT_TYPES = (typing._TypedDictMeta, _TypedDictMeta)
1133
- else:
1134
- _TYPEDDICT_TYPES = (_TypedDictMeta,)
1135
-
1136
- def is_typeddict(tp):
1137
- """Check if an annotation is a TypedDict class
1138
-
1139
- For example::
1140
- class Film(TypedDict):
1141
- title: str
1142
- year: int
1143
-
1144
- is_typeddict(Film) # => True
1145
- is_typeddict(Union[list, str]) # => False
1146
- """
1147
- # On 3.8, this would otherwise return True
1148
- if hasattr(typing, "TypedDict") and tp is typing.TypedDict:
1149
- return False
1150
- return isinstance(tp, _TYPEDDICT_TYPES)
1151
-
1152
-
1153
- if hasattr(typing, "assert_type"):
1154
- assert_type = typing.assert_type
1155
-
1156
- else:
1157
- def assert_type(val, typ, /):
1158
- """Assert (to the type checker) that the value is of the given type.
1159
-
1160
- When the type checker encounters a call to assert_type(), it
1161
- emits an error if the value is not of the specified type::
1162
-
1163
- def greet(name: str) -> None:
1164
- assert_type(name, str) # ok
1165
- assert_type(name, int) # type checker error
1166
-
1167
- At runtime this returns the first argument unchanged and otherwise
1168
- does nothing.
1169
- """
1170
- return val
1171
-
1172
-
1173
- if hasattr(typing, "ReadOnly"): # 3.13+
1174
- get_type_hints = typing.get_type_hints
1175
- else: # <=3.13
1176
- # replaces _strip_annotations()
1177
- def _strip_extras(t):
1178
- """Strips Annotated, Required and NotRequired from a given type."""
1179
- if isinstance(t, _AnnotatedAlias):
1180
- return _strip_extras(t.__origin__)
1181
- if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired, ReadOnly):
1182
- return _strip_extras(t.__args__[0])
1183
- if isinstance(t, typing._GenericAlias):
1184
- stripped_args = tuple(_strip_extras(a) for a in t.__args__)
1185
- if stripped_args == t.__args__:
1186
- return t
1187
- return t.copy_with(stripped_args)
1188
- if hasattr(_types, "GenericAlias") and isinstance(t, _types.GenericAlias):
1189
- stripped_args = tuple(_strip_extras(a) for a in t.__args__)
1190
- if stripped_args == t.__args__:
1191
- return t
1192
- return _types.GenericAlias(t.__origin__, stripped_args)
1193
- if hasattr(_types, "UnionType") and isinstance(t, _types.UnionType):
1194
- stripped_args = tuple(_strip_extras(a) for a in t.__args__)
1195
- if stripped_args == t.__args__:
1196
- return t
1197
- return functools.reduce(operator.or_, stripped_args)
1198
-
1199
- return t
1200
-
1201
- def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
1202
- """Return type hints for an object.
1203
-
1204
- This is often the same as obj.__annotations__, but it handles
1205
- forward references encoded as string literals, adds Optional[t] if a
1206
- default value equal to None is set and recursively replaces all
1207
- 'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T'
1208
- (unless 'include_extras=True').
1209
-
1210
- The argument may be a module, class, method, or function. The annotations
1211
- are returned as a dictionary. For classes, annotations include also
1212
- inherited members.
1213
-
1214
- TypeError is raised if the argument is not of a type that can contain
1215
- annotations, and an empty dictionary is returned if no annotations are
1216
- present.
1217
-
1218
- BEWARE -- the behavior of globalns and localns is counterintuitive
1219
- (unless you are familiar with how eval() and exec() work). The
1220
- search order is locals first, then globals.
1221
-
1222
- - If no dict arguments are passed, an attempt is made to use the
1223
- globals from obj (or the respective module's globals for classes),
1224
- and these are also used as the locals. If the object does not appear
1225
- to have globals, an empty dictionary is used.
1226
-
1227
- - If one dict argument is passed, it is used for both globals and
1228
- locals.
1229
-
1230
- - If two dict arguments are passed, they specify globals and
1231
- locals, respectively.
1232
- """
1233
- if hasattr(typing, "Annotated"): # 3.9+
1234
- hint = typing.get_type_hints(
1235
- obj, globalns=globalns, localns=localns, include_extras=True
1236
- )
1237
- else: # 3.8
1238
- hint = typing.get_type_hints(obj, globalns=globalns, localns=localns)
1239
- if include_extras:
1240
- return hint
1241
- return {k: _strip_extras(t) for k, t in hint.items()}
1242
-
1243
-
1244
- # Python 3.9+ has PEP 593 (Annotated)
1245
- if hasattr(typing, 'Annotated'):
1246
- Annotated = typing.Annotated
1247
- # Not exported and not a public API, but needed for get_origin() and get_args()
1248
- # to work.
1249
- _AnnotatedAlias = typing._AnnotatedAlias
1250
- # 3.8
1251
- else:
1252
- class _AnnotatedAlias(typing._GenericAlias, _root=True):
1253
- """Runtime representation of an annotated type.
1254
-
1255
- At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
1256
- with extra annotations. The alias behaves like a normal typing alias,
1257
- instantiating is the same as instantiating the underlying type, binding
1258
- it to types is also the same.
1259
- """
1260
- def __init__(self, origin, metadata):
1261
- if isinstance(origin, _AnnotatedAlias):
1262
- metadata = origin.__metadata__ + metadata
1263
- origin = origin.__origin__
1264
- super().__init__(origin, origin)
1265
- self.__metadata__ = metadata
1266
-
1267
- def copy_with(self, params):
1268
- assert len(params) == 1
1269
- new_type = params[0]
1270
- return _AnnotatedAlias(new_type, self.__metadata__)
1271
-
1272
- def __repr__(self):
1273
- return (f"typing_extensions.Annotated[{typing._type_repr(self.__origin__)}, "
1274
- f"{', '.join(repr(a) for a in self.__metadata__)}]")
1275
-
1276
- def __reduce__(self):
1277
- return operator.getitem, (
1278
- Annotated, (self.__origin__, *self.__metadata__)
1279
- )
1280
-
1281
- def __eq__(self, other):
1282
- if not isinstance(other, _AnnotatedAlias):
1283
- return NotImplemented
1284
- if self.__origin__ != other.__origin__:
1285
- return False
1286
- return self.__metadata__ == other.__metadata__
1287
-
1288
- def __hash__(self):
1289
- return hash((self.__origin__, self.__metadata__))
1290
-
1291
- class Annotated:
1292
- """Add context specific metadata to a type.
1293
-
1294
- Example: Annotated[int, runtime_check.Unsigned] indicates to the
1295
- hypothetical runtime_check module that this type is an unsigned int.
1296
- Every other consumer of this type can ignore this metadata and treat
1297
- this type as int.
1298
-
1299
- The first argument to Annotated must be a valid type (and will be in
1300
- the __origin__ field), the remaining arguments are kept as a tuple in
1301
- the __extra__ field.
1302
-
1303
- Details:
1304
-
1305
- - It's an error to call `Annotated` with less than two arguments.
1306
- - Nested Annotated are flattened::
1307
-
1308
- Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
1309
-
1310
- - Instantiating an annotated type is equivalent to instantiating the
1311
- underlying type::
1312
-
1313
- Annotated[C, Ann1](5) == C(5)
1314
-
1315
- - Annotated can be used as a generic type alias::
1316
-
1317
- Optimized = Annotated[T, runtime.Optimize()]
1318
- Optimized[int] == Annotated[int, runtime.Optimize()]
1319
-
1320
- OptimizedList = Annotated[List[T], runtime.Optimize()]
1321
- OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
1322
- """
1323
-
1324
- __slots__ = ()
1325
-
1326
- def __new__(cls, *args, **kwargs):
1327
- raise TypeError("Type Annotated cannot be instantiated.")
1328
-
1329
- @typing._tp_cache
1330
- def __class_getitem__(cls, params):
1331
- if not isinstance(params, tuple) or len(params) < 2:
1332
- raise TypeError("Annotated[...] should be used "
1333
- "with at least two arguments (a type and an "
1334
- "annotation).")
1335
- allowed_special_forms = (ClassVar, Final)
1336
- if get_origin(params[0]) in allowed_special_forms:
1337
- origin = params[0]
1338
- else:
1339
- msg = "Annotated[t, ...]: t must be a type."
1340
- origin = typing._type_check(params[0], msg)
1341
- metadata = tuple(params[1:])
1342
- return _AnnotatedAlias(origin, metadata)
1343
-
1344
- def __init_subclass__(cls, *args, **kwargs):
1345
- raise TypeError(
1346
- f"Cannot subclass {cls.__module__}.Annotated"
1347
- )
1348
-
1349
- # Python 3.8 has get_origin() and get_args() but those implementations aren't
1350
- # Annotated-aware, so we can't use those. Python 3.9's versions don't support
1351
- # ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do.
1352
- if sys.version_info[:2] >= (3, 10):
1353
- get_origin = typing.get_origin
1354
- get_args = typing.get_args
1355
- # 3.8-3.9
1356
- else:
1357
- try:
1358
- # 3.9+
1359
- from typing import _BaseGenericAlias
1360
- except ImportError:
1361
- _BaseGenericAlias = typing._GenericAlias
1362
- try:
1363
- # 3.9+
1364
- from typing import GenericAlias as _typing_GenericAlias
1365
- except ImportError:
1366
- _typing_GenericAlias = typing._GenericAlias
1367
-
1368
- def get_origin(tp):
1369
- """Get the unsubscripted version of a type.
1370
-
1371
- This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
1372
- and Annotated. Return None for unsupported types. Examples::
1373
-
1374
- get_origin(Literal[42]) is Literal
1375
- get_origin(int) is None
1376
- get_origin(ClassVar[int]) is ClassVar
1377
- get_origin(Generic) is Generic
1378
- get_origin(Generic[T]) is Generic
1379
- get_origin(Union[T, int]) is Union
1380
- get_origin(List[Tuple[T, T]][int]) == list
1381
- get_origin(P.args) is P
1382
- """
1383
- if isinstance(tp, _AnnotatedAlias):
1384
- return Annotated
1385
- if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias, _BaseGenericAlias,
1386
- ParamSpecArgs, ParamSpecKwargs)):
1387
- return tp.__origin__
1388
- if tp is typing.Generic:
1389
- return typing.Generic
1390
- return None
1391
-
1392
- def get_args(tp):
1393
- """Get type arguments with all substitutions performed.
1394
-
1395
- For unions, basic simplifications used by Union constructor are performed.
1396
- Examples::
1397
- get_args(Dict[str, int]) == (str, int)
1398
- get_args(int) == ()
1399
- get_args(Union[int, Union[T, int], str][int]) == (int, str)
1400
- get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
1401
- get_args(Callable[[], T][int]) == ([], int)
1402
- """
1403
- if isinstance(tp, _AnnotatedAlias):
1404
- return (tp.__origin__, *tp.__metadata__)
1405
- if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias)):
1406
- if getattr(tp, "_special", False):
1407
- return ()
1408
- res = tp.__args__
1409
- if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis:
1410
- res = (list(res[:-1]), res[-1])
1411
- return res
1412
- return ()
1413
-
1414
-
1415
- # 3.10+
1416
- if hasattr(typing, 'TypeAlias'):
1417
- TypeAlias = typing.TypeAlias
1418
- # 3.9
1419
- elif sys.version_info[:2] >= (3, 9):
1420
- @_ExtensionsSpecialForm
1421
- def TypeAlias(self, parameters):
1422
- """Special marker indicating that an assignment should
1423
- be recognized as a proper type alias definition by type
1424
- checkers.
1425
-
1426
- For example::
1427
-
1428
- Predicate: TypeAlias = Callable[..., bool]
1429
-
1430
- It's invalid when used anywhere except as in the example above.
1431
- """
1432
- raise TypeError(f"{self} is not subscriptable")
1433
- # 3.8
1434
- else:
1435
- TypeAlias = _ExtensionsSpecialForm(
1436
- 'TypeAlias',
1437
- doc="""Special marker indicating that an assignment should
1438
- be recognized as a proper type alias definition by type
1439
- checkers.
1440
-
1441
- For example::
1442
-
1443
- Predicate: TypeAlias = Callable[..., bool]
1444
-
1445
- It's invalid when used anywhere except as in the example
1446
- above."""
1447
- )
1448
-
1449
-
1450
- if hasattr(typing, "NoDefault"):
1451
- NoDefault = typing.NoDefault
1452
- else:
1453
- class NoDefaultTypeMeta(type):
1454
- def __setattr__(cls, attr, value):
1455
- # TypeError is consistent with the behavior of NoneType
1456
- raise TypeError(
1457
- f"cannot set {attr!r} attribute of immutable type {cls.__name__!r}"
1458
- )
1459
-
1460
- class NoDefaultType(metaclass=NoDefaultTypeMeta):
1461
- """The type of the NoDefault singleton."""
1462
-
1463
- __slots__ = ()
1464
-
1465
- def __new__(cls):
1466
- return globals().get("NoDefault") or object.__new__(cls)
1467
-
1468
- def __repr__(self):
1469
- return "typing_extensions.NoDefault"
1470
-
1471
- def __reduce__(self):
1472
- return "NoDefault"
1473
-
1474
- NoDefault = NoDefaultType()
1475
- del NoDefaultType, NoDefaultTypeMeta
1476
-
1477
-
1478
- def _set_default(type_param, default):
1479
- type_param.has_default = lambda: default is not NoDefault
1480
- type_param.__default__ = default
1481
-
1482
-
1483
- def _set_module(typevarlike):
1484
- # for pickling:
1485
- def_mod = _caller(depth=3)
1486
- if def_mod != 'typing_extensions':
1487
- typevarlike.__module__ = def_mod
1488
-
1489
-
1490
- class _DefaultMixin:
1491
- """Mixin for TypeVarLike defaults."""
1492
-
1493
- __slots__ = ()
1494
- __init__ = _set_default
1495
-
1496
-
1497
- # Classes using this metaclass must provide a _backported_typevarlike ClassVar
1498
- class _TypeVarLikeMeta(type):
1499
- def __instancecheck__(cls, __instance: Any) -> bool:
1500
- return isinstance(__instance, cls._backported_typevarlike)
1501
-
1502
-
1503
- if _PEP_696_IMPLEMENTED:
1504
- from typing import TypeVar
1505
- else:
1506
- # Add default and infer_variance parameters from PEP 696 and 695
1507
- class TypeVar(metaclass=_TypeVarLikeMeta):
1508
- """Type variable."""
1509
-
1510
- _backported_typevarlike = typing.TypeVar
1511
-
1512
- def __new__(cls, name, *constraints, bound=None,
1513
- covariant=False, contravariant=False,
1514
- default=NoDefault, infer_variance=False):
1515
- if hasattr(typing, "TypeAliasType"):
1516
- # PEP 695 implemented (3.12+), can pass infer_variance to typing.TypeVar
1517
- typevar = typing.TypeVar(name, *constraints, bound=bound,
1518
- covariant=covariant, contravariant=contravariant,
1519
- infer_variance=infer_variance)
1520
- else:
1521
- typevar = typing.TypeVar(name, *constraints, bound=bound,
1522
- covariant=covariant, contravariant=contravariant)
1523
- if infer_variance and (covariant or contravariant):
1524
- raise ValueError("Variance cannot be specified with infer_variance.")
1525
- typevar.__infer_variance__ = infer_variance
1526
-
1527
- _set_default(typevar, default)
1528
- _set_module(typevar)
1529
-
1530
- def _tvar_prepare_subst(alias, args):
1531
- if (
1532
- typevar.has_default()
1533
- and alias.__parameters__.index(typevar) == len(args)
1534
- ):
1535
- args += (typevar.__default__,)
1536
- return args
1537
-
1538
- typevar.__typing_prepare_subst__ = _tvar_prepare_subst
1539
- return typevar
1540
-
1541
- def __init_subclass__(cls) -> None:
1542
- raise TypeError(f"type '{__name__}.TypeVar' is not an acceptable base type")
1543
-
1544
-
1545
- # Python 3.10+ has PEP 612
1546
- if hasattr(typing, 'ParamSpecArgs'):
1547
- ParamSpecArgs = typing.ParamSpecArgs
1548
- ParamSpecKwargs = typing.ParamSpecKwargs
1549
- # 3.8-3.9
1550
- else:
1551
- class _Immutable:
1552
- """Mixin to indicate that object should not be copied."""
1553
- __slots__ = ()
1554
-
1555
- def __copy__(self):
1556
- return self
1557
-
1558
- def __deepcopy__(self, memo):
1559
- return self
1560
-
1561
- class ParamSpecArgs(_Immutable):
1562
- """The args for a ParamSpec object.
1563
-
1564
- Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.
1565
-
1566
- ParamSpecArgs objects have a reference back to their ParamSpec:
1567
-
1568
- P.args.__origin__ is P
1569
-
1570
- This type is meant for runtime introspection and has no special meaning to
1571
- static type checkers.
1572
- """
1573
- def __init__(self, origin):
1574
- self.__origin__ = origin
1575
-
1576
- def __repr__(self):
1577
- return f"{self.__origin__.__name__}.args"
1578
-
1579
- def __eq__(self, other):
1580
- if not isinstance(other, ParamSpecArgs):
1581
- return NotImplemented
1582
- return self.__origin__ == other.__origin__
1583
-
1584
- class ParamSpecKwargs(_Immutable):
1585
- """The kwargs for a ParamSpec object.
1586
-
1587
- Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs.
1588
-
1589
- ParamSpecKwargs objects have a reference back to their ParamSpec:
1590
-
1591
- P.kwargs.__origin__ is P
1592
-
1593
- This type is meant for runtime introspection and has no special meaning to
1594
- static type checkers.
1595
- """
1596
- def __init__(self, origin):
1597
- self.__origin__ = origin
1598
-
1599
- def __repr__(self):
1600
- return f"{self.__origin__.__name__}.kwargs"
1601
-
1602
- def __eq__(self, other):
1603
- if not isinstance(other, ParamSpecKwargs):
1604
- return NotImplemented
1605
- return self.__origin__ == other.__origin__
1606
-
1607
-
1608
- if _PEP_696_IMPLEMENTED:
1609
- from typing import ParamSpec
1610
-
1611
- # 3.10+
1612
- elif hasattr(typing, 'ParamSpec'):
1613
-
1614
- # Add default parameter - PEP 696
1615
- class ParamSpec(metaclass=_TypeVarLikeMeta):
1616
- """Parameter specification."""
1617
-
1618
- _backported_typevarlike = typing.ParamSpec
1619
-
1620
- def __new__(cls, name, *, bound=None,
1621
- covariant=False, contravariant=False,
1622
- infer_variance=False, default=NoDefault):
1623
- if hasattr(typing, "TypeAliasType"):
1624
- # PEP 695 implemented, can pass infer_variance to typing.TypeVar
1625
- paramspec = typing.ParamSpec(name, bound=bound,
1626
- covariant=covariant,
1627
- contravariant=contravariant,
1628
- infer_variance=infer_variance)
1629
- else:
1630
- paramspec = typing.ParamSpec(name, bound=bound,
1631
- covariant=covariant,
1632
- contravariant=contravariant)
1633
- paramspec.__infer_variance__ = infer_variance
1634
-
1635
- _set_default(paramspec, default)
1636
- _set_module(paramspec)
1637
-
1638
- def _paramspec_prepare_subst(alias, args):
1639
- params = alias.__parameters__
1640
- i = params.index(paramspec)
1641
- if i == len(args) and paramspec.has_default():
1642
- args = [*args, paramspec.__default__]
1643
- if i >= len(args):
1644
- raise TypeError(f"Too few arguments for {alias}")
1645
- # Special case where Z[[int, str, bool]] == Z[int, str, bool] in PEP 612.
1646
- if len(params) == 1 and not typing._is_param_expr(args[0]):
1647
- assert i == 0
1648
- args = (args,)
1649
- # Convert lists to tuples to help other libraries cache the results.
1650
- elif isinstance(args[i], list):
1651
- args = (*args[:i], tuple(args[i]), *args[i + 1:])
1652
- return args
1653
-
1654
- paramspec.__typing_prepare_subst__ = _paramspec_prepare_subst
1655
- return paramspec
1656
-
1657
- def __init_subclass__(cls) -> None:
1658
- raise TypeError(f"type '{__name__}.ParamSpec' is not an acceptable base type")
1659
-
1660
- # 3.8-3.9
1661
- else:
1662
-
1663
- # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
1664
- class ParamSpec(list, _DefaultMixin):
1665
- """Parameter specification variable.
1666
-
1667
- Usage::
1668
-
1669
- P = ParamSpec('P')
1670
-
1671
- Parameter specification variables exist primarily for the benefit of static
1672
- type checkers. They are used to forward the parameter types of one
1673
- callable to another callable, a pattern commonly found in higher order
1674
- functions and decorators. They are only valid when used in ``Concatenate``,
1675
- or s the first argument to ``Callable``. In Python 3.10 and higher,
1676
- they are also supported in user-defined Generics at runtime.
1677
- See class Generic for more information on generic types. An
1678
- example for annotating a decorator::
1679
-
1680
- T = TypeVar('T')
1681
- P = ParamSpec('P')
1682
-
1683
- def add_logging(f: Callable[P, T]) -> Callable[P, T]:
1684
- '''A type-safe decorator to add logging to a function.'''
1685
- def inner(*args: P.args, **kwargs: P.kwargs) -> T:
1686
- logging.info(f'{f.__name__} was called')
1687
- return f(*args, **kwargs)
1688
- return inner
1689
-
1690
- @add_logging
1691
- def add_two(x: float, y: float) -> float:
1692
- '''Add two numbers together.'''
1693
- return x + y
1694
-
1695
- Parameter specification variables defined with covariant=True or
1696
- contravariant=True can be used to declare covariant or contravariant
1697
- generic types. These keyword arguments are valid, but their actual semantics
1698
- are yet to be decided. See PEP 612 for details.
1699
-
1700
- Parameter specification variables can be introspected. e.g.:
1701
-
1702
- P.__name__ == 'T'
1703
- P.__bound__ == None
1704
- P.__covariant__ == False
1705
- P.__contravariant__ == False
1706
-
1707
- Note that only parameter specification variables defined in global scope can
1708
- be pickled.
1709
- """
1710
-
1711
- # Trick Generic __parameters__.
1712
- __class__ = typing.TypeVar
1713
-
1714
- @property
1715
- def args(self):
1716
- return ParamSpecArgs(self)
1717
-
1718
- @property
1719
- def kwargs(self):
1720
- return ParamSpecKwargs(self)
1721
-
1722
- def __init__(self, name, *, bound=None, covariant=False, contravariant=False,
1723
- infer_variance=False, default=NoDefault):
1724
- list.__init__(self, [self])
1725
- self.__name__ = name
1726
- self.__covariant__ = bool(covariant)
1727
- self.__contravariant__ = bool(contravariant)
1728
- self.__infer_variance__ = bool(infer_variance)
1729
- if bound:
1730
- self.__bound__ = typing._type_check(bound, 'Bound must be a type.')
1731
- else:
1732
- self.__bound__ = None
1733
- _DefaultMixin.__init__(self, default)
1734
-
1735
- # for pickling:
1736
- def_mod = _caller()
1737
- if def_mod != 'typing_extensions':
1738
- self.__module__ = def_mod
1739
-
1740
- def __repr__(self):
1741
- if self.__infer_variance__:
1742
- prefix = ''
1743
- elif self.__covariant__:
1744
- prefix = '+'
1745
- elif self.__contravariant__:
1746
- prefix = '-'
1747
- else:
1748
- prefix = '~'
1749
- return prefix + self.__name__
1750
-
1751
- def __hash__(self):
1752
- return object.__hash__(self)
1753
-
1754
- def __eq__(self, other):
1755
- return self is other
1756
-
1757
- def __reduce__(self):
1758
- return self.__name__
1759
-
1760
- # Hack to get typing._type_check to pass.
1761
- def __call__(self, *args, **kwargs):
1762
- pass
1763
-
1764
-
1765
- # 3.8-3.9
1766
- if not hasattr(typing, 'Concatenate'):
1767
- # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
1768
- class _ConcatenateGenericAlias(list):
1769
-
1770
- # Trick Generic into looking into this for __parameters__.
1771
- __class__ = typing._GenericAlias
1772
-
1773
- # Flag in 3.8.
1774
- _special = False
1775
-
1776
- def __init__(self, origin, args):
1777
- super().__init__(args)
1778
- self.__origin__ = origin
1779
- self.__args__ = args
1780
-
1781
- def __repr__(self):
1782
- _type_repr = typing._type_repr
1783
- return (f'{_type_repr(self.__origin__)}'
1784
- f'[{", ".join(_type_repr(arg) for arg in self.__args__)}]')
1785
-
1786
- def __hash__(self):
1787
- return hash((self.__origin__, self.__args__))
1788
-
1789
- # Hack to get typing._type_check to pass in Generic.
1790
- def __call__(self, *args, **kwargs):
1791
- pass
1792
-
1793
- @property
1794
- def __parameters__(self):
1795
- return tuple(
1796
- tp for tp in self.__args__ if isinstance(tp, (typing.TypeVar, ParamSpec))
1797
- )
1798
-
1799
-
1800
- # 3.8-3.9
1801
- @typing._tp_cache
1802
- def _concatenate_getitem(self, parameters):
1803
- if parameters == ():
1804
- raise TypeError("Cannot take a Concatenate of no types.")
1805
- if not isinstance(parameters, tuple):
1806
- parameters = (parameters,)
1807
- if not isinstance(parameters[-1], ParamSpec):
1808
- raise TypeError("The last parameter to Concatenate should be a "
1809
- "ParamSpec variable.")
1810
- msg = "Concatenate[arg, ...]: each arg must be a type."
1811
- parameters = tuple(typing._type_check(p, msg) for p in parameters)
1812
- return _ConcatenateGenericAlias(self, parameters)
1813
-
1814
-
1815
- # 3.10+
1816
- if hasattr(typing, 'Concatenate'):
1817
- Concatenate = typing.Concatenate
1818
- _ConcatenateGenericAlias = typing._ConcatenateGenericAlias
1819
- # 3.9
1820
- elif sys.version_info[:2] >= (3, 9):
1821
- @_ExtensionsSpecialForm
1822
- def Concatenate(self, parameters):
1823
- """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
1824
- higher order function which adds, removes or transforms parameters of a
1825
- callable.
1826
-
1827
- For example::
1828
-
1829
- Callable[Concatenate[int, P], int]
1830
-
1831
- See PEP 612 for detailed information.
1832
- """
1833
- return _concatenate_getitem(self, parameters)
1834
- # 3.8
1835
- else:
1836
- class _ConcatenateForm(_ExtensionsSpecialForm, _root=True):
1837
- def __getitem__(self, parameters):
1838
- return _concatenate_getitem(self, parameters)
1839
-
1840
- Concatenate = _ConcatenateForm(
1841
- 'Concatenate',
1842
- doc="""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
1843
- higher order function which adds, removes or transforms parameters of a
1844
- callable.
1845
-
1846
- For example::
1847
-
1848
- Callable[Concatenate[int, P], int]
1849
-
1850
- See PEP 612 for detailed information.
1851
- """)
1852
-
1853
- # 3.10+
1854
- if hasattr(typing, 'TypeGuard'):
1855
- TypeGuard = typing.TypeGuard
1856
- # 3.9
1857
- elif sys.version_info[:2] >= (3, 9):
1858
- @_ExtensionsSpecialForm
1859
- def TypeGuard(self, parameters):
1860
- """Special typing form used to annotate the return type of a user-defined
1861
- type guard function. ``TypeGuard`` only accepts a single type argument.
1862
- At runtime, functions marked this way should return a boolean.
1863
-
1864
- ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
1865
- type checkers to determine a more precise type of an expression within a
1866
- program's code flow. Usually type narrowing is done by analyzing
1867
- conditional code flow and applying the narrowing to a block of code. The
1868
- conditional expression here is sometimes referred to as a "type guard".
1869
-
1870
- Sometimes it would be convenient to use a user-defined boolean function
1871
- as a type guard. Such a function should use ``TypeGuard[...]`` as its
1872
- return type to alert static type checkers to this intention.
1873
-
1874
- Using ``-> TypeGuard`` tells the static type checker that for a given
1875
- function:
1876
-
1877
- 1. The return value is a boolean.
1878
- 2. If the return value is ``True``, the type of its argument
1879
- is the type inside ``TypeGuard``.
1880
-
1881
- For example::
1882
-
1883
- def is_str(val: Union[str, float]):
1884
- # "isinstance" type guard
1885
- if isinstance(val, str):
1886
- # Type of ``val`` is narrowed to ``str``
1887
- ...
1888
- else:
1889
- # Else, type of ``val`` is narrowed to ``float``.
1890
- ...
1891
-
1892
- Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
1893
- form of ``TypeA`` (it can even be a wider form) and this may lead to
1894
- type-unsafe results. The main reason is to allow for things like
1895
- narrowing ``List[object]`` to ``List[str]`` even though the latter is not
1896
- a subtype of the former, since ``List`` is invariant. The responsibility of
1897
- writing type-safe type guards is left to the user.
1898
-
1899
- ``TypeGuard`` also works with type variables. For more information, see
1900
- PEP 647 (User-Defined Type Guards).
1901
- """
1902
- item = typing._type_check(parameters, f'{self} accepts only a single type.')
1903
- return typing._GenericAlias(self, (item,))
1904
- # 3.8
1905
- else:
1906
- class _TypeGuardForm(_ExtensionsSpecialForm, _root=True):
1907
- def __getitem__(self, parameters):
1908
- item = typing._type_check(parameters,
1909
- f'{self._name} accepts only a single type')
1910
- return typing._GenericAlias(self, (item,))
1911
-
1912
- TypeGuard = _TypeGuardForm(
1913
- 'TypeGuard',
1914
- doc="""Special typing form used to annotate the return type of a user-defined
1915
- type guard function. ``TypeGuard`` only accepts a single type argument.
1916
- At runtime, functions marked this way should return a boolean.
1917
-
1918
- ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
1919
- type checkers to determine a more precise type of an expression within a
1920
- program's code flow. Usually type narrowing is done by analyzing
1921
- conditional code flow and applying the narrowing to a block of code. The
1922
- conditional expression here is sometimes referred to as a "type guard".
1923
-
1924
- Sometimes it would be convenient to use a user-defined boolean function
1925
- as a type guard. Such a function should use ``TypeGuard[...]`` as its
1926
- return type to alert static type checkers to this intention.
1927
-
1928
- Using ``-> TypeGuard`` tells the static type checker that for a given
1929
- function:
1930
-
1931
- 1. The return value is a boolean.
1932
- 2. If the return value is ``True``, the type of its argument
1933
- is the type inside ``TypeGuard``.
1934
-
1935
- For example::
1936
-
1937
- def is_str(val: Union[str, float]):
1938
- # "isinstance" type guard
1939
- if isinstance(val, str):
1940
- # Type of ``val`` is narrowed to ``str``
1941
- ...
1942
- else:
1943
- # Else, type of ``val`` is narrowed to ``float``.
1944
- ...
1945
-
1946
- Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
1947
- form of ``TypeA`` (it can even be a wider form) and this may lead to
1948
- type-unsafe results. The main reason is to allow for things like
1949
- narrowing ``List[object]`` to ``List[str]`` even though the latter is not
1950
- a subtype of the former, since ``List`` is invariant. The responsibility of
1951
- writing type-safe type guards is left to the user.
1952
-
1953
- ``TypeGuard`` also works with type variables. For more information, see
1954
- PEP 647 (User-Defined Type Guards).
1955
- """)
1956
-
1957
- # 3.13+
1958
- if hasattr(typing, 'TypeIs'):
1959
- TypeIs = typing.TypeIs
1960
- # 3.9
1961
- elif sys.version_info[:2] >= (3, 9):
1962
- @_ExtensionsSpecialForm
1963
- def TypeIs(self, parameters):
1964
- """Special typing form used to annotate the return type of a user-defined
1965
- type narrower function. ``TypeIs`` only accepts a single type argument.
1966
- At runtime, functions marked this way should return a boolean.
1967
-
1968
- ``TypeIs`` aims to benefit *type narrowing* -- a technique used by static
1969
- type checkers to determine a more precise type of an expression within a
1970
- program's code flow. Usually type narrowing is done by analyzing
1971
- conditional code flow and applying the narrowing to a block of code. The
1972
- conditional expression here is sometimes referred to as a "type guard".
1973
-
1974
- Sometimes it would be convenient to use a user-defined boolean function
1975
- as a type guard. Such a function should use ``TypeIs[...]`` as its
1976
- return type to alert static type checkers to this intention.
1977
-
1978
- Using ``-> TypeIs`` tells the static type checker that for a given
1979
- function:
1980
-
1981
- 1. The return value is a boolean.
1982
- 2. If the return value is ``True``, the type of its argument
1983
- is the intersection of the type inside ``TypeGuard`` and the argument's
1984
- previously known type.
1985
-
1986
- For example::
1987
-
1988
- def is_awaitable(val: object) -> TypeIs[Awaitable[Any]]:
1989
- return hasattr(val, '__await__')
1990
-
1991
- def f(val: Union[int, Awaitable[int]]) -> int:
1992
- if is_awaitable(val):
1993
- assert_type(val, Awaitable[int])
1994
- else:
1995
- assert_type(val, int)
1996
-
1997
- ``TypeIs`` also works with type variables. For more information, see
1998
- PEP 742 (Narrowing types with TypeIs).
1999
- """
2000
- item = typing._type_check(parameters, f'{self} accepts only a single type.')
2001
- return typing._GenericAlias(self, (item,))
2002
- # 3.8
2003
- else:
2004
- class _TypeIsForm(_ExtensionsSpecialForm, _root=True):
2005
- def __getitem__(self, parameters):
2006
- item = typing._type_check(parameters,
2007
- f'{self._name} accepts only a single type')
2008
- return typing._GenericAlias(self, (item,))
2009
-
2010
- TypeIs = _TypeIsForm(
2011
- 'TypeIs',
2012
- doc="""Special typing form used to annotate the return type of a user-defined
2013
- type narrower function. ``TypeIs`` only accepts a single type argument.
2014
- At runtime, functions marked this way should return a boolean.
2015
-
2016
- ``TypeIs`` aims to benefit *type narrowing* -- a technique used by static
2017
- type checkers to determine a more precise type of an expression within a
2018
- program's code flow. Usually type narrowing is done by analyzing
2019
- conditional code flow and applying the narrowing to a block of code. The
2020
- conditional expression here is sometimes referred to as a "type guard".
2021
-
2022
- Sometimes it would be convenient to use a user-defined boolean function
2023
- as a type guard. Such a function should use ``TypeIs[...]`` as its
2024
- return type to alert static type checkers to this intention.
2025
-
2026
- Using ``-> TypeIs`` tells the static type checker that for a given
2027
- function:
2028
-
2029
- 1. The return value is a boolean.
2030
- 2. If the return value is ``True``, the type of its argument
2031
- is the intersection of the type inside ``TypeGuard`` and the argument's
2032
- previously known type.
2033
-
2034
- For example::
2035
-
2036
- def is_awaitable(val: object) -> TypeIs[Awaitable[Any]]:
2037
- return hasattr(val, '__await__')
2038
-
2039
- def f(val: Union[int, Awaitable[int]]) -> int:
2040
- if is_awaitable(val):
2041
- assert_type(val, Awaitable[int])
2042
- else:
2043
- assert_type(val, int)
2044
-
2045
- ``TypeIs`` also works with type variables. For more information, see
2046
- PEP 742 (Narrowing types with TypeIs).
2047
- """)
2048
-
2049
- # 3.14+?
2050
- if hasattr(typing, 'TypeExpr'):
2051
- TypeExpr = typing.TypeExpr
2052
- # 3.9
2053
- elif sys.version_info[:2] >= (3, 9):
2054
- class _TypeExprForm(_ExtensionsSpecialForm, _root=True):
2055
- # TypeExpr(X) is equivalent to X but indicates to the type checker
2056
- # that the object is a TypeExpr.
2057
- def __call__(self, obj, /):
2058
- return obj
2059
-
2060
- @_TypeExprForm
2061
- def TypeExpr(self, parameters):
2062
- """Special typing form used to represent a type expression.
2063
-
2064
- Usage:
2065
-
2066
- def cast[T](typ: TypeExpr[T], value: Any) -> T: ...
2067
-
2068
- reveal_type(cast(int, "x")) # int
2069
-
2070
- See PEP 747 for more information.
2071
- """
2072
- item = typing._type_check(parameters, f'{self} accepts only a single type.')
2073
- return typing._GenericAlias(self, (item,))
2074
- # 3.8
2075
- else:
2076
- class _TypeExprForm(_ExtensionsSpecialForm, _root=True):
2077
- def __getitem__(self, parameters):
2078
- item = typing._type_check(parameters,
2079
- f'{self._name} accepts only a single type')
2080
- return typing._GenericAlias(self, (item,))
2081
-
2082
- def __call__(self, obj, /):
2083
- return obj
2084
-
2085
- TypeExpr = _TypeExprForm(
2086
- 'TypeExpr',
2087
- doc="""Special typing form used to represent a type expression.
2088
-
2089
- Usage:
2090
-
2091
- def cast[T](typ: TypeExpr[T], value: Any) -> T: ...
2092
-
2093
- reveal_type(cast(int, "x")) # int
2094
-
2095
- See PEP 747 for more information.
2096
- """)
2097
-
2098
-
2099
- # Vendored from cpython typing._SpecialFrom
2100
- class _SpecialForm(typing._Final, _root=True):
2101
- __slots__ = ('_name', '__doc__', '_getitem')
2102
-
2103
- def __init__(self, getitem):
2104
- self._getitem = getitem
2105
- self._name = getitem.__name__
2106
- self.__doc__ = getitem.__doc__
2107
-
2108
- def __getattr__(self, item):
2109
- if item in {'__name__', '__qualname__'}:
2110
- return self._name
2111
-
2112
- raise AttributeError(item)
2113
-
2114
- def __mro_entries__(self, bases):
2115
- raise TypeError(f"Cannot subclass {self!r}")
2116
-
2117
- def __repr__(self):
2118
- return f'typing_extensions.{self._name}'
2119
-
2120
- def __reduce__(self):
2121
- return self._name
2122
-
2123
- def __call__(self, *args, **kwds):
2124
- raise TypeError(f"Cannot instantiate {self!r}")
2125
-
2126
- def __or__(self, other):
2127
- return typing.Union[self, other]
2128
-
2129
- def __ror__(self, other):
2130
- return typing.Union[other, self]
2131
-
2132
- def __instancecheck__(self, obj):
2133
- raise TypeError(f"{self} cannot be used with isinstance()")
2134
-
2135
- def __subclasscheck__(self, cls):
2136
- raise TypeError(f"{self} cannot be used with issubclass()")
2137
-
2138
- @typing._tp_cache
2139
- def __getitem__(self, parameters):
2140
- return self._getitem(self, parameters)
2141
-
2142
-
2143
- if hasattr(typing, "LiteralString"): # 3.11+
2144
- LiteralString = typing.LiteralString
2145
- else:
2146
- @_SpecialForm
2147
- def LiteralString(self, params):
2148
- """Represents an arbitrary literal string.
2149
-
2150
- Example::
2151
-
2152
- from typing_extensions import LiteralString
2153
-
2154
- def query(sql: LiteralString) -> ...:
2155
- ...
2156
-
2157
- query("SELECT * FROM table") # ok
2158
- query(f"SELECT * FROM {input()}") # not ok
2159
-
2160
- See PEP 675 for details.
2161
-
2162
- """
2163
- raise TypeError(f"{self} is not subscriptable")
2164
-
2165
-
2166
- if hasattr(typing, "Self"): # 3.11+
2167
- Self = typing.Self
2168
- else:
2169
- @_SpecialForm
2170
- def Self(self, params):
2171
- """Used to spell the type of "self" in classes.
2172
-
2173
- Example::
2174
-
2175
- from typing import Self
2176
-
2177
- class ReturnsSelf:
2178
- def parse(self, data: bytes) -> Self:
2179
- ...
2180
- return self
2181
-
2182
- """
2183
-
2184
- raise TypeError(f"{self} is not subscriptable")
2185
-
2186
-
2187
- if hasattr(typing, "Never"): # 3.11+
2188
- Never = typing.Never
2189
- else:
2190
- @_SpecialForm
2191
- def Never(self, params):
2192
- """The bottom type, a type that has no members.
2193
-
2194
- This can be used to define a function that should never be
2195
- called, or a function that never returns::
2196
-
2197
- from typing_extensions import Never
2198
-
2199
- def never_call_me(arg: Never) -> None:
2200
- pass
2201
-
2202
- def int_or_str(arg: int | str) -> None:
2203
- never_call_me(arg) # type checker error
2204
- match arg:
2205
- case int():
2206
- print("It's an int")
2207
- case str():
2208
- print("It's a str")
2209
- case _:
2210
- never_call_me(arg) # ok, arg is of type Never
2211
-
2212
- """
2213
-
2214
- raise TypeError(f"{self} is not subscriptable")
2215
-
2216
-
2217
- if hasattr(typing, 'Required'): # 3.11+
2218
- Required = typing.Required
2219
- NotRequired = typing.NotRequired
2220
- elif sys.version_info[:2] >= (3, 9): # 3.9-3.10
2221
- @_ExtensionsSpecialForm
2222
- def Required(self, parameters):
2223
- """A special typing construct to mark a key of a total=False TypedDict
2224
- as required. For example:
2225
-
2226
- class Movie(TypedDict, total=False):
2227
- title: Required[str]
2228
- year: int
2229
-
2230
- m = Movie(
2231
- title='The Matrix', # typechecker error if key is omitted
2232
- year=1999,
2233
- )
2234
-
2235
- There is no runtime checking that a required key is actually provided
2236
- when instantiating a related TypedDict.
2237
- """
2238
- item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
2239
- return typing._GenericAlias(self, (item,))
2240
-
2241
- @_ExtensionsSpecialForm
2242
- def NotRequired(self, parameters):
2243
- """A special typing construct to mark a key of a TypedDict as
2244
- potentially missing. For example:
2245
-
2246
- class Movie(TypedDict):
2247
- title: str
2248
- year: NotRequired[int]
2249
-
2250
- m = Movie(
2251
- title='The Matrix', # typechecker error if key is omitted
2252
- year=1999,
2253
- )
2254
- """
2255
- item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
2256
- return typing._GenericAlias(self, (item,))
2257
-
2258
- else: # 3.8
2259
- class _RequiredForm(_ExtensionsSpecialForm, _root=True):
2260
- def __getitem__(self, parameters):
2261
- item = typing._type_check(parameters,
2262
- f'{self._name} accepts only a single type.')
2263
- return typing._GenericAlias(self, (item,))
2264
-
2265
- Required = _RequiredForm(
2266
- 'Required',
2267
- doc="""A special typing construct to mark a key of a total=False TypedDict
2268
- as required. For example:
2269
-
2270
- class Movie(TypedDict, total=False):
2271
- title: Required[str]
2272
- year: int
2273
-
2274
- m = Movie(
2275
- title='The Matrix', # typechecker error if key is omitted
2276
- year=1999,
2277
- )
2278
-
2279
- There is no runtime checking that a required key is actually provided
2280
- when instantiating a related TypedDict.
2281
- """)
2282
- NotRequired = _RequiredForm(
2283
- 'NotRequired',
2284
- doc="""A special typing construct to mark a key of a TypedDict as
2285
- potentially missing. For example:
2286
-
2287
- class Movie(TypedDict):
2288
- title: str
2289
- year: NotRequired[int]
2290
-
2291
- m = Movie(
2292
- title='The Matrix', # typechecker error if key is omitted
2293
- year=1999,
2294
- )
2295
- """)
2296
-
2297
-
2298
- if hasattr(typing, 'ReadOnly'):
2299
- ReadOnly = typing.ReadOnly
2300
- elif sys.version_info[:2] >= (3, 9): # 3.9-3.12
2301
- @_ExtensionsSpecialForm
2302
- def ReadOnly(self, parameters):
2303
- """A special typing construct to mark an item of a TypedDict as read-only.
2304
-
2305
- For example:
2306
-
2307
- class Movie(TypedDict):
2308
- title: ReadOnly[str]
2309
- year: int
2310
-
2311
- def mutate_movie(m: Movie) -> None:
2312
- m["year"] = 1992 # allowed
2313
- m["title"] = "The Matrix" # typechecker error
2314
-
2315
- There is no runtime checking for this property.
2316
- """
2317
- item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
2318
- return typing._GenericAlias(self, (item,))
2319
-
2320
- else: # 3.8
2321
- class _ReadOnlyForm(_ExtensionsSpecialForm, _root=True):
2322
- def __getitem__(self, parameters):
2323
- item = typing._type_check(parameters,
2324
- f'{self._name} accepts only a single type.')
2325
- return typing._GenericAlias(self, (item,))
2326
-
2327
- ReadOnly = _ReadOnlyForm(
2328
- 'ReadOnly',
2329
- doc="""A special typing construct to mark a key of a TypedDict as read-only.
2330
-
2331
- For example:
2332
-
2333
- class Movie(TypedDict):
2334
- title: ReadOnly[str]
2335
- year: int
2336
-
2337
- def mutate_movie(m: Movie) -> None:
2338
- m["year"] = 1992 # allowed
2339
- m["title"] = "The Matrix" # typechecker error
2340
-
2341
- There is no runtime checking for this propery.
2342
- """)
2343
-
2344
-
2345
- _UNPACK_DOC = """\
2346
- Type unpack operator.
2347
-
2348
- The type unpack operator takes the child types from some container type,
2349
- such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'. For
2350
- example:
2351
-
2352
- # For some generic class `Foo`:
2353
- Foo[Unpack[tuple[int, str]]] # Equivalent to Foo[int, str]
2354
-
2355
- Ts = TypeVarTuple('Ts')
2356
- # Specifies that `Bar` is generic in an arbitrary number of types.
2357
- # (Think of `Ts` as a tuple of an arbitrary number of individual
2358
- # `TypeVar`s, which the `Unpack` is 'pulling out' directly into the
2359
- # `Generic[]`.)
2360
- class Bar(Generic[Unpack[Ts]]): ...
2361
- Bar[int] # Valid
2362
- Bar[int, str] # Also valid
2363
-
2364
- From Python 3.11, this can also be done using the `*` operator:
2365
-
2366
- Foo[*tuple[int, str]]
2367
- class Bar(Generic[*Ts]): ...
2368
-
2369
- The operator can also be used along with a `TypedDict` to annotate
2370
- `**kwargs` in a function signature. For instance:
2371
-
2372
- class Movie(TypedDict):
2373
- name: str
2374
- year: int
2375
-
2376
- # This function expects two keyword arguments - *name* of type `str` and
2377
- # *year* of type `int`.
2378
- def foo(**kwargs: Unpack[Movie]): ...
2379
-
2380
- Note that there is only some runtime checking of this operator. Not
2381
- everything the runtime allows may be accepted by static type checkers.
2382
-
2383
- For more information, see PEP 646 and PEP 692.
2384
- """
2385
-
2386
-
2387
- if sys.version_info >= (3, 12): # PEP 692 changed the repr of Unpack[]
2388
- Unpack = typing.Unpack
2389
-
2390
- def _is_unpack(obj):
2391
- return get_origin(obj) is Unpack
2392
-
2393
- elif sys.version_info[:2] >= (3, 9): # 3.9+
2394
- class _UnpackSpecialForm(_ExtensionsSpecialForm, _root=True):
2395
- def __init__(self, getitem):
2396
- super().__init__(getitem)
2397
- self.__doc__ = _UNPACK_DOC
2398
-
2399
- class _UnpackAlias(typing._GenericAlias, _root=True):
2400
- __class__ = typing.TypeVar
2401
-
2402
- @property
2403
- def __typing_unpacked_tuple_args__(self):
2404
- assert self.__origin__ is Unpack
2405
- assert len(self.__args__) == 1
2406
- arg, = self.__args__
2407
- if isinstance(arg, (typing._GenericAlias, _types.GenericAlias)):
2408
- if arg.__origin__ is not tuple:
2409
- raise TypeError("Unpack[...] must be used with a tuple type")
2410
- return arg.__args__
2411
- return None
2412
-
2413
- @_UnpackSpecialForm
2414
- def Unpack(self, parameters):
2415
- item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
2416
- return _UnpackAlias(self, (item,))
2417
-
2418
- def _is_unpack(obj):
2419
- return isinstance(obj, _UnpackAlias)
2420
-
2421
- else: # 3.8
2422
- class _UnpackAlias(typing._GenericAlias, _root=True):
2423
- __class__ = typing.TypeVar
2424
-
2425
- class _UnpackForm(_ExtensionsSpecialForm, _root=True):
2426
- def __getitem__(self, parameters):
2427
- item = typing._type_check(parameters,
2428
- f'{self._name} accepts only a single type.')
2429
- return _UnpackAlias(self, (item,))
2430
-
2431
- Unpack = _UnpackForm('Unpack', doc=_UNPACK_DOC)
2432
-
2433
- def _is_unpack(obj):
2434
- return isinstance(obj, _UnpackAlias)
2435
-
2436
-
2437
- if _PEP_696_IMPLEMENTED:
2438
- from typing import TypeVarTuple
2439
-
2440
- elif hasattr(typing, "TypeVarTuple"): # 3.11+
2441
-
2442
- def _unpack_args(*args):
2443
- newargs = []
2444
- for arg in args:
2445
- subargs = getattr(arg, '__typing_unpacked_tuple_args__', None)
2446
- if subargs is not None and not (subargs and subargs[-1] is ...):
2447
- newargs.extend(subargs)
2448
- else:
2449
- newargs.append(arg)
2450
- return newargs
2451
-
2452
- # Add default parameter - PEP 696
2453
- class TypeVarTuple(metaclass=_TypeVarLikeMeta):
2454
- """Type variable tuple."""
2455
-
2456
- _backported_typevarlike = typing.TypeVarTuple
2457
-
2458
- def __new__(cls, name, *, default=NoDefault):
2459
- tvt = typing.TypeVarTuple(name)
2460
- _set_default(tvt, default)
2461
- _set_module(tvt)
2462
-
2463
- def _typevartuple_prepare_subst(alias, args):
2464
- params = alias.__parameters__
2465
- typevartuple_index = params.index(tvt)
2466
- for param in params[typevartuple_index + 1:]:
2467
- if isinstance(param, TypeVarTuple):
2468
- raise TypeError(
2469
- f"More than one TypeVarTuple parameter in {alias}"
2470
- )
2471
-
2472
- alen = len(args)
2473
- plen = len(params)
2474
- left = typevartuple_index
2475
- right = plen - typevartuple_index - 1
2476
- var_tuple_index = None
2477
- fillarg = None
2478
- for k, arg in enumerate(args):
2479
- if not isinstance(arg, type):
2480
- subargs = getattr(arg, '__typing_unpacked_tuple_args__', None)
2481
- if subargs and len(subargs) == 2 and subargs[-1] is ...:
2482
- if var_tuple_index is not None:
2483
- raise TypeError(
2484
- "More than one unpacked "
2485
- "arbitrary-length tuple argument"
2486
- )
2487
- var_tuple_index = k
2488
- fillarg = subargs[0]
2489
- if var_tuple_index is not None:
2490
- left = min(left, var_tuple_index)
2491
- right = min(right, alen - var_tuple_index - 1)
2492
- elif left + right > alen:
2493
- raise TypeError(f"Too few arguments for {alias};"
2494
- f" actual {alen}, expected at least {plen - 1}")
2495
- if left == alen - right and tvt.has_default():
2496
- replacement = _unpack_args(tvt.__default__)
2497
- else:
2498
- replacement = args[left: alen - right]
2499
-
2500
- return (
2501
- *args[:left],
2502
- *([fillarg] * (typevartuple_index - left)),
2503
- replacement,
2504
- *([fillarg] * (plen - right - left - typevartuple_index - 1)),
2505
- *args[alen - right:],
2506
- )
2507
-
2508
- tvt.__typing_prepare_subst__ = _typevartuple_prepare_subst
2509
- return tvt
2510
-
2511
- def __init_subclass__(self, *args, **kwds):
2512
- raise TypeError("Cannot subclass special typing classes")
2513
-
2514
- else: # <=3.10
2515
- class TypeVarTuple(_DefaultMixin):
2516
- """Type variable tuple.
2517
-
2518
- Usage::
2519
-
2520
- Ts = TypeVarTuple('Ts')
2521
-
2522
- In the same way that a normal type variable is a stand-in for a single
2523
- type such as ``int``, a type variable *tuple* is a stand-in for a *tuple*
2524
- type such as ``Tuple[int, str]``.
2525
-
2526
- Type variable tuples can be used in ``Generic`` declarations.
2527
- Consider the following example::
2528
-
2529
- class Array(Generic[*Ts]): ...
2530
-
2531
- The ``Ts`` type variable tuple here behaves like ``tuple[T1, T2]``,
2532
- where ``T1`` and ``T2`` are type variables. To use these type variables
2533
- as type parameters of ``Array``, we must *unpack* the type variable tuple using
2534
- the star operator: ``*Ts``. The signature of ``Array`` then behaves
2535
- as if we had simply written ``class Array(Generic[T1, T2]): ...``.
2536
- In contrast to ``Generic[T1, T2]``, however, ``Generic[*Shape]`` allows
2537
- us to parameterise the class with an *arbitrary* number of type parameters.
2538
-
2539
- Type variable tuples can be used anywhere a normal ``TypeVar`` can.
2540
- This includes class definitions, as shown above, as well as function
2541
- signatures and variable annotations::
2542
-
2543
- class Array(Generic[*Ts]):
2544
-
2545
- def __init__(self, shape: Tuple[*Ts]):
2546
- self._shape: Tuple[*Ts] = shape
2547
-
2548
- def get_shape(self) -> Tuple[*Ts]:
2549
- return self._shape
2550
-
2551
- shape = (Height(480), Width(640))
2552
- x: Array[Height, Width] = Array(shape)
2553
- y = abs(x) # Inferred type is Array[Height, Width]
2554
- z = x + x # ... is Array[Height, Width]
2555
- x.get_shape() # ... is tuple[Height, Width]
2556
-
2557
- """
2558
-
2559
- # Trick Generic __parameters__.
2560
- __class__ = typing.TypeVar
2561
-
2562
- def __iter__(self):
2563
- yield self.__unpacked__
2564
-
2565
- def __init__(self, name, *, default=NoDefault):
2566
- self.__name__ = name
2567
- _DefaultMixin.__init__(self, default)
2568
-
2569
- # for pickling:
2570
- def_mod = _caller()
2571
- if def_mod != 'typing_extensions':
2572
- self.__module__ = def_mod
2573
-
2574
- self.__unpacked__ = Unpack[self]
2575
-
2576
- def __repr__(self):
2577
- return self.__name__
2578
-
2579
- def __hash__(self):
2580
- return object.__hash__(self)
2581
-
2582
- def __eq__(self, other):
2583
- return self is other
2584
-
2585
- def __reduce__(self):
2586
- return self.__name__
2587
-
2588
- def __init_subclass__(self, *args, **kwds):
2589
- if '_root' not in kwds:
2590
- raise TypeError("Cannot subclass special typing classes")
2591
-
2592
-
2593
- if hasattr(typing, "reveal_type"): # 3.11+
2594
- reveal_type = typing.reveal_type
2595
- else: # <=3.10
2596
- def reveal_type(obj: T, /) -> T:
2597
- """Reveal the inferred type of a variable.
2598
-
2599
- When a static type checker encounters a call to ``reveal_type()``,
2600
- it will emit the inferred type of the argument::
2601
-
2602
- x: int = 1
2603
- reveal_type(x)
2604
-
2605
- Running a static type checker (e.g., ``mypy``) on this example
2606
- will produce output similar to 'Revealed type is "builtins.int"'.
2607
-
2608
- At runtime, the function prints the runtime type of the
2609
- argument and returns it unchanged.
2610
-
2611
- """
2612
- print(f"Runtime type is {type(obj).__name__!r}", file=sys.stderr)
2613
- return obj
2614
-
2615
-
2616
- if hasattr(typing, "_ASSERT_NEVER_REPR_MAX_LENGTH"): # 3.11+
2617
- _ASSERT_NEVER_REPR_MAX_LENGTH = typing._ASSERT_NEVER_REPR_MAX_LENGTH
2618
- else: # <=3.10
2619
- _ASSERT_NEVER_REPR_MAX_LENGTH = 100
2620
-
2621
-
2622
- if hasattr(typing, "assert_never"): # 3.11+
2623
- assert_never = typing.assert_never
2624
- else: # <=3.10
2625
- def assert_never(arg: Never, /) -> Never:
2626
- """Assert to the type checker that a line of code is unreachable.
2627
-
2628
- Example::
2629
-
2630
- def int_or_str(arg: int | str) -> None:
2631
- match arg:
2632
- case int():
2633
- print("It's an int")
2634
- case str():
2635
- print("It's a str")
2636
- case _:
2637
- assert_never(arg)
2638
-
2639
- If a type checker finds that a call to assert_never() is
2640
- reachable, it will emit an error.
2641
-
2642
- At runtime, this throws an exception when called.
2643
-
2644
- """
2645
- value = repr(arg)
2646
- if len(value) > _ASSERT_NEVER_REPR_MAX_LENGTH:
2647
- value = value[:_ASSERT_NEVER_REPR_MAX_LENGTH] + '...'
2648
- raise AssertionError(f"Expected code to be unreachable, but got: {value}")
2649
-
2650
-
2651
- if sys.version_info >= (3, 12): # 3.12+
2652
- # dataclass_transform exists in 3.11 but lacks the frozen_default parameter
2653
- dataclass_transform = typing.dataclass_transform
2654
- else: # <=3.11
2655
- def dataclass_transform(
2656
- *,
2657
- eq_default: bool = True,
2658
- order_default: bool = False,
2659
- kw_only_default: bool = False,
2660
- frozen_default: bool = False,
2661
- field_specifiers: typing.Tuple[
2662
- typing.Union[typing.Type[typing.Any], typing.Callable[..., typing.Any]],
2663
- ...
2664
- ] = (),
2665
- **kwargs: typing.Any,
2666
- ) -> typing.Callable[[T], T]:
2667
- """Decorator that marks a function, class, or metaclass as providing
2668
- dataclass-like behavior.
2669
-
2670
- Example:
2671
-
2672
- from typing_extensions import dataclass_transform
2673
-
2674
- _T = TypeVar("_T")
2675
-
2676
- # Used on a decorator function
2677
- @dataclass_transform()
2678
- def create_model(cls: type[_T]) -> type[_T]:
2679
- ...
2680
- return cls
2681
-
2682
- @create_model
2683
- class CustomerModel:
2684
- id: int
2685
- name: str
2686
-
2687
- # Used on a base class
2688
- @dataclass_transform()
2689
- class ModelBase: ...
2690
-
2691
- class CustomerModel(ModelBase):
2692
- id: int
2693
- name: str
2694
-
2695
- # Used on a metaclass
2696
- @dataclass_transform()
2697
- class ModelMeta(type): ...
2698
-
2699
- class ModelBase(metaclass=ModelMeta): ...
2700
-
2701
- class CustomerModel(ModelBase):
2702
- id: int
2703
- name: str
2704
-
2705
- Each of the ``CustomerModel`` classes defined in this example will now
2706
- behave similarly to a dataclass created with the ``@dataclasses.dataclass``
2707
- decorator. For example, the type checker will synthesize an ``__init__``
2708
- method.
2709
-
2710
- The arguments to this decorator can be used to customize this behavior:
2711
- - ``eq_default`` indicates whether the ``eq`` parameter is assumed to be
2712
- True or False if it is omitted by the caller.
2713
- - ``order_default`` indicates whether the ``order`` parameter is
2714
- assumed to be True or False if it is omitted by the caller.
2715
- - ``kw_only_default`` indicates whether the ``kw_only`` parameter is
2716
- assumed to be True or False if it is omitted by the caller.
2717
- - ``frozen_default`` indicates whether the ``frozen`` parameter is
2718
- assumed to be True or False if it is omitted by the caller.
2719
- - ``field_specifiers`` specifies a static list of supported classes
2720
- or functions that describe fields, similar to ``dataclasses.field()``.
2721
-
2722
- At runtime, this decorator records its arguments in the
2723
- ``__dataclass_transform__`` attribute on the decorated object.
2724
-
2725
- See PEP 681 for details.
2726
-
2727
- """
2728
- def decorator(cls_or_fn):
2729
- cls_or_fn.__dataclass_transform__ = {
2730
- "eq_default": eq_default,
2731
- "order_default": order_default,
2732
- "kw_only_default": kw_only_default,
2733
- "frozen_default": frozen_default,
2734
- "field_specifiers": field_specifiers,
2735
- "kwargs": kwargs,
2736
- }
2737
- return cls_or_fn
2738
- return decorator
2739
-
2740
-
2741
- if hasattr(typing, "override"): # 3.12+
2742
- override = typing.override
2743
- else: # <=3.11
2744
- _F = typing.TypeVar("_F", bound=typing.Callable[..., typing.Any])
2745
-
2746
- def override(arg: _F, /) -> _F:
2747
- """Indicate that a method is intended to override a method in a base class.
2748
-
2749
- Usage:
2750
-
2751
- class Base:
2752
- def method(self) -> None:
2753
- pass
2754
-
2755
- class Child(Base):
2756
- @override
2757
- def method(self) -> None:
2758
- super().method()
2759
-
2760
- When this decorator is applied to a method, the type checker will
2761
- validate that it overrides a method with the same name on a base class.
2762
- This helps prevent bugs that may occur when a base class is changed
2763
- without an equivalent change to a child class.
2764
-
2765
- There is no runtime checking of these properties. The decorator
2766
- sets the ``__override__`` attribute to ``True`` on the decorated object
2767
- to allow runtime introspection.
2768
-
2769
- See PEP 698 for details.
2770
-
2771
- """
2772
- try:
2773
- arg.__override__ = True
2774
- except (AttributeError, TypeError):
2775
- # Skip the attribute silently if it is not writable.
2776
- # AttributeError happens if the object has __slots__ or a
2777
- # read-only property, TypeError if it's a builtin class.
2778
- pass
2779
- return arg
2780
-
2781
-
2782
- if hasattr(warnings, "deprecated"):
2783
- deprecated = warnings.deprecated
2784
- else:
2785
- _T = typing.TypeVar("_T")
2786
-
2787
- class deprecated:
2788
- """Indicate that a class, function or overload is deprecated.
2789
-
2790
- When this decorator is applied to an object, the type checker
2791
- will generate a diagnostic on usage of the deprecated object.
2792
-
2793
- Usage:
2794
-
2795
- @deprecated("Use B instead")
2796
- class A:
2797
- pass
2798
-
2799
- @deprecated("Use g instead")
2800
- def f():
2801
- pass
2802
-
2803
- @overload
2804
- @deprecated("int support is deprecated")
2805
- def g(x: int) -> int: ...
2806
- @overload
2807
- def g(x: str) -> int: ...
2808
-
2809
- The warning specified by *category* will be emitted at runtime
2810
- on use of deprecated objects. For functions, that happens on calls;
2811
- for classes, on instantiation and on creation of subclasses.
2812
- If the *category* is ``None``, no warning is emitted at runtime.
2813
- The *stacklevel* determines where the
2814
- warning is emitted. If it is ``1`` (the default), the warning
2815
- is emitted at the direct caller of the deprecated object; if it
2816
- is higher, it is emitted further up the stack.
2817
- Static type checker behavior is not affected by the *category*
2818
- and *stacklevel* arguments.
2819
-
2820
- The deprecation message passed to the decorator is saved in the
2821
- ``__deprecated__`` attribute on the decorated object.
2822
- If applied to an overload, the decorator
2823
- must be after the ``@overload`` decorator for the attribute to
2824
- exist on the overload as returned by ``get_overloads()``.
2825
-
2826
- See PEP 702 for details.
2827
-
2828
- """
2829
- def __init__(
2830
- self,
2831
- message: str,
2832
- /,
2833
- *,
2834
- category: typing.Optional[typing.Type[Warning]] = DeprecationWarning,
2835
- stacklevel: int = 1,
2836
- ) -> None:
2837
- if not isinstance(message, str):
2838
- raise TypeError(
2839
- "Expected an object of type str for 'message', not "
2840
- f"{type(message).__name__!r}"
2841
- )
2842
- self.message = message
2843
- self.category = category
2844
- self.stacklevel = stacklevel
2845
-
2846
- def __call__(self, arg: _T, /) -> _T:
2847
- # Make sure the inner functions created below don't
2848
- # retain a reference to self.
2849
- msg = self.message
2850
- category = self.category
2851
- stacklevel = self.stacklevel
2852
- if category is None:
2853
- arg.__deprecated__ = msg
2854
- return arg
2855
- elif isinstance(arg, type):
2856
- import functools
2857
- from types import MethodType
2858
-
2859
- original_new = arg.__new__
2860
-
2861
- @functools.wraps(original_new)
2862
- def __new__(cls, *args, **kwargs):
2863
- if cls is arg:
2864
- warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
2865
- if original_new is not object.__new__:
2866
- return original_new(cls, *args, **kwargs)
2867
- # Mirrors a similar check in object.__new__.
2868
- elif cls.__init__ is object.__init__ and (args or kwargs):
2869
- raise TypeError(f"{cls.__name__}() takes no arguments")
2870
- else:
2871
- return original_new(cls)
2872
-
2873
- arg.__new__ = staticmethod(__new__)
2874
-
2875
- original_init_subclass = arg.__init_subclass__
2876
- # We need slightly different behavior if __init_subclass__
2877
- # is a bound method (likely if it was implemented in Python)
2878
- if isinstance(original_init_subclass, MethodType):
2879
- original_init_subclass = original_init_subclass.__func__
2880
-
2881
- @functools.wraps(original_init_subclass)
2882
- def __init_subclass__(*args, **kwargs):
2883
- warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
2884
- return original_init_subclass(*args, **kwargs)
2885
-
2886
- arg.__init_subclass__ = classmethod(__init_subclass__)
2887
- # Or otherwise, which likely means it's a builtin such as
2888
- # object's implementation of __init_subclass__.
2889
- else:
2890
- @functools.wraps(original_init_subclass)
2891
- def __init_subclass__(*args, **kwargs):
2892
- warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
2893
- return original_init_subclass(*args, **kwargs)
2894
-
2895
- arg.__init_subclass__ = __init_subclass__
2896
-
2897
- arg.__deprecated__ = __new__.__deprecated__ = msg
2898
- __init_subclass__.__deprecated__ = msg
2899
- return arg
2900
- elif callable(arg):
2901
- import functools
2902
-
2903
- @functools.wraps(arg)
2904
- def wrapper(*args, **kwargs):
2905
- warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
2906
- return arg(*args, **kwargs)
2907
-
2908
- arg.__deprecated__ = wrapper.__deprecated__ = msg
2909
- return wrapper
2910
- else:
2911
- raise TypeError(
2912
- "@deprecated decorator with non-None category must be applied to "
2913
- f"a class or callable, not {arg!r}"
2914
- )
2915
-
2916
-
2917
- # We have to do some monkey patching to deal with the dual nature of
2918
- # Unpack/TypeVarTuple:
2919
- # - We want Unpack to be a kind of TypeVar so it gets accepted in
2920
- # Generic[Unpack[Ts]]
2921
- # - We want it to *not* be treated as a TypeVar for the purposes of
2922
- # counting generic parameters, so that when we subscript a generic,
2923
- # the runtime doesn't try to substitute the Unpack with the subscripted type.
2924
- if not hasattr(typing, "TypeVarTuple"):
2925
- def _check_generic(cls, parameters, elen=_marker):
2926
- """Check correct count for parameters of a generic cls (internal helper).
2927
-
2928
- This gives a nice error message in case of count mismatch.
2929
- """
2930
- if not elen:
2931
- raise TypeError(f"{cls} is not a generic class")
2932
- if elen is _marker:
2933
- if not hasattr(cls, "__parameters__") or not cls.__parameters__:
2934
- raise TypeError(f"{cls} is not a generic class")
2935
- elen = len(cls.__parameters__)
2936
- alen = len(parameters)
2937
- if alen != elen:
2938
- expect_val = elen
2939
- if hasattr(cls, "__parameters__"):
2940
- parameters = [p for p in cls.__parameters__ if not _is_unpack(p)]
2941
- num_tv_tuples = sum(isinstance(p, TypeVarTuple) for p in parameters)
2942
- if (num_tv_tuples > 0) and (alen >= elen - num_tv_tuples):
2943
- return
2944
-
2945
- # deal with TypeVarLike defaults
2946
- # required TypeVarLikes cannot appear after a defaulted one.
2947
- if alen < elen:
2948
- # since we validate TypeVarLike default in _collect_type_vars
2949
- # or _collect_parameters we can safely check parameters[alen]
2950
- if (
2951
- getattr(parameters[alen], '__default__', NoDefault)
2952
- is not NoDefault
2953
- ):
2954
- return
2955
-
2956
- num_default_tv = sum(getattr(p, '__default__', NoDefault)
2957
- is not NoDefault for p in parameters)
2958
-
2959
- elen -= num_default_tv
2960
-
2961
- expect_val = f"at least {elen}"
2962
-
2963
- things = "arguments" if sys.version_info >= (3, 10) else "parameters"
2964
- raise TypeError(f"Too {'many' if alen > elen else 'few'} {things}"
2965
- f" for {cls}; actual {alen}, expected {expect_val}")
2966
- else:
2967
- # Python 3.11+
2968
-
2969
- def _check_generic(cls, parameters, elen):
2970
- """Check correct count for parameters of a generic cls (internal helper).
2971
-
2972
- This gives a nice error message in case of count mismatch.
2973
- """
2974
- if not elen:
2975
- raise TypeError(f"{cls} is not a generic class")
2976
- alen = len(parameters)
2977
- if alen != elen:
2978
- expect_val = elen
2979
- if hasattr(cls, "__parameters__"):
2980
- parameters = [p for p in cls.__parameters__ if not _is_unpack(p)]
2981
-
2982
- # deal with TypeVarLike defaults
2983
- # required TypeVarLikes cannot appear after a defaulted one.
2984
- if alen < elen:
2985
- # since we validate TypeVarLike default in _collect_type_vars
2986
- # or _collect_parameters we can safely check parameters[alen]
2987
- if (
2988
- getattr(parameters[alen], '__default__', NoDefault)
2989
- is not NoDefault
2990
- ):
2991
- return
2992
-
2993
- num_default_tv = sum(getattr(p, '__default__', NoDefault)
2994
- is not NoDefault for p in parameters)
2995
-
2996
- elen -= num_default_tv
2997
-
2998
- expect_val = f"at least {elen}"
2999
-
3000
- raise TypeError(f"Too {'many' if alen > elen else 'few'} arguments"
3001
- f" for {cls}; actual {alen}, expected {expect_val}")
3002
-
3003
- if not _PEP_696_IMPLEMENTED:
3004
- typing._check_generic = _check_generic
3005
-
3006
-
3007
- def _has_generic_or_protocol_as_origin() -> bool:
3008
- try:
3009
- frame = sys._getframe(2)
3010
- # - Catch AttributeError: not all Python implementations have sys._getframe()
3011
- # - Catch ValueError: maybe we're called from an unexpected module
3012
- # and the call stack isn't deep enough
3013
- except (AttributeError, ValueError):
3014
- return False # err on the side of leniency
3015
- else:
3016
- # If we somehow get invoked from outside typing.py,
3017
- # also err on the side of leniency
3018
- if frame.f_globals.get("__name__") != "typing":
3019
- return False
3020
- origin = frame.f_locals.get("origin")
3021
- # Cannot use "in" because origin may be an object with a buggy __eq__ that
3022
- # throws an error.
3023
- return origin is typing.Generic or origin is Protocol or origin is typing.Protocol
3024
-
3025
-
3026
- _TYPEVARTUPLE_TYPES = {TypeVarTuple, getattr(typing, "TypeVarTuple", None)}
3027
-
3028
-
3029
- def _is_unpacked_typevartuple(x) -> bool:
3030
- if get_origin(x) is not Unpack:
3031
- return False
3032
- args = get_args(x)
3033
- return (
3034
- bool(args)
3035
- and len(args) == 1
3036
- and type(args[0]) in _TYPEVARTUPLE_TYPES
3037
- )
3038
-
3039
-
3040
- # Python 3.11+ _collect_type_vars was renamed to _collect_parameters
3041
- if hasattr(typing, '_collect_type_vars'):
3042
- def _collect_type_vars(types, typevar_types=None):
3043
- """Collect all type variable contained in types in order of
3044
- first appearance (lexicographic order). For example::
3045
-
3046
- _collect_type_vars((T, List[S, T])) == (T, S)
3047
- """
3048
- if typevar_types is None:
3049
- typevar_types = typing.TypeVar
3050
- tvars = []
3051
-
3052
- # A required TypeVarLike cannot appear after a TypeVarLike with a default
3053
- # if it was a direct call to `Generic[]` or `Protocol[]`
3054
- enforce_default_ordering = _has_generic_or_protocol_as_origin()
3055
- default_encountered = False
3056
-
3057
- # Also, a TypeVarLike with a default cannot appear after a TypeVarTuple
3058
- type_var_tuple_encountered = False
3059
-
3060
- for t in types:
3061
- if _is_unpacked_typevartuple(t):
3062
- type_var_tuple_encountered = True
3063
- elif isinstance(t, typevar_types) and t not in tvars:
3064
- if enforce_default_ordering:
3065
- has_default = getattr(t, '__default__', NoDefault) is not NoDefault
3066
- if has_default:
3067
- if type_var_tuple_encountered:
3068
- raise TypeError('Type parameter with a default'
3069
- ' follows TypeVarTuple')
3070
- default_encountered = True
3071
- elif default_encountered:
3072
- raise TypeError(f'Type parameter {t!r} without a default'
3073
- ' follows type parameter with a default')
3074
-
3075
- tvars.append(t)
3076
- if _should_collect_from_parameters(t):
3077
- tvars.extend([t for t in t.__parameters__ if t not in tvars])
3078
- return tuple(tvars)
3079
-
3080
- typing._collect_type_vars = _collect_type_vars
3081
- else:
3082
- def _collect_parameters(args):
3083
- """Collect all type variables and parameter specifications in args
3084
- in order of first appearance (lexicographic order).
3085
-
3086
- For example::
3087
-
3088
- assert _collect_parameters((T, Callable[P, T])) == (T, P)
3089
- """
3090
- parameters = []
3091
-
3092
- # A required TypeVarLike cannot appear after a TypeVarLike with default
3093
- # if it was a direct call to `Generic[]` or `Protocol[]`
3094
- enforce_default_ordering = _has_generic_or_protocol_as_origin()
3095
- default_encountered = False
3096
-
3097
- # Also, a TypeVarLike with a default cannot appear after a TypeVarTuple
3098
- type_var_tuple_encountered = False
3099
-
3100
- for t in args:
3101
- if isinstance(t, type):
3102
- # We don't want __parameters__ descriptor of a bare Python class.
3103
- pass
3104
- elif isinstance(t, tuple):
3105
- # `t` might be a tuple, when `ParamSpec` is substituted with
3106
- # `[T, int]`, or `[int, *Ts]`, etc.
3107
- for x in t:
3108
- for collected in _collect_parameters([x]):
3109
- if collected not in parameters:
3110
- parameters.append(collected)
3111
- elif hasattr(t, '__typing_subst__'):
3112
- if t not in parameters:
3113
- if enforce_default_ordering:
3114
- has_default = (
3115
- getattr(t, '__default__', NoDefault) is not NoDefault
3116
- )
3117
-
3118
- if type_var_tuple_encountered and has_default:
3119
- raise TypeError('Type parameter with a default'
3120
- ' follows TypeVarTuple')
3121
-
3122
- if has_default:
3123
- default_encountered = True
3124
- elif default_encountered:
3125
- raise TypeError(f'Type parameter {t!r} without a default'
3126
- ' follows type parameter with a default')
3127
-
3128
- parameters.append(t)
3129
- else:
3130
- if _is_unpacked_typevartuple(t):
3131
- type_var_tuple_encountered = True
3132
- for x in getattr(t, '__parameters__', ()):
3133
- if x not in parameters:
3134
- parameters.append(x)
3135
-
3136
- return tuple(parameters)
3137
-
3138
- if not _PEP_696_IMPLEMENTED:
3139
- typing._collect_parameters = _collect_parameters
3140
-
3141
- # Backport typing.NamedTuple as it exists in Python 3.13.
3142
- # In 3.11, the ability to define generic `NamedTuple`s was supported.
3143
- # This was explicitly disallowed in 3.9-3.10, and only half-worked in <=3.8.
3144
- # On 3.12, we added __orig_bases__ to call-based NamedTuples
3145
- # On 3.13, we deprecated kwargs-based NamedTuples
3146
- if sys.version_info >= (3, 13):
3147
- NamedTuple = typing.NamedTuple
3148
- else:
3149
- def _make_nmtuple(name, types, module, defaults=()):
3150
- fields = [n for n, t in types]
3151
- annotations = {n: typing._type_check(t, f"field {n} annotation must be a type")
3152
- for n, t in types}
3153
- nm_tpl = collections.namedtuple(name, fields,
3154
- defaults=defaults, module=module)
3155
- nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = annotations
3156
- # The `_field_types` attribute was removed in 3.9;
3157
- # in earlier versions, it is the same as the `__annotations__` attribute
3158
- if sys.version_info < (3, 9):
3159
- nm_tpl._field_types = annotations
3160
- return nm_tpl
3161
-
3162
- _prohibited_namedtuple_fields = typing._prohibited
3163
- _special_namedtuple_fields = frozenset({'__module__', '__name__', '__annotations__'})
3164
-
3165
- class _NamedTupleMeta(type):
3166
- def __new__(cls, typename, bases, ns):
3167
- assert _NamedTuple in bases
3168
- for base in bases:
3169
- if base is not _NamedTuple and base is not typing.Generic:
3170
- raise TypeError(
3171
- 'can only inherit from a NamedTuple type and Generic')
3172
- bases = tuple(tuple if base is _NamedTuple else base for base in bases)
3173
- if "__annotations__" in ns:
3174
- types = ns["__annotations__"]
3175
- elif "__annotate__" in ns:
3176
- # TODO: Use inspect.VALUE here, and make the annotations lazily evaluated
3177
- types = ns["__annotate__"](1)
3178
- else:
3179
- types = {}
3180
- default_names = []
3181
- for field_name in types:
3182
- if field_name in ns:
3183
- default_names.append(field_name)
3184
- elif default_names:
3185
- raise TypeError(f"Non-default namedtuple field {field_name} "
3186
- f"cannot follow default field"
3187
- f"{'s' if len(default_names) > 1 else ''} "
3188
- f"{', '.join(default_names)}")
3189
- nm_tpl = _make_nmtuple(
3190
- typename, types.items(),
3191
- defaults=[ns[n] for n in default_names],
3192
- module=ns['__module__']
3193
- )
3194
- nm_tpl.__bases__ = bases
3195
- if typing.Generic in bases:
3196
- if hasattr(typing, '_generic_class_getitem'): # 3.12+
3197
- nm_tpl.__class_getitem__ = classmethod(typing._generic_class_getitem)
3198
- else:
3199
- class_getitem = typing.Generic.__class_getitem__.__func__
3200
- nm_tpl.__class_getitem__ = classmethod(class_getitem)
3201
- # update from user namespace without overriding special namedtuple attributes
3202
- for key, val in ns.items():
3203
- if key in _prohibited_namedtuple_fields:
3204
- raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
3205
- elif key not in _special_namedtuple_fields:
3206
- if key not in nm_tpl._fields:
3207
- setattr(nm_tpl, key, ns[key])
3208
- try:
3209
- set_name = type(val).__set_name__
3210
- except AttributeError:
3211
- pass
3212
- else:
3213
- try:
3214
- set_name(val, nm_tpl, key)
3215
- except BaseException as e:
3216
- msg = (
3217
- f"Error calling __set_name__ on {type(val).__name__!r} "
3218
- f"instance {key!r} in {typename!r}"
3219
- )
3220
- # BaseException.add_note() existed on py311,
3221
- # but the __set_name__ machinery didn't start
3222
- # using add_note() until py312.
3223
- # Making sure exceptions are raised in the same way
3224
- # as in "normal" classes seems most important here.
3225
- if sys.version_info >= (3, 12):
3226
- e.add_note(msg)
3227
- raise
3228
- else:
3229
- raise RuntimeError(msg) from e
3230
-
3231
- if typing.Generic in bases:
3232
- nm_tpl.__init_subclass__()
3233
- return nm_tpl
3234
-
3235
- _NamedTuple = type.__new__(_NamedTupleMeta, 'NamedTuple', (), {})
3236
-
3237
- def _namedtuple_mro_entries(bases):
3238
- assert NamedTuple in bases
3239
- return (_NamedTuple,)
3240
-
3241
- @_ensure_subclassable(_namedtuple_mro_entries)
3242
- def NamedTuple(typename, fields=_marker, /, **kwargs):
3243
- """Typed version of namedtuple.
3244
-
3245
- Usage::
3246
-
3247
- class Employee(NamedTuple):
3248
- name: str
3249
- id: int
3250
-
3251
- This is equivalent to::
3252
-
3253
- Employee = collections.namedtuple('Employee', ['name', 'id'])
3254
-
3255
- The resulting class has an extra __annotations__ attribute, giving a
3256
- dict that maps field names to types. (The field names are also in
3257
- the _fields attribute, which is part of the namedtuple API.)
3258
- An alternative equivalent functional syntax is also accepted::
3259
-
3260
- Employee = NamedTuple('Employee', [('name', str), ('id', int)])
3261
- """
3262
- if fields is _marker:
3263
- if kwargs:
3264
- deprecated_thing = "Creating NamedTuple classes using keyword arguments"
3265
- deprecation_msg = (
3266
- "{name} is deprecated and will be disallowed in Python {remove}. "
3267
- "Use the class-based or functional syntax instead."
3268
- )
3269
- else:
3270
- deprecated_thing = "Failing to pass a value for the 'fields' parameter"
3271
- example = f"`{typename} = NamedTuple({typename!r}, [])`"
3272
- deprecation_msg = (
3273
- "{name} is deprecated and will be disallowed in Python {remove}. "
3274
- "To create a NamedTuple class with 0 fields "
3275
- "using the functional syntax, "
3276
- "pass an empty list, e.g. "
3277
- ) + example + "."
3278
- elif fields is None:
3279
- if kwargs:
3280
- raise TypeError(
3281
- "Cannot pass `None` as the 'fields' parameter "
3282
- "and also specify fields using keyword arguments"
3283
- )
3284
- else:
3285
- deprecated_thing = "Passing `None` as the 'fields' parameter"
3286
- example = f"`{typename} = NamedTuple({typename!r}, [])`"
3287
- deprecation_msg = (
3288
- "{name} is deprecated and will be disallowed in Python {remove}. "
3289
- "To create a NamedTuple class with 0 fields "
3290
- "using the functional syntax, "
3291
- "pass an empty list, e.g. "
3292
- ) + example + "."
3293
- elif kwargs:
3294
- raise TypeError("Either list of fields or keywords"
3295
- " can be provided to NamedTuple, not both")
3296
- if fields is _marker or fields is None:
3297
- warnings.warn(
3298
- deprecation_msg.format(name=deprecated_thing, remove="3.15"),
3299
- DeprecationWarning,
3300
- stacklevel=2,
3301
- )
3302
- fields = kwargs.items()
3303
- nt = _make_nmtuple(typename, fields, module=_caller())
3304
- nt.__orig_bases__ = (NamedTuple,)
3305
- return nt
3306
-
3307
-
3308
- if hasattr(collections.abc, "Buffer"):
3309
- Buffer = collections.abc.Buffer
3310
- else:
3311
- class Buffer(abc.ABC): # noqa: B024
3312
- """Base class for classes that implement the buffer protocol.
3313
-
3314
- The buffer protocol allows Python objects to expose a low-level
3315
- memory buffer interface. Before Python 3.12, it is not possible
3316
- to implement the buffer protocol in pure Python code, or even
3317
- to check whether a class implements the buffer protocol. In
3318
- Python 3.12 and higher, the ``__buffer__`` method allows access
3319
- to the buffer protocol from Python code, and the
3320
- ``collections.abc.Buffer`` ABC allows checking whether a class
3321
- implements the buffer protocol.
3322
-
3323
- To indicate support for the buffer protocol in earlier versions,
3324
- inherit from this ABC, either in a stub file or at runtime,
3325
- or use ABC registration. This ABC provides no methods, because
3326
- there is no Python-accessible methods shared by pre-3.12 buffer
3327
- classes. It is useful primarily for static checks.
3328
-
3329
- """
3330
-
3331
- # As a courtesy, register the most common stdlib buffer classes.
3332
- Buffer.register(memoryview)
3333
- Buffer.register(bytearray)
3334
- Buffer.register(bytes)
3335
-
3336
-
3337
- # Backport of types.get_original_bases, available on 3.12+ in CPython
3338
- if hasattr(_types, "get_original_bases"):
3339
- get_original_bases = _types.get_original_bases
3340
- else:
3341
- def get_original_bases(cls, /):
3342
- """Return the class's "original" bases prior to modification by `__mro_entries__`.
3343
-
3344
- Examples::
3345
-
3346
- from typing import TypeVar, Generic
3347
- from typing_extensions import NamedTuple, TypedDict
3348
-
3349
- T = TypeVar("T")
3350
- class Foo(Generic[T]): ...
3351
- class Bar(Foo[int], float): ...
3352
- class Baz(list[str]): ...
3353
- Eggs = NamedTuple("Eggs", [("a", int), ("b", str)])
3354
- Spam = TypedDict("Spam", {"a": int, "b": str})
3355
-
3356
- assert get_original_bases(Bar) == (Foo[int], float)
3357
- assert get_original_bases(Baz) == (list[str],)
3358
- assert get_original_bases(Eggs) == (NamedTuple,)
3359
- assert get_original_bases(Spam) == (TypedDict,)
3360
- assert get_original_bases(int) == (object,)
3361
- """
3362
- try:
3363
- return cls.__dict__.get("__orig_bases__", cls.__bases__)
3364
- except AttributeError:
3365
- raise TypeError(
3366
- f'Expected an instance of type, not {type(cls).__name__!r}'
3367
- ) from None
3368
-
3369
-
3370
- # NewType is a class on Python 3.10+, making it pickleable
3371
- # The error message for subclassing instances of NewType was improved on 3.11+
3372
- if sys.version_info >= (3, 11):
3373
- NewType = typing.NewType
3374
- else:
3375
- class NewType:
3376
- """NewType creates simple unique types with almost zero
3377
- runtime overhead. NewType(name, tp) is considered a subtype of tp
3378
- by static type checkers. At runtime, NewType(name, tp) returns
3379
- a dummy callable that simply returns its argument. Usage::
3380
- UserId = NewType('UserId', int)
3381
- def name_by_id(user_id: UserId) -> str:
3382
- ...
3383
- UserId('user') # Fails type check
3384
- name_by_id(42) # Fails type check
3385
- name_by_id(UserId(42)) # OK
3386
- num = UserId(5) + 1 # type: int
3387
- """
3388
-
3389
- def __call__(self, obj, /):
3390
- return obj
3391
-
3392
- def __init__(self, name, tp):
3393
- self.__qualname__ = name
3394
- if '.' in name:
3395
- name = name.rpartition('.')[-1]
3396
- self.__name__ = name
3397
- self.__supertype__ = tp
3398
- def_mod = _caller()
3399
- if def_mod != 'typing_extensions':
3400
- self.__module__ = def_mod
3401
-
3402
- def __mro_entries__(self, bases):
3403
- # We defined __mro_entries__ to get a better error message
3404
- # if a user attempts to subclass a NewType instance. bpo-46170
3405
- supercls_name = self.__name__
3406
-
3407
- class Dummy:
3408
- def __init_subclass__(cls):
3409
- subcls_name = cls.__name__
3410
- raise TypeError(
3411
- f"Cannot subclass an instance of NewType. "
3412
- f"Perhaps you were looking for: "
3413
- f"`{subcls_name} = NewType({subcls_name!r}, {supercls_name})`"
3414
- )
3415
-
3416
- return (Dummy,)
3417
-
3418
- def __repr__(self):
3419
- return f'{self.__module__}.{self.__qualname__}'
3420
-
3421
- def __reduce__(self):
3422
- return self.__qualname__
3423
-
3424
- if sys.version_info >= (3, 10):
3425
- # PEP 604 methods
3426
- # It doesn't make sense to have these methods on Python <3.10
3427
-
3428
- def __or__(self, other):
3429
- return typing.Union[self, other]
3430
-
3431
- def __ror__(self, other):
3432
- return typing.Union[other, self]
3433
-
3434
-
3435
- if hasattr(typing, "TypeAliasType"):
3436
- TypeAliasType = typing.TypeAliasType
3437
- else:
3438
- def _is_unionable(obj):
3439
- """Corresponds to is_unionable() in unionobject.c in CPython."""
3440
- return obj is None or isinstance(obj, (
3441
- type,
3442
- _types.GenericAlias,
3443
- _types.UnionType,
3444
- TypeAliasType,
3445
- ))
3446
-
3447
- class TypeAliasType:
3448
- """Create named, parameterized type aliases.
3449
-
3450
- This provides a backport of the new `type` statement in Python 3.12:
3451
-
3452
- type ListOrSet[T] = list[T] | set[T]
3453
-
3454
- is equivalent to:
3455
-
3456
- T = TypeVar("T")
3457
- ListOrSet = TypeAliasType("ListOrSet", list[T] | set[T], type_params=(T,))
3458
-
3459
- The name ListOrSet can then be used as an alias for the type it refers to.
3460
-
3461
- The type_params argument should contain all the type parameters used
3462
- in the value of the type alias. If the alias is not generic, this
3463
- argument is omitted.
3464
-
3465
- Static type checkers should only support type aliases declared using
3466
- TypeAliasType that follow these rules:
3467
-
3468
- - The first argument (the name) must be a string literal.
3469
- - The TypeAliasType instance must be immediately assigned to a variable
3470
- of the same name. (For example, 'X = TypeAliasType("Y", int)' is invalid,
3471
- as is 'X, Y = TypeAliasType("X", int), TypeAliasType("Y", int)').
3472
-
3473
- """
3474
-
3475
- def __init__(self, name: str, value, *, type_params=()):
3476
- if not isinstance(name, str):
3477
- raise TypeError("TypeAliasType name must be a string")
3478
- self.__value__ = value
3479
- self.__type_params__ = type_params
3480
-
3481
- parameters = []
3482
- for type_param in type_params:
3483
- if isinstance(type_param, TypeVarTuple):
3484
- parameters.extend(type_param)
3485
- else:
3486
- parameters.append(type_param)
3487
- self.__parameters__ = tuple(parameters)
3488
- def_mod = _caller()
3489
- if def_mod != 'typing_extensions':
3490
- self.__module__ = def_mod
3491
- # Setting this attribute closes the TypeAliasType from further modification
3492
- self.__name__ = name
3493
-
3494
- def __setattr__(self, name: str, value: object, /) -> None:
3495
- if hasattr(self, "__name__"):
3496
- self._raise_attribute_error(name)
3497
- super().__setattr__(name, value)
3498
-
3499
- def __delattr__(self, name: str, /) -> Never:
3500
- self._raise_attribute_error(name)
3501
-
3502
- def _raise_attribute_error(self, name: str) -> Never:
3503
- # Match the Python 3.12 error messages exactly
3504
- if name == "__name__":
3505
- raise AttributeError("readonly attribute")
3506
- elif name in {"__value__", "__type_params__", "__parameters__", "__module__"}:
3507
- raise AttributeError(
3508
- f"attribute '{name}' of 'typing.TypeAliasType' objects "
3509
- "is not writable"
3510
- )
3511
- else:
3512
- raise AttributeError(
3513
- f"'typing.TypeAliasType' object has no attribute '{name}'"
3514
- )
3515
-
3516
- def __repr__(self) -> str:
3517
- return self.__name__
3518
-
3519
- def __getitem__(self, parameters):
3520
- if not isinstance(parameters, tuple):
3521
- parameters = (parameters,)
3522
- parameters = [
3523
- typing._type_check(
3524
- item, f'Subscripting {self.__name__} requires a type.'
3525
- )
3526
- for item in parameters
3527
- ]
3528
- return typing._GenericAlias(self, tuple(parameters))
3529
-
3530
- def __reduce__(self):
3531
- return self.__name__
3532
-
3533
- def __init_subclass__(cls, *args, **kwargs):
3534
- raise TypeError(
3535
- "type 'typing_extensions.TypeAliasType' is not an acceptable base type"
3536
- )
3537
-
3538
- # The presence of this method convinces typing._type_check
3539
- # that TypeAliasTypes are types.
3540
- def __call__(self):
3541
- raise TypeError("Type alias is not callable")
3542
-
3543
- if sys.version_info >= (3, 10):
3544
- def __or__(self, right):
3545
- # For forward compatibility with 3.12, reject Unions
3546
- # that are not accepted by the built-in Union.
3547
- if not _is_unionable(right):
3548
- return NotImplemented
3549
- return typing.Union[self, right]
3550
-
3551
- def __ror__(self, left):
3552
- if not _is_unionable(left):
3553
- return NotImplemented
3554
- return typing.Union[left, self]
3555
-
3556
-
3557
- if hasattr(typing, "is_protocol"):
3558
- is_protocol = typing.is_protocol
3559
- get_protocol_members = typing.get_protocol_members
3560
- else:
3561
- def is_protocol(tp: type, /) -> bool:
3562
- """Return True if the given type is a Protocol.
3563
-
3564
- Example::
3565
-
3566
- >>> from typing_extensions import Protocol, is_protocol
3567
- >>> class P(Protocol):
3568
- ... def a(self) -> str: ...
3569
- ... b: int
3570
- >>> is_protocol(P)
3571
- True
3572
- >>> is_protocol(int)
3573
- False
3574
- """
3575
- return (
3576
- isinstance(tp, type)
3577
- and getattr(tp, '_is_protocol', False)
3578
- and tp is not Protocol
3579
- and tp is not typing.Protocol
3580
- )
3581
-
3582
- def get_protocol_members(tp: type, /) -> typing.FrozenSet[str]:
3583
- """Return the set of members defined in a Protocol.
3584
-
3585
- Example::
3586
-
3587
- >>> from typing_extensions import Protocol, get_protocol_members
3588
- >>> class P(Protocol):
3589
- ... def a(self) -> str: ...
3590
- ... b: int
3591
- >>> get_protocol_members(P)
3592
- frozenset({'a', 'b'})
3593
-
3594
- Raise a TypeError for arguments that are not Protocols.
3595
- """
3596
- if not is_protocol(tp):
3597
- raise TypeError(f'{tp!r} is not a Protocol')
3598
- if hasattr(tp, '__protocol_attrs__'):
3599
- return frozenset(tp.__protocol_attrs__)
3600
- return frozenset(_get_protocol_attrs(tp))
3601
-
3602
-
3603
- if hasattr(typing, "Doc"):
3604
- Doc = typing.Doc
3605
- else:
3606
- class Doc:
3607
- """Define the documentation of a type annotation using ``Annotated``, to be
3608
- used in class attributes, function and method parameters, return values,
3609
- and variables.
3610
-
3611
- The value should be a positional-only string literal to allow static tools
3612
- like editors and documentation generators to use it.
3613
-
3614
- This complements docstrings.
3615
-
3616
- The string value passed is available in the attribute ``documentation``.
3617
-
3618
- Example::
3619
-
3620
- >>> from typing_extensions import Annotated, Doc
3621
- >>> def hi(to: Annotated[str, Doc("Who to say hi to")]) -> None: ...
3622
- """
3623
- def __init__(self, documentation: str, /) -> None:
3624
- self.documentation = documentation
3625
-
3626
- def __repr__(self) -> str:
3627
- return f"Doc({self.documentation!r})"
3628
-
3629
- def __hash__(self) -> int:
3630
- return hash(self.documentation)
3631
-
3632
- def __eq__(self, other: object) -> bool:
3633
- if not isinstance(other, Doc):
3634
- return NotImplemented
3635
- return self.documentation == other.documentation
3636
-
3637
-
3638
- _CapsuleType = getattr(_types, "CapsuleType", None)
3639
-
3640
- if _CapsuleType is None:
3641
- try:
3642
- import _socket
3643
- except ImportError:
3644
- pass
3645
- else:
3646
- _CAPI = getattr(_socket, "CAPI", None)
3647
- if _CAPI is not None:
3648
- _CapsuleType = type(_CAPI)
3649
-
3650
- if _CapsuleType is not None:
3651
- CapsuleType = _CapsuleType
3652
- __all__.append("CapsuleType")
3653
-
3654
-
3655
- # Using this convoluted approach so that this keeps working
3656
- # whether we end up using PEP 649 as written, PEP 749, or
3657
- # some other variation: in any case, inspect.get_annotations
3658
- # will continue to exist and will gain a `format` parameter.
3659
- _PEP_649_OR_749_IMPLEMENTED = (
3660
- hasattr(inspect, 'get_annotations')
3661
- and inspect.get_annotations.__kwdefaults__ is not None
3662
- and "format" in inspect.get_annotations.__kwdefaults__
3663
- )
3664
-
3665
-
3666
- class Format(enum.IntEnum):
3667
- VALUE = 1
3668
- FORWARDREF = 2
3669
- SOURCE = 3
3670
-
3671
-
3672
- if _PEP_649_OR_749_IMPLEMENTED:
3673
- get_annotations = inspect.get_annotations
3674
- else:
3675
- def get_annotations(obj, *, globals=None, locals=None, eval_str=False,
3676
- format=Format.VALUE):
3677
- """Compute the annotations dict for an object.
3678
-
3679
- obj may be a callable, class, or module.
3680
- Passing in an object of any other type raises TypeError.
3681
-
3682
- Returns a dict. get_annotations() returns a new dict every time
3683
- it's called; calling it twice on the same object will return two
3684
- different but equivalent dicts.
3685
-
3686
- This is a backport of `inspect.get_annotations`, which has been
3687
- in the standard library since Python 3.10. See the standard library
3688
- documentation for more:
3689
-
3690
- https://docs.python.org/3/library/inspect.html#inspect.get_annotations
3691
-
3692
- This backport adds the *format* argument introduced by PEP 649. The
3693
- three formats supported are:
3694
- * VALUE: the annotations are returned as-is. This is the default and
3695
- it is compatible with the behavior on previous Python versions.
3696
- * FORWARDREF: return annotations as-is if possible, but replace any
3697
- undefined names with ForwardRef objects. The implementation proposed by
3698
- PEP 649 relies on language changes that cannot be backported; the
3699
- typing-extensions implementation simply returns the same result as VALUE.
3700
- * SOURCE: return annotations as strings, in a format close to the original
3701
- source. Again, this behavior cannot be replicated directly in a backport.
3702
- As an approximation, typing-extensions retrieves the annotations under
3703
- VALUE semantics and then stringifies them.
3704
-
3705
- The purpose of this backport is to allow users who would like to use
3706
- FORWARDREF or SOURCE semantics once PEP 649 is implemented, but who also
3707
- want to support earlier Python versions, to simply write:
3708
-
3709
- typing_extensions.get_annotations(obj, format=Format.FORWARDREF)
3710
-
3711
- """
3712
- format = Format(format)
3713
-
3714
- if eval_str and format is not Format.VALUE:
3715
- raise ValueError("eval_str=True is only supported with format=Format.VALUE")
3716
-
3717
- if isinstance(obj, type):
3718
- # class
3719
- obj_dict = getattr(obj, '__dict__', None)
3720
- if obj_dict and hasattr(obj_dict, 'get'):
3721
- ann = obj_dict.get('__annotations__', None)
3722
- if isinstance(ann, _types.GetSetDescriptorType):
3723
- ann = None
3724
- else:
3725
- ann = None
3726
-
3727
- obj_globals = None
3728
- module_name = getattr(obj, '__module__', None)
3729
- if module_name:
3730
- module = sys.modules.get(module_name, None)
3731
- if module:
3732
- obj_globals = getattr(module, '__dict__', None)
3733
- obj_locals = dict(vars(obj))
3734
- unwrap = obj
3735
- elif isinstance(obj, _types.ModuleType):
3736
- # module
3737
- ann = getattr(obj, '__annotations__', None)
3738
- obj_globals = obj.__dict__
3739
- obj_locals = None
3740
- unwrap = None
3741
- elif callable(obj):
3742
- # this includes types.Function, types.BuiltinFunctionType,
3743
- # types.BuiltinMethodType, functools.partial, functools.singledispatch,
3744
- # "class funclike" from Lib/test/test_inspect... on and on it goes.
3745
- ann = getattr(obj, '__annotations__', None)
3746
- obj_globals = getattr(obj, '__globals__', None)
3747
- obj_locals = None
3748
- unwrap = obj
3749
- elif hasattr(obj, '__annotations__'):
3750
- ann = obj.__annotations__
3751
- obj_globals = obj_locals = unwrap = None
3752
- else:
3753
- raise TypeError(f"{obj!r} is not a module, class, or callable.")
3754
-
3755
- if ann is None:
3756
- return {}
3757
-
3758
- if not isinstance(ann, dict):
3759
- raise ValueError(f"{obj!r}.__annotations__ is neither a dict nor None")
3760
-
3761
- if not ann:
3762
- return {}
3763
-
3764
- if not eval_str:
3765
- if format is Format.SOURCE:
3766
- return {
3767
- key: value if isinstance(value, str) else typing._type_repr(value)
3768
- for key, value in ann.items()
3769
- }
3770
- return dict(ann)
3771
-
3772
- if unwrap is not None:
3773
- while True:
3774
- if hasattr(unwrap, '__wrapped__'):
3775
- unwrap = unwrap.__wrapped__
3776
- continue
3777
- if isinstance(unwrap, functools.partial):
3778
- unwrap = unwrap.func
3779
- continue
3780
- break
3781
- if hasattr(unwrap, "__globals__"):
3782
- obj_globals = unwrap.__globals__
3783
-
3784
- if globals is None:
3785
- globals = obj_globals
3786
- if locals is None:
3787
- locals = obj_locals or {}
3788
-
3789
- # "Inject" type parameters into the local namespace
3790
- # (unless they are shadowed by assignments *in* the local namespace),
3791
- # as a way of emulating annotation scopes when calling `eval()`
3792
- if type_params := getattr(obj, "__type_params__", ()):
3793
- locals = {param.__name__: param for param in type_params} | locals
3794
-
3795
- return_value = {key:
3796
- value if not isinstance(value, str) else eval(value, globals, locals)
3797
- for key, value in ann.items() }
3798
- return return_value
3799
-
3800
- # Aliases for items that have always been in typing.
3801
- # Explicitly assign these (rather than using `from typing import *` at the top),
3802
- # so that we get a CI error if one of these is deleted from typing.py
3803
- # in a future version of Python
3804
- AbstractSet = typing.AbstractSet
3805
- AnyStr = typing.AnyStr
3806
- BinaryIO = typing.BinaryIO
3807
- Callable = typing.Callable
3808
- Collection = typing.Collection
3809
- Container = typing.Container
3810
- Dict = typing.Dict
3811
- ForwardRef = typing.ForwardRef
3812
- FrozenSet = typing.FrozenSet
3813
- Generic = typing.Generic
3814
- Hashable = typing.Hashable
3815
- IO = typing.IO
3816
- ItemsView = typing.ItemsView
3817
- Iterable = typing.Iterable
3818
- Iterator = typing.Iterator
3819
- KeysView = typing.KeysView
3820
- List = typing.List
3821
- Mapping = typing.Mapping
3822
- MappingView = typing.MappingView
3823
- Match = typing.Match
3824
- MutableMapping = typing.MutableMapping
3825
- MutableSequence = typing.MutableSequence
3826
- MutableSet = typing.MutableSet
3827
- Optional = typing.Optional
3828
- Pattern = typing.Pattern
3829
- Reversible = typing.Reversible
3830
- Sequence = typing.Sequence
3831
- Set = typing.Set
3832
- Sized = typing.Sized
3833
- TextIO = typing.TextIO
3834
- Tuple = typing.Tuple
3835
- Union = typing.Union
3836
- ValuesView = typing.ValuesView
3837
- cast = typing.cast
3838
- no_type_check = typing.no_type_check
3839
- no_type_check_decorator = typing.no_type_check_decorator