]> jfr.im git - dlqueue.git/blob - venv/lib/python3.11/site-packages/setuptools/_vendor/typing_extensions.py
init: venv aand flask
[dlqueue.git] / venv / lib / python3.11 / site-packages / setuptools / _vendor / typing_extensions.py
1 import abc
2 import collections
3 import collections.abc
4 import operator
5 import sys
6 import typing
7
8 # After PEP 560, internal typing API was substantially reworked.
9 # This is especially important for Protocol class which uses internal APIs
10 # quite extensively.
11 PEP_560 = sys.version_info[:3] >= (3, 7, 0)
12
13 if PEP_560:
14 GenericMeta = type
15 else:
16 # 3.6
17 from typing import GenericMeta, _type_vars # noqa
18
19 # The two functions below are copies of typing internal helpers.
20 # They are needed by _ProtocolMeta
21
22
23 def _no_slots_copy(dct):
24 dict_copy = dict(dct)
25 if '__slots__' in dict_copy:
26 for slot in dict_copy['__slots__']:
27 dict_copy.pop(slot, None)
28 return dict_copy
29
30
31 def _check_generic(cls, parameters):
32 if not cls.__parameters__:
33 raise TypeError(f"{cls} is not a generic class")
34 alen = len(parameters)
35 elen = len(cls.__parameters__)
36 if alen != elen:
37 raise TypeError(f"Too {'many' if alen > elen else 'few'} arguments for {cls};"
38 f" actual {alen}, expected {elen}")
39
40
41 # Please keep __all__ alphabetized within each category.
42 __all__ = [
43 # Super-special typing primitives.
44 'ClassVar',
45 'Concatenate',
46 'Final',
47 'ParamSpec',
48 'Self',
49 'Type',
50
51 # ABCs (from collections.abc).
52 'Awaitable',
53 'AsyncIterator',
54 'AsyncIterable',
55 'Coroutine',
56 'AsyncGenerator',
57 'AsyncContextManager',
58 'ChainMap',
59
60 # Concrete collection types.
61 'ContextManager',
62 'Counter',
63 'Deque',
64 'DefaultDict',
65 'OrderedDict',
66 'TypedDict',
67
68 # Structural checks, a.k.a. protocols.
69 'SupportsIndex',
70
71 # One-off things.
72 'Annotated',
73 'final',
74 'IntVar',
75 'Literal',
76 'NewType',
77 'overload',
78 'Protocol',
79 'runtime',
80 'runtime_checkable',
81 'Text',
82 'TypeAlias',
83 'TypeGuard',
84 'TYPE_CHECKING',
85 ]
86
87 if PEP_560:
88 __all__.extend(["get_args", "get_origin", "get_type_hints"])
89
90 # 3.6.2+
91 if hasattr(typing, 'NoReturn'):
92 NoReturn = typing.NoReturn
93 # 3.6.0-3.6.1
94 else:
95 class _NoReturn(typing._FinalTypingBase, _root=True):
96 """Special type indicating functions that never return.
97 Example::
98
99 from typing import NoReturn
100
101 def stop() -> NoReturn:
102 raise Exception('no way')
103
104 This type is invalid in other positions, e.g., ``List[NoReturn]``
105 will fail in static type checkers.
106 """
107 __slots__ = ()
108
109 def __instancecheck__(self, obj):
110 raise TypeError("NoReturn cannot be used with isinstance().")
111
112 def __subclasscheck__(self, cls):
113 raise TypeError("NoReturn cannot be used with issubclass().")
114
115 NoReturn = _NoReturn(_root=True)
116
117 # Some unconstrained type variables. These are used by the container types.
118 # (These are not for export.)
119 T = typing.TypeVar('T') # Any type.
120 KT = typing.TypeVar('KT') # Key type.
121 VT = typing.TypeVar('VT') # Value type.
122 T_co = typing.TypeVar('T_co', covariant=True) # Any type covariant containers.
123 T_contra = typing.TypeVar('T_contra', contravariant=True) # Ditto contravariant.
124
125 ClassVar = typing.ClassVar
126
127 # On older versions of typing there is an internal class named "Final".
128 # 3.8+
129 if hasattr(typing, 'Final') and sys.version_info[:2] >= (3, 7):
130 Final = typing.Final
131 # 3.7
132 elif sys.version_info[:2] >= (3, 7):
133 class _FinalForm(typing._SpecialForm, _root=True):
134
135 def __repr__(self):
136 return 'typing_extensions.' + self._name
137
138 def __getitem__(self, parameters):
139 item = typing._type_check(parameters,
140 f'{self._name} accepts only single type')
141 return typing._GenericAlias(self, (item,))
142
143 Final = _FinalForm('Final',
144 doc="""A special typing construct to indicate that a name
145 cannot be re-assigned or overridden in a subclass.
146 For example:
147
148 MAX_SIZE: Final = 9000
149 MAX_SIZE += 1 # Error reported by type checker
150
151 class Connection:
152 TIMEOUT: Final[int] = 10
153 class FastConnector(Connection):
154 TIMEOUT = 1 # Error reported by type checker
155
156 There is no runtime checking of these properties.""")
157 # 3.6
158 else:
159 class _Final(typing._FinalTypingBase, _root=True):
160 """A special typing construct to indicate that a name
161 cannot be re-assigned or overridden in a subclass.
162 For example:
163
164 MAX_SIZE: Final = 9000
165 MAX_SIZE += 1 # Error reported by type checker
166
167 class Connection:
168 TIMEOUT: Final[int] = 10
169 class FastConnector(Connection):
170 TIMEOUT = 1 # Error reported by type checker
171
172 There is no runtime checking of these properties.
173 """
174
175 __slots__ = ('__type__',)
176
177 def __init__(self, tp=None, **kwds):
178 self.__type__ = tp
179
180 def __getitem__(self, item):
181 cls = type(self)
182 if self.__type__ is None:
183 return cls(typing._type_check(item,
184 f'{cls.__name__[1:]} accepts only single type.'),
185 _root=True)
186 raise TypeError(f'{cls.__name__[1:]} cannot be further subscripted')
187
188 def _eval_type(self, globalns, localns):
189 new_tp = typing._eval_type(self.__type__, globalns, localns)
190 if new_tp == self.__type__:
191 return self
192 return type(self)(new_tp, _root=True)
193
194 def __repr__(self):
195 r = super().__repr__()
196 if self.__type__ is not None:
197 r += f'[{typing._type_repr(self.__type__)}]'
198 return r
199
200 def __hash__(self):
201 return hash((type(self).__name__, self.__type__))
202
203 def __eq__(self, other):
204 if not isinstance(other, _Final):
205 return NotImplemented
206 if self.__type__ is not None:
207 return self.__type__ == other.__type__
208 return self is other
209
210 Final = _Final(_root=True)
211
212
213 # 3.8+
214 if hasattr(typing, 'final'):
215 final = typing.final
216 # 3.6-3.7
217 else:
218 def final(f):
219 """This decorator can be used to indicate to type checkers that
220 the decorated method cannot be overridden, and decorated class
221 cannot be subclassed. For example:
222
223 class Base:
224 @final
225 def done(self) -> None:
226 ...
227 class Sub(Base):
228 def done(self) -> None: # Error reported by type checker
229 ...
230 @final
231 class Leaf:
232 ...
233 class Other(Leaf): # Error reported by type checker
234 ...
235
236 There is no runtime checking of these properties.
237 """
238 return f
239
240
241 def IntVar(name):
242 return typing.TypeVar(name)
243
244
245 # 3.8+:
246 if hasattr(typing, 'Literal'):
247 Literal = typing.Literal
248 # 3.7:
249 elif sys.version_info[:2] >= (3, 7):
250 class _LiteralForm(typing._SpecialForm, _root=True):
251
252 def __repr__(self):
253 return 'typing_extensions.' + self._name
254
255 def __getitem__(self, parameters):
256 return typing._GenericAlias(self, parameters)
257
258 Literal = _LiteralForm('Literal',
259 doc="""A type that can be used to indicate to type checkers
260 that the corresponding value has a value literally equivalent
261 to the provided parameter. For example:
262
263 var: Literal[4] = 4
264
265 The type checker understands that 'var' is literally equal to
266 the value 4 and no other value.
267
268 Literal[...] cannot be subclassed. There is no runtime
269 checking verifying that the parameter is actually a value
270 instead of a type.""")
271 # 3.6:
272 else:
273 class _Literal(typing._FinalTypingBase, _root=True):
274 """A type that can be used to indicate to type checkers that the
275 corresponding value has a value literally equivalent to the
276 provided parameter. For example:
277
278 var: Literal[4] = 4
279
280 The type checker understands that 'var' is literally equal to the
281 value 4 and no other value.
282
283 Literal[...] cannot be subclassed. There is no runtime checking
284 verifying that the parameter is actually a value instead of a type.
285 """
286
287 __slots__ = ('__values__',)
288
289 def __init__(self, values=None, **kwds):
290 self.__values__ = values
291
292 def __getitem__(self, values):
293 cls = type(self)
294 if self.__values__ is None:
295 if not isinstance(values, tuple):
296 values = (values,)
297 return cls(values, _root=True)
298 raise TypeError(f'{cls.__name__[1:]} cannot be further subscripted')
299
300 def _eval_type(self, globalns, localns):
301 return self
302
303 def __repr__(self):
304 r = super().__repr__()
305 if self.__values__ is not None:
306 r += f'[{", ".join(map(typing._type_repr, self.__values__))}]'
307 return r
308
309 def __hash__(self):
310 return hash((type(self).__name__, self.__values__))
311
312 def __eq__(self, other):
313 if not isinstance(other, _Literal):
314 return NotImplemented
315 if self.__values__ is not None:
316 return self.__values__ == other.__values__
317 return self is other
318
319 Literal = _Literal(_root=True)
320
321
322 _overload_dummy = typing._overload_dummy # noqa
323 overload = typing.overload
324
325
326 # This is not a real generic class. Don't use outside annotations.
327 Type = typing.Type
328
329 # Various ABCs mimicking those in collections.abc.
330 # A few are simply re-exported for completeness.
331
332
333 class _ExtensionsGenericMeta(GenericMeta):
334 def __subclasscheck__(self, subclass):
335 """This mimics a more modern GenericMeta.__subclasscheck__() logic
336 (that does not have problems with recursion) to work around interactions
337 between collections, typing, and typing_extensions on older
338 versions of Python, see https://github.com/python/typing/issues/501.
339 """
340 if self.__origin__ is not None:
341 if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools']:
342 raise TypeError("Parameterized generics cannot be used with class "
343 "or instance checks")
344 return False
345 if not self.__extra__:
346 return super().__subclasscheck__(subclass)
347 res = self.__extra__.__subclasshook__(subclass)
348 if res is not NotImplemented:
349 return res
350 if self.__extra__ in subclass.__mro__:
351 return True
352 for scls in self.__extra__.__subclasses__():
353 if isinstance(scls, GenericMeta):
354 continue
355 if issubclass(subclass, scls):
356 return True
357 return False
358
359
360 Awaitable = typing.Awaitable
361 Coroutine = typing.Coroutine
362 AsyncIterable = typing.AsyncIterable
363 AsyncIterator = typing.AsyncIterator
364
365 # 3.6.1+
366 if hasattr(typing, 'Deque'):
367 Deque = typing.Deque
368 # 3.6.0
369 else:
370 class Deque(collections.deque, typing.MutableSequence[T],
371 metaclass=_ExtensionsGenericMeta,
372 extra=collections.deque):
373 __slots__ = ()
374
375 def __new__(cls, *args, **kwds):
376 if cls._gorg is Deque:
377 return collections.deque(*args, **kwds)
378 return typing._generic_new(collections.deque, cls, *args, **kwds)
379
380 ContextManager = typing.ContextManager
381 # 3.6.2+
382 if hasattr(typing, 'AsyncContextManager'):
383 AsyncContextManager = typing.AsyncContextManager
384 # 3.6.0-3.6.1
385 else:
386 from _collections_abc import _check_methods as _check_methods_in_mro # noqa
387
388 class AsyncContextManager(typing.Generic[T_co]):
389 __slots__ = ()
390
391 async def __aenter__(self):
392 return self
393
394 @abc.abstractmethod
395 async def __aexit__(self, exc_type, exc_value, traceback):
396 return None
397
398 @classmethod
399 def __subclasshook__(cls, C):
400 if cls is AsyncContextManager:
401 return _check_methods_in_mro(C, "__aenter__", "__aexit__")
402 return NotImplemented
403
404 DefaultDict = typing.DefaultDict
405
406 # 3.7.2+
407 if hasattr(typing, 'OrderedDict'):
408 OrderedDict = typing.OrderedDict
409 # 3.7.0-3.7.2
410 elif (3, 7, 0) <= sys.version_info[:3] < (3, 7, 2):
411 OrderedDict = typing._alias(collections.OrderedDict, (KT, VT))
412 # 3.6
413 else:
414 class OrderedDict(collections.OrderedDict, typing.MutableMapping[KT, VT],
415 metaclass=_ExtensionsGenericMeta,
416 extra=collections.OrderedDict):
417
418 __slots__ = ()
419
420 def __new__(cls, *args, **kwds):
421 if cls._gorg is OrderedDict:
422 return collections.OrderedDict(*args, **kwds)
423 return typing._generic_new(collections.OrderedDict, cls, *args, **kwds)
424
425 # 3.6.2+
426 if hasattr(typing, 'Counter'):
427 Counter = typing.Counter
428 # 3.6.0-3.6.1
429 else:
430 class Counter(collections.Counter,
431 typing.Dict[T, int],
432 metaclass=_ExtensionsGenericMeta, extra=collections.Counter):
433
434 __slots__ = ()
435
436 def __new__(cls, *args, **kwds):
437 if cls._gorg is Counter:
438 return collections.Counter(*args, **kwds)
439 return typing._generic_new(collections.Counter, cls, *args, **kwds)
440
441 # 3.6.1+
442 if hasattr(typing, 'ChainMap'):
443 ChainMap = typing.ChainMap
444 elif hasattr(collections, 'ChainMap'):
445 class ChainMap(collections.ChainMap, typing.MutableMapping[KT, VT],
446 metaclass=_ExtensionsGenericMeta,
447 extra=collections.ChainMap):
448
449 __slots__ = ()
450
451 def __new__(cls, *args, **kwds):
452 if cls._gorg is ChainMap:
453 return collections.ChainMap(*args, **kwds)
454 return typing._generic_new(collections.ChainMap, cls, *args, **kwds)
455
456 # 3.6.1+
457 if hasattr(typing, 'AsyncGenerator'):
458 AsyncGenerator = typing.AsyncGenerator
459 # 3.6.0
460 else:
461 class AsyncGenerator(AsyncIterator[T_co], typing.Generic[T_co, T_contra],
462 metaclass=_ExtensionsGenericMeta,
463 extra=collections.abc.AsyncGenerator):
464 __slots__ = ()
465
466 NewType = typing.NewType
467 Text = typing.Text
468 TYPE_CHECKING = typing.TYPE_CHECKING
469
470
471 def _gorg(cls):
472 """This function exists for compatibility with old typing versions."""
473 assert isinstance(cls, GenericMeta)
474 if hasattr(cls, '_gorg'):
475 return cls._gorg
476 while cls.__origin__ is not None:
477 cls = cls.__origin__
478 return cls
479
480
481 _PROTO_WHITELIST = ['Callable', 'Awaitable',
482 'Iterable', 'Iterator', 'AsyncIterable', 'AsyncIterator',
483 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible',
484 'ContextManager', 'AsyncContextManager']
485
486
487 def _get_protocol_attrs(cls):
488 attrs = set()
489 for base in cls.__mro__[:-1]: # without object
490 if base.__name__ in ('Protocol', 'Generic'):
491 continue
492 annotations = getattr(base, '__annotations__', {})
493 for attr in list(base.__dict__.keys()) + list(annotations.keys()):
494 if (not attr.startswith('_abc_') and attr not in (
495 '__abstractmethods__', '__annotations__', '__weakref__',
496 '_is_protocol', '_is_runtime_protocol', '__dict__',
497 '__args__', '__slots__',
498 '__next_in_mro__', '__parameters__', '__origin__',
499 '__orig_bases__', '__extra__', '__tree_hash__',
500 '__doc__', '__subclasshook__', '__init__', '__new__',
501 '__module__', '_MutableMapping__marker', '_gorg')):
502 attrs.add(attr)
503 return attrs
504
505
506 def _is_callable_members_only(cls):
507 return all(callable(getattr(cls, attr, None)) for attr in _get_protocol_attrs(cls))
508
509
510 # 3.8+
511 if hasattr(typing, 'Protocol'):
512 Protocol = typing.Protocol
513 # 3.7
514 elif PEP_560:
515 from typing import _collect_type_vars # noqa
516
517 def _no_init(self, *args, **kwargs):
518 if type(self)._is_protocol:
519 raise TypeError('Protocols cannot be instantiated')
520
521 class _ProtocolMeta(abc.ABCMeta):
522 # This metaclass is a bit unfortunate and exists only because of the lack
523 # of __instancehook__.
524 def __instancecheck__(cls, instance):
525 # We need this method for situations where attributes are
526 # assigned in __init__.
527 if ((not getattr(cls, '_is_protocol', False) or
528 _is_callable_members_only(cls)) and
529 issubclass(instance.__class__, cls)):
530 return True
531 if cls._is_protocol:
532 if all(hasattr(instance, attr) and
533 (not callable(getattr(cls, attr, None)) or
534 getattr(instance, attr) is not None)
535 for attr in _get_protocol_attrs(cls)):
536 return True
537 return super().__instancecheck__(instance)
538
539 class Protocol(metaclass=_ProtocolMeta):
540 # There is quite a lot of overlapping code with typing.Generic.
541 # Unfortunately it is hard to avoid this while these live in two different
542 # modules. The duplicated code will be removed when Protocol is moved to typing.
543 """Base class for protocol classes. Protocol classes are defined as::
544
545 class Proto(Protocol):
546 def meth(self) -> int:
547 ...
548
549 Such classes are primarily used with static type checkers that recognize
550 structural subtyping (static duck-typing), for example::
551
552 class C:
553 def meth(self) -> int:
554 return 0
555
556 def func(x: Proto) -> int:
557 return x.meth()
558
559 func(C()) # Passes static type check
560
561 See PEP 544 for details. Protocol classes decorated with
562 @typing_extensions.runtime act as simple-minded runtime protocol that checks
563 only the presence of given attributes, ignoring their type signatures.
564
565 Protocol classes can be generic, they are defined as::
566
567 class GenProto(Protocol[T]):
568 def meth(self) -> T:
569 ...
570 """
571 __slots__ = ()
572 _is_protocol = True
573
574 def __new__(cls, *args, **kwds):
575 if cls is Protocol:
576 raise TypeError("Type Protocol cannot be instantiated; "
577 "it can only be used as a base class")
578 return super().__new__(cls)
579
580 @typing._tp_cache
581 def __class_getitem__(cls, params):
582 if not isinstance(params, tuple):
583 params = (params,)
584 if not params and cls is not typing.Tuple:
585 raise TypeError(
586 f"Parameter list to {cls.__qualname__}[...] cannot be empty")
587 msg = "Parameters to generic types must be types."
588 params = tuple(typing._type_check(p, msg) for p in params) # noqa
589 if cls is Protocol:
590 # Generic can only be subscripted with unique type variables.
591 if not all(isinstance(p, typing.TypeVar) for p in params):
592 i = 0
593 while isinstance(params[i], typing.TypeVar):
594 i += 1
595 raise TypeError(
596 "Parameters to Protocol[...] must all be type variables."
597 f" Parameter {i + 1} is {params[i]}")
598 if len(set(params)) != len(params):
599 raise TypeError(
600 "Parameters to Protocol[...] must all be unique")
601 else:
602 # Subscripting a regular Generic subclass.
603 _check_generic(cls, params)
604 return typing._GenericAlias(cls, params)
605
606 def __init_subclass__(cls, *args, **kwargs):
607 tvars = []
608 if '__orig_bases__' in cls.__dict__:
609 error = typing.Generic in cls.__orig_bases__
610 else:
611 error = typing.Generic in cls.__bases__
612 if error:
613 raise TypeError("Cannot inherit from plain Generic")
614 if '__orig_bases__' in cls.__dict__:
615 tvars = _collect_type_vars(cls.__orig_bases__)
616 # Look for Generic[T1, ..., Tn] or Protocol[T1, ..., Tn].
617 # If found, tvars must be a subset of it.
618 # If not found, tvars is it.
619 # Also check for and reject plain Generic,
620 # and reject multiple Generic[...] and/or Protocol[...].
621 gvars = None
622 for base in cls.__orig_bases__:
623 if (isinstance(base, typing._GenericAlias) and
624 base.__origin__ in (typing.Generic, Protocol)):
625 # for error messages
626 the_base = base.__origin__.__name__
627 if gvars is not None:
628 raise TypeError(
629 "Cannot inherit from Generic[...]"
630 " and/or Protocol[...] multiple types.")
631 gvars = base.__parameters__
632 if gvars is None:
633 gvars = tvars
634 else:
635 tvarset = set(tvars)
636 gvarset = set(gvars)
637 if not tvarset <= gvarset:
638 s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)
639 s_args = ', '.join(str(g) for g in gvars)
640 raise TypeError(f"Some type variables ({s_vars}) are"
641 f" not listed in {the_base}[{s_args}]")
642 tvars = gvars
643 cls.__parameters__ = tuple(tvars)
644
645 # Determine if this is a protocol or a concrete subclass.
646 if not cls.__dict__.get('_is_protocol', None):
647 cls._is_protocol = any(b is Protocol for b in cls.__bases__)
648
649 # Set (or override) the protocol subclass hook.
650 def _proto_hook(other):
651 if not cls.__dict__.get('_is_protocol', None):
652 return NotImplemented
653 if not getattr(cls, '_is_runtime_protocol', False):
654 if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']:
655 return NotImplemented
656 raise TypeError("Instance and class checks can only be used with"
657 " @runtime protocols")
658 if not _is_callable_members_only(cls):
659 if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']:
660 return NotImplemented
661 raise TypeError("Protocols with non-method members"
662 " don't support issubclass()")
663 if not isinstance(other, type):
664 # Same error as for issubclass(1, int)
665 raise TypeError('issubclass() arg 1 must be a class')
666 for attr in _get_protocol_attrs(cls):
667 for base in other.__mro__:
668 if attr in base.__dict__:
669 if base.__dict__[attr] is None:
670 return NotImplemented
671 break
672 annotations = getattr(base, '__annotations__', {})
673 if (isinstance(annotations, typing.Mapping) and
674 attr in annotations and
675 isinstance(other, _ProtocolMeta) and
676 other._is_protocol):
677 break
678 else:
679 return NotImplemented
680 return True
681 if '__subclasshook__' not in cls.__dict__:
682 cls.__subclasshook__ = _proto_hook
683
684 # We have nothing more to do for non-protocols.
685 if not cls._is_protocol:
686 return
687
688 # Check consistency of bases.
689 for base in cls.__bases__:
690 if not (base in (object, typing.Generic) or
691 base.__module__ == 'collections.abc' and
692 base.__name__ in _PROTO_WHITELIST or
693 isinstance(base, _ProtocolMeta) and base._is_protocol):
694 raise TypeError('Protocols can only inherit from other'
695 f' protocols, got {repr(base)}')
696 cls.__init__ = _no_init
697 # 3.6
698 else:
699 from typing import _next_in_mro, _type_check # noqa
700
701 def _no_init(self, *args, **kwargs):
702 if type(self)._is_protocol:
703 raise TypeError('Protocols cannot be instantiated')
704
705 class _ProtocolMeta(GenericMeta):
706 """Internal metaclass for Protocol.
707
708 This exists so Protocol classes can be generic without deriving
709 from Generic.
710 """
711 def __new__(cls, name, bases, namespace,
712 tvars=None, args=None, origin=None, extra=None, orig_bases=None):
713 # This is just a version copied from GenericMeta.__new__ that
714 # includes "Protocol" special treatment. (Comments removed for brevity.)
715 assert extra is None # Protocols should not have extra
716 if tvars is not None:
717 assert origin is not None
718 assert all(isinstance(t, typing.TypeVar) for t in tvars), tvars
719 else:
720 tvars = _type_vars(bases)
721 gvars = None
722 for base in bases:
723 if base is typing.Generic:
724 raise TypeError("Cannot inherit from plain Generic")
725 if (isinstance(base, GenericMeta) and
726 base.__origin__ in (typing.Generic, Protocol)):
727 if gvars is not None:
728 raise TypeError(
729 "Cannot inherit from Generic[...] or"
730 " Protocol[...] multiple times.")
731 gvars = base.__parameters__
732 if gvars is None:
733 gvars = tvars
734 else:
735 tvarset = set(tvars)
736 gvarset = set(gvars)
737 if not tvarset <= gvarset:
738 s_vars = ", ".join(str(t) for t in tvars if t not in gvarset)
739 s_args = ", ".join(str(g) for g in gvars)
740 cls_name = "Generic" if any(b.__origin__ is typing.Generic
741 for b in bases) else "Protocol"
742 raise TypeError(f"Some type variables ({s_vars}) are"
743 f" not listed in {cls_name}[{s_args}]")
744 tvars = gvars
745
746 initial_bases = bases
747 if (extra is not None and type(extra) is abc.ABCMeta and
748 extra not in bases):
749 bases = (extra,) + bases
750 bases = tuple(_gorg(b) if isinstance(b, GenericMeta) else b
751 for b in bases)
752 if any(isinstance(b, GenericMeta) and b is not typing.Generic for b in bases):
753 bases = tuple(b for b in bases if b is not typing.Generic)
754 namespace.update({'__origin__': origin, '__extra__': extra})
755 self = super(GenericMeta, cls).__new__(cls, name, bases, namespace,
756 _root=True)
757 super(GenericMeta, self).__setattr__('_gorg',
758 self if not origin else
759 _gorg(origin))
760 self.__parameters__ = tvars
761 self.__args__ = tuple(... if a is typing._TypingEllipsis else
762 () if a is typing._TypingEmpty else
763 a for a in args) if args else None
764 self.__next_in_mro__ = _next_in_mro(self)
765 if orig_bases is None:
766 self.__orig_bases__ = initial_bases
767 elif origin is not None:
768 self._abc_registry = origin._abc_registry
769 self._abc_cache = origin._abc_cache
770 if hasattr(self, '_subs_tree'):
771 self.__tree_hash__ = (hash(self._subs_tree()) if origin else
772 super(GenericMeta, self).__hash__())
773 return self
774
775 def __init__(cls, *args, **kwargs):
776 super().__init__(*args, **kwargs)
777 if not cls.__dict__.get('_is_protocol', None):
778 cls._is_protocol = any(b is Protocol or
779 isinstance(b, _ProtocolMeta) and
780 b.__origin__ is Protocol
781 for b in cls.__bases__)
782 if cls._is_protocol:
783 for base in cls.__mro__[1:]:
784 if not (base in (object, typing.Generic) or
785 base.__module__ == 'collections.abc' and
786 base.__name__ in _PROTO_WHITELIST or
787 isinstance(base, typing.TypingMeta) and base._is_protocol or
788 isinstance(base, GenericMeta) and
789 base.__origin__ is typing.Generic):
790 raise TypeError(f'Protocols can only inherit from other'
791 f' protocols, got {repr(base)}')
792
793 cls.__init__ = _no_init
794
795 def _proto_hook(other):
796 if not cls.__dict__.get('_is_protocol', None):
797 return NotImplemented
798 if not isinstance(other, type):
799 # Same error as for issubclass(1, int)
800 raise TypeError('issubclass() arg 1 must be a class')
801 for attr in _get_protocol_attrs(cls):
802 for base in other.__mro__:
803 if attr in base.__dict__:
804 if base.__dict__[attr] is None:
805 return NotImplemented
806 break
807 annotations = getattr(base, '__annotations__', {})
808 if (isinstance(annotations, typing.Mapping) and
809 attr in annotations and
810 isinstance(other, _ProtocolMeta) and
811 other._is_protocol):
812 break
813 else:
814 return NotImplemented
815 return True
816 if '__subclasshook__' not in cls.__dict__:
817 cls.__subclasshook__ = _proto_hook
818
819 def __instancecheck__(self, instance):
820 # We need this method for situations where attributes are
821 # assigned in __init__.
822 if ((not getattr(self, '_is_protocol', False) or
823 _is_callable_members_only(self)) and
824 issubclass(instance.__class__, self)):
825 return True
826 if self._is_protocol:
827 if all(hasattr(instance, attr) and
828 (not callable(getattr(self, attr, None)) or
829 getattr(instance, attr) is not None)
830 for attr in _get_protocol_attrs(self)):
831 return True
832 return super(GenericMeta, self).__instancecheck__(instance)
833
834 def __subclasscheck__(self, cls):
835 if self.__origin__ is not None:
836 if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools']:
837 raise TypeError("Parameterized generics cannot be used with class "
838 "or instance checks")
839 return False
840 if (self.__dict__.get('_is_protocol', None) and
841 not self.__dict__.get('_is_runtime_protocol', None)):
842 if sys._getframe(1).f_globals['__name__'] in ['abc',
843 'functools',
844 'typing']:
845 return False
846 raise TypeError("Instance and class checks can only be used with"
847 " @runtime protocols")
848 if (self.__dict__.get('_is_runtime_protocol', None) and
849 not _is_callable_members_only(self)):
850 if sys._getframe(1).f_globals['__name__'] in ['abc',
851 'functools',
852 'typing']:
853 return super(GenericMeta, self).__subclasscheck__(cls)
854 raise TypeError("Protocols with non-method members"
855 " don't support issubclass()")
856 return super(GenericMeta, self).__subclasscheck__(cls)
857
858 @typing._tp_cache
859 def __getitem__(self, params):
860 # We also need to copy this from GenericMeta.__getitem__ to get
861 # special treatment of "Protocol". (Comments removed for brevity.)
862 if not isinstance(params, tuple):
863 params = (params,)
864 if not params and _gorg(self) is not typing.Tuple:
865 raise TypeError(
866 f"Parameter list to {self.__qualname__}[...] cannot be empty")
867 msg = "Parameters to generic types must be types."
868 params = tuple(_type_check(p, msg) for p in params)
869 if self in (typing.Generic, Protocol):
870 if not all(isinstance(p, typing.TypeVar) for p in params):
871 raise TypeError(
872 f"Parameters to {repr(self)}[...] must all be type variables")
873 if len(set(params)) != len(params):
874 raise TypeError(
875 f"Parameters to {repr(self)}[...] must all be unique")
876 tvars = params
877 args = params
878 elif self in (typing.Tuple, typing.Callable):
879 tvars = _type_vars(params)
880 args = params
881 elif self.__origin__ in (typing.Generic, Protocol):
882 raise TypeError(f"Cannot subscript already-subscripted {repr(self)}")
883 else:
884 _check_generic(self, params)
885 tvars = _type_vars(params)
886 args = params
887
888 prepend = (self,) if self.__origin__ is None else ()
889 return self.__class__(self.__name__,
890 prepend + self.__bases__,
891 _no_slots_copy(self.__dict__),
892 tvars=tvars,
893 args=args,
894 origin=self,
895 extra=self.__extra__,
896 orig_bases=self.__orig_bases__)
897
898 class Protocol(metaclass=_ProtocolMeta):
899 """Base class for protocol classes. Protocol classes are defined as::
900
901 class Proto(Protocol):
902 def meth(self) -> int:
903 ...
904
905 Such classes are primarily used with static type checkers that recognize
906 structural subtyping (static duck-typing), for example::
907
908 class C:
909 def meth(self) -> int:
910 return 0
911
912 def func(x: Proto) -> int:
913 return x.meth()
914
915 func(C()) # Passes static type check
916
917 See PEP 544 for details. Protocol classes decorated with
918 @typing_extensions.runtime act as simple-minded runtime protocol that checks
919 only the presence of given attributes, ignoring their type signatures.
920
921 Protocol classes can be generic, they are defined as::
922
923 class GenProto(Protocol[T]):
924 def meth(self) -> T:
925 ...
926 """
927 __slots__ = ()
928 _is_protocol = True
929
930 def __new__(cls, *args, **kwds):
931 if _gorg(cls) is Protocol:
932 raise TypeError("Type Protocol cannot be instantiated; "
933 "it can be used only as a base class")
934 return typing._generic_new(cls.__next_in_mro__, cls, *args, **kwds)
935
936
937 # 3.8+
938 if hasattr(typing, 'runtime_checkable'):
939 runtime_checkable = typing.runtime_checkable
940 # 3.6-3.7
941 else:
942 def runtime_checkable(cls):
943 """Mark a protocol class as a runtime protocol, so that it
944 can be used with isinstance() and issubclass(). Raise TypeError
945 if applied to a non-protocol class.
946
947 This allows a simple-minded structural check very similar to the
948 one-offs in collections.abc such as Hashable.
949 """
950 if not isinstance(cls, _ProtocolMeta) or not cls._is_protocol:
951 raise TypeError('@runtime_checkable can be only applied to protocol classes,'
952 f' got {cls!r}')
953 cls._is_runtime_protocol = True
954 return cls
955
956
957 # Exists for backwards compatibility.
958 runtime = runtime_checkable
959
960
961 # 3.8+
962 if hasattr(typing, 'SupportsIndex'):
963 SupportsIndex = typing.SupportsIndex
964 # 3.6-3.7
965 else:
966 @runtime_checkable
967 class SupportsIndex(Protocol):
968 __slots__ = ()
969
970 @abc.abstractmethod
971 def __index__(self) -> int:
972 pass
973
974
975 if sys.version_info >= (3, 9, 2):
976 # The standard library TypedDict in Python 3.8 does not store runtime information
977 # about which (if any) keys are optional. See https://bugs.python.org/issue38834
978 # The standard library TypedDict in Python 3.9.0/1 does not honour the "total"
979 # keyword with old-style TypedDict(). See https://bugs.python.org/issue42059
980 TypedDict = typing.TypedDict
981 else:
982 def _check_fails(cls, other):
983 try:
984 if sys._getframe(1).f_globals['__name__'] not in ['abc',
985 'functools',
986 'typing']:
987 # Typed dicts are only for static structural subtyping.
988 raise TypeError('TypedDict does not support instance and class checks')
989 except (AttributeError, ValueError):
990 pass
991 return False
992
993 def _dict_new(*args, **kwargs):
994 if not args:
995 raise TypeError('TypedDict.__new__(): not enough arguments')
996 _, args = args[0], args[1:] # allow the "cls" keyword be passed
997 return dict(*args, **kwargs)
998
999 _dict_new.__text_signature__ = '($cls, _typename, _fields=None, /, **kwargs)'
1000
1001 def _typeddict_new(*args, total=True, **kwargs):
1002 if not args:
1003 raise TypeError('TypedDict.__new__(): not enough arguments')
1004 _, args = args[0], args[1:] # allow the "cls" keyword be passed
1005 if args:
1006 typename, args = args[0], args[1:] # allow the "_typename" keyword be passed
1007 elif '_typename' in kwargs:
1008 typename = kwargs.pop('_typename')
1009 import warnings
1010 warnings.warn("Passing '_typename' as keyword argument is deprecated",
1011 DeprecationWarning, stacklevel=2)
1012 else:
1013 raise TypeError("TypedDict.__new__() missing 1 required positional "
1014 "argument: '_typename'")
1015 if args:
1016 try:
1017 fields, = args # allow the "_fields" keyword be passed
1018 except ValueError:
1019 raise TypeError('TypedDict.__new__() takes from 2 to 3 '
1020 f'positional arguments but {len(args) + 2} '
1021 'were given')
1022 elif '_fields' in kwargs and len(kwargs) == 1:
1023 fields = kwargs.pop('_fields')
1024 import warnings
1025 warnings.warn("Passing '_fields' as keyword argument is deprecated",
1026 DeprecationWarning, stacklevel=2)
1027 else:
1028 fields = None
1029
1030 if fields is None:
1031 fields = kwargs
1032 elif kwargs:
1033 raise TypeError("TypedDict takes either a dict or keyword arguments,"
1034 " but not both")
1035
1036 ns = {'__annotations__': dict(fields)}
1037 try:
1038 # Setting correct module is necessary to make typed dict classes pickleable.
1039 ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__')
1040 except (AttributeError, ValueError):
1041 pass
1042
1043 return _TypedDictMeta(typename, (), ns, total=total)
1044
1045 _typeddict_new.__text_signature__ = ('($cls, _typename, _fields=None,'
1046 ' /, *, total=True, **kwargs)')
1047
1048 class _TypedDictMeta(type):
1049 def __init__(cls, name, bases, ns, total=True):
1050 super().__init__(name, bases, ns)
1051
1052 def __new__(cls, name, bases, ns, total=True):
1053 # Create new typed dict class object.
1054 # This method is called directly when TypedDict is subclassed,
1055 # or via _typeddict_new when TypedDict is instantiated. This way
1056 # TypedDict supports all three syntaxes described in its docstring.
1057 # Subclasses and instances of TypedDict return actual dictionaries
1058 # via _dict_new.
1059 ns['__new__'] = _typeddict_new if name == 'TypedDict' else _dict_new
1060 tp_dict = super().__new__(cls, name, (dict,), ns)
1061
1062 annotations = {}
1063 own_annotations = ns.get('__annotations__', {})
1064 own_annotation_keys = set(own_annotations.keys())
1065 msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
1066 own_annotations = {
1067 n: typing._type_check(tp, msg) for n, tp in own_annotations.items()
1068 }
1069 required_keys = set()
1070 optional_keys = set()
1071
1072 for base in bases:
1073 annotations.update(base.__dict__.get('__annotations__', {}))
1074 required_keys.update(base.__dict__.get('__required_keys__', ()))
1075 optional_keys.update(base.__dict__.get('__optional_keys__', ()))
1076
1077 annotations.update(own_annotations)
1078 if total:
1079 required_keys.update(own_annotation_keys)
1080 else:
1081 optional_keys.update(own_annotation_keys)
1082
1083 tp_dict.__annotations__ = annotations
1084 tp_dict.__required_keys__ = frozenset(required_keys)
1085 tp_dict.__optional_keys__ = frozenset(optional_keys)
1086 if not hasattr(tp_dict, '__total__'):
1087 tp_dict.__total__ = total
1088 return tp_dict
1089
1090 __instancecheck__ = __subclasscheck__ = _check_fails
1091
1092 TypedDict = _TypedDictMeta('TypedDict', (dict,), {})
1093 TypedDict.__module__ = __name__
1094 TypedDict.__doc__ = \
1095 """A simple typed name space. At runtime it is equivalent to a plain dict.
1096
1097 TypedDict creates a dictionary type that expects all of its
1098 instances to have a certain set of keys, with each key
1099 associated with a value of a consistent type. This expectation
1100 is not checked at runtime but is only enforced by type checkers.
1101 Usage::
1102
1103 class Point2D(TypedDict):
1104 x: int
1105 y: int
1106 label: str
1107
1108 a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
1109 b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
1110
1111 assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
1112
1113 The type info can be accessed via the Point2D.__annotations__ dict, and
1114 the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
1115 TypedDict supports two additional equivalent forms::
1116
1117 Point2D = TypedDict('Point2D', x=int, y=int, label=str)
1118 Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
1119
1120 The class syntax is only supported in Python 3.6+, while two other
1121 syntax forms work for Python 2.7 and 3.2+
1122 """
1123
1124
1125 # Python 3.9+ has PEP 593 (Annotated and modified get_type_hints)
1126 if hasattr(typing, 'Annotated'):
1127 Annotated = typing.Annotated
1128 get_type_hints = typing.get_type_hints
1129 # Not exported and not a public API, but needed for get_origin() and get_args()
1130 # to work.
1131 _AnnotatedAlias = typing._AnnotatedAlias
1132 # 3.7-3.8
1133 elif PEP_560:
1134 class _AnnotatedAlias(typing._GenericAlias, _root=True):
1135 """Runtime representation of an annotated type.
1136
1137 At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
1138 with extra annotations. The alias behaves like a normal typing alias,
1139 instantiating is the same as instantiating the underlying type, binding
1140 it to types is also the same.
1141 """
1142 def __init__(self, origin, metadata):
1143 if isinstance(origin, _AnnotatedAlias):
1144 metadata = origin.__metadata__ + metadata
1145 origin = origin.__origin__
1146 super().__init__(origin, origin)
1147 self.__metadata__ = metadata
1148
1149 def copy_with(self, params):
1150 assert len(params) == 1
1151 new_type = params[0]
1152 return _AnnotatedAlias(new_type, self.__metadata__)
1153
1154 def __repr__(self):
1155 return (f"typing_extensions.Annotated[{typing._type_repr(self.__origin__)}, "
1156 f"{', '.join(repr(a) for a in self.__metadata__)}]")
1157
1158 def __reduce__(self):
1159 return operator.getitem, (
1160 Annotated, (self.__origin__,) + self.__metadata__
1161 )
1162
1163 def __eq__(self, other):
1164 if not isinstance(other, _AnnotatedAlias):
1165 return NotImplemented
1166 if self.__origin__ != other.__origin__:
1167 return False
1168 return self.__metadata__ == other.__metadata__
1169
1170 def __hash__(self):
1171 return hash((self.__origin__, self.__metadata__))
1172
1173 class Annotated:
1174 """Add context specific metadata to a type.
1175
1176 Example: Annotated[int, runtime_check.Unsigned] indicates to the
1177 hypothetical runtime_check module that this type is an unsigned int.
1178 Every other consumer of this type can ignore this metadata and treat
1179 this type as int.
1180
1181 The first argument to Annotated must be a valid type (and will be in
1182 the __origin__ field), the remaining arguments are kept as a tuple in
1183 the __extra__ field.
1184
1185 Details:
1186
1187 - It's an error to call `Annotated` with less than two arguments.
1188 - Nested Annotated are flattened::
1189
1190 Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
1191
1192 - Instantiating an annotated type is equivalent to instantiating the
1193 underlying type::
1194
1195 Annotated[C, Ann1](5) == C(5)
1196
1197 - Annotated can be used as a generic type alias::
1198
1199 Optimized = Annotated[T, runtime.Optimize()]
1200 Optimized[int] == Annotated[int, runtime.Optimize()]
1201
1202 OptimizedList = Annotated[List[T], runtime.Optimize()]
1203 OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
1204 """
1205
1206 __slots__ = ()
1207
1208 def __new__(cls, *args, **kwargs):
1209 raise TypeError("Type Annotated cannot be instantiated.")
1210
1211 @typing._tp_cache
1212 def __class_getitem__(cls, params):
1213 if not isinstance(params, tuple) or len(params) < 2:
1214 raise TypeError("Annotated[...] should be used "
1215 "with at least two arguments (a type and an "
1216 "annotation).")
1217 msg = "Annotated[t, ...]: t must be a type."
1218 origin = typing._type_check(params[0], msg)
1219 metadata = tuple(params[1:])
1220 return _AnnotatedAlias(origin, metadata)
1221
1222 def __init_subclass__(cls, *args, **kwargs):
1223 raise TypeError(
1224 f"Cannot subclass {cls.__module__}.Annotated"
1225 )
1226
1227 def _strip_annotations(t):
1228 """Strips the annotations from a given type.
1229 """
1230 if isinstance(t, _AnnotatedAlias):
1231 return _strip_annotations(t.__origin__)
1232 if isinstance(t, typing._GenericAlias):
1233 stripped_args = tuple(_strip_annotations(a) for a in t.__args__)
1234 if stripped_args == t.__args__:
1235 return t
1236 res = t.copy_with(stripped_args)
1237 res._special = t._special
1238 return res
1239 return t
1240
1241 def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
1242 """Return type hints for an object.
1243
1244 This is often the same as obj.__annotations__, but it handles
1245 forward references encoded as string literals, adds Optional[t] if a
1246 default value equal to None is set and recursively replaces all
1247 'Annotated[T, ...]' with 'T' (unless 'include_extras=True').
1248
1249 The argument may be a module, class, method, or function. The annotations
1250 are returned as a dictionary. For classes, annotations include also
1251 inherited members.
1252
1253 TypeError is raised if the argument is not of a type that can contain
1254 annotations, and an empty dictionary is returned if no annotations are
1255 present.
1256
1257 BEWARE -- the behavior of globalns and localns is counterintuitive
1258 (unless you are familiar with how eval() and exec() work). The
1259 search order is locals first, then globals.
1260
1261 - If no dict arguments are passed, an attempt is made to use the
1262 globals from obj (or the respective module's globals for classes),
1263 and these are also used as the locals. If the object does not appear
1264 to have globals, an empty dictionary is used.
1265
1266 - If one dict argument is passed, it is used for both globals and
1267 locals.
1268
1269 - If two dict arguments are passed, they specify globals and
1270 locals, respectively.
1271 """
1272 hint = typing.get_type_hints(obj, globalns=globalns, localns=localns)
1273 if include_extras:
1274 return hint
1275 return {k: _strip_annotations(t) for k, t in hint.items()}
1276 # 3.6
1277 else:
1278
1279 def _is_dunder(name):
1280 """Returns True if name is a __dunder_variable_name__."""
1281 return len(name) > 4 and name.startswith('__') and name.endswith('__')
1282
1283 # Prior to Python 3.7 types did not have `copy_with`. A lot of the equality
1284 # checks, argument expansion etc. are done on the _subs_tre. As a result we
1285 # can't provide a get_type_hints function that strips out annotations.
1286
1287 class AnnotatedMeta(typing.GenericMeta):
1288 """Metaclass for Annotated"""
1289
1290 def __new__(cls, name, bases, namespace, **kwargs):
1291 if any(b is not object for b in bases):
1292 raise TypeError("Cannot subclass " + str(Annotated))
1293 return super().__new__(cls, name, bases, namespace, **kwargs)
1294
1295 @property
1296 def __metadata__(self):
1297 return self._subs_tree()[2]
1298
1299 def _tree_repr(self, tree):
1300 cls, origin, metadata = tree
1301 if not isinstance(origin, tuple):
1302 tp_repr = typing._type_repr(origin)
1303 else:
1304 tp_repr = origin[0]._tree_repr(origin)
1305 metadata_reprs = ", ".join(repr(arg) for arg in metadata)
1306 return f'{cls}[{tp_repr}, {metadata_reprs}]'
1307
1308 def _subs_tree(self, tvars=None, args=None): # noqa
1309 if self is Annotated:
1310 return Annotated
1311 res = super()._subs_tree(tvars=tvars, args=args)
1312 # Flatten nested Annotated
1313 if isinstance(res[1], tuple) and res[1][0] is Annotated:
1314 sub_tp = res[1][1]
1315 sub_annot = res[1][2]
1316 return (Annotated, sub_tp, sub_annot + res[2])
1317 return res
1318
1319 def _get_cons(self):
1320 """Return the class used to create instance of this type."""
1321 if self.__origin__ is None:
1322 raise TypeError("Cannot get the underlying type of a "
1323 "non-specialized Annotated type.")
1324 tree = self._subs_tree()
1325 while isinstance(tree, tuple) and tree[0] is Annotated:
1326 tree = tree[1]
1327 if isinstance(tree, tuple):
1328 return tree[0]
1329 else:
1330 return tree
1331
1332 @typing._tp_cache
1333 def __getitem__(self, params):
1334 if not isinstance(params, tuple):
1335 params = (params,)
1336 if self.__origin__ is not None: # specializing an instantiated type
1337 return super().__getitem__(params)
1338 elif not isinstance(params, tuple) or len(params) < 2:
1339 raise TypeError("Annotated[...] should be instantiated "
1340 "with at least two arguments (a type and an "
1341 "annotation).")
1342 else:
1343 msg = "Annotated[t, ...]: t must be a type."
1344 tp = typing._type_check(params[0], msg)
1345 metadata = tuple(params[1:])
1346 return self.__class__(
1347 self.__name__,
1348 self.__bases__,
1349 _no_slots_copy(self.__dict__),
1350 tvars=_type_vars((tp,)),
1351 # Metadata is a tuple so it won't be touched by _replace_args et al.
1352 args=(tp, metadata),
1353 origin=self,
1354 )
1355
1356 def __call__(self, *args, **kwargs):
1357 cons = self._get_cons()
1358 result = cons(*args, **kwargs)
1359 try:
1360 result.__orig_class__ = self
1361 except AttributeError:
1362 pass
1363 return result
1364
1365 def __getattr__(self, attr):
1366 # For simplicity we just don't relay all dunder names
1367 if self.__origin__ is not None and not _is_dunder(attr):
1368 return getattr(self._get_cons(), attr)
1369 raise AttributeError(attr)
1370
1371 def __setattr__(self, attr, value):
1372 if _is_dunder(attr) or attr.startswith('_abc_'):
1373 super().__setattr__(attr, value)
1374 elif self.__origin__ is None:
1375 raise AttributeError(attr)
1376 else:
1377 setattr(self._get_cons(), attr, value)
1378
1379 def __instancecheck__(self, obj):
1380 raise TypeError("Annotated cannot be used with isinstance().")
1381
1382 def __subclasscheck__(self, cls):
1383 raise TypeError("Annotated cannot be used with issubclass().")
1384
1385 class Annotated(metaclass=AnnotatedMeta):
1386 """Add context specific metadata to a type.
1387
1388 Example: Annotated[int, runtime_check.Unsigned] indicates to the
1389 hypothetical runtime_check module that this type is an unsigned int.
1390 Every other consumer of this type can ignore this metadata and treat
1391 this type as int.
1392
1393 The first argument to Annotated must be a valid type, the remaining
1394 arguments are kept as a tuple in the __metadata__ field.
1395
1396 Details:
1397
1398 - It's an error to call `Annotated` with less than two arguments.
1399 - Nested Annotated are flattened::
1400
1401 Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
1402
1403 - Instantiating an annotated type is equivalent to instantiating the
1404 underlying type::
1405
1406 Annotated[C, Ann1](5) == C(5)
1407
1408 - Annotated can be used as a generic type alias::
1409
1410 Optimized = Annotated[T, runtime.Optimize()]
1411 Optimized[int] == Annotated[int, runtime.Optimize()]
1412
1413 OptimizedList = Annotated[List[T], runtime.Optimize()]
1414 OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
1415 """
1416
1417 # Python 3.8 has get_origin() and get_args() but those implementations aren't
1418 # Annotated-aware, so we can't use those. Python 3.9's versions don't support
1419 # ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do.
1420 if sys.version_info[:2] >= (3, 10):
1421 get_origin = typing.get_origin
1422 get_args = typing.get_args
1423 # 3.7-3.9
1424 elif PEP_560:
1425 try:
1426 # 3.9+
1427 from typing import _BaseGenericAlias
1428 except ImportError:
1429 _BaseGenericAlias = typing._GenericAlias
1430 try:
1431 # 3.9+
1432 from typing import GenericAlias
1433 except ImportError:
1434 GenericAlias = typing._GenericAlias
1435
1436 def get_origin(tp):
1437 """Get the unsubscripted version of a type.
1438
1439 This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
1440 and Annotated. Return None for unsupported types. Examples::
1441
1442 get_origin(Literal[42]) is Literal
1443 get_origin(int) is None
1444 get_origin(ClassVar[int]) is ClassVar
1445 get_origin(Generic) is Generic
1446 get_origin(Generic[T]) is Generic
1447 get_origin(Union[T, int]) is Union
1448 get_origin(List[Tuple[T, T]][int]) == list
1449 get_origin(P.args) is P
1450 """
1451 if isinstance(tp, _AnnotatedAlias):
1452 return Annotated
1453 if isinstance(tp, (typing._GenericAlias, GenericAlias, _BaseGenericAlias,
1454 ParamSpecArgs, ParamSpecKwargs)):
1455 return tp.__origin__
1456 if tp is typing.Generic:
1457 return typing.Generic
1458 return None
1459
1460 def get_args(tp):
1461 """Get type arguments with all substitutions performed.
1462
1463 For unions, basic simplifications used by Union constructor are performed.
1464 Examples::
1465 get_args(Dict[str, int]) == (str, int)
1466 get_args(int) == ()
1467 get_args(Union[int, Union[T, int], str][int]) == (int, str)
1468 get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
1469 get_args(Callable[[], T][int]) == ([], int)
1470 """
1471 if isinstance(tp, _AnnotatedAlias):
1472 return (tp.__origin__,) + tp.__metadata__
1473 if isinstance(tp, (typing._GenericAlias, GenericAlias)):
1474 if getattr(tp, "_special", False):
1475 return ()
1476 res = tp.__args__
1477 if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis:
1478 res = (list(res[:-1]), res[-1])
1479 return res
1480 return ()
1481
1482
1483 # 3.10+
1484 if hasattr(typing, 'TypeAlias'):
1485 TypeAlias = typing.TypeAlias
1486 # 3.9
1487 elif sys.version_info[:2] >= (3, 9):
1488 class _TypeAliasForm(typing._SpecialForm, _root=True):
1489 def __repr__(self):
1490 return 'typing_extensions.' + self._name
1491
1492 @_TypeAliasForm
1493 def TypeAlias(self, parameters):
1494 """Special marker indicating that an assignment should
1495 be recognized as a proper type alias definition by type
1496 checkers.
1497
1498 For example::
1499
1500 Predicate: TypeAlias = Callable[..., bool]
1501
1502 It's invalid when used anywhere except as in the example above.
1503 """
1504 raise TypeError(f"{self} is not subscriptable")
1505 # 3.7-3.8
1506 elif sys.version_info[:2] >= (3, 7):
1507 class _TypeAliasForm(typing._SpecialForm, _root=True):
1508 def __repr__(self):
1509 return 'typing_extensions.' + self._name
1510
1511 TypeAlias = _TypeAliasForm('TypeAlias',
1512 doc="""Special marker indicating that an assignment should
1513 be recognized as a proper type alias definition by type
1514 checkers.
1515
1516 For example::
1517
1518 Predicate: TypeAlias = Callable[..., bool]
1519
1520 It's invalid when used anywhere except as in the example
1521 above.""")
1522 # 3.6
1523 else:
1524 class _TypeAliasMeta(typing.TypingMeta):
1525 """Metaclass for TypeAlias"""
1526
1527 def __repr__(self):
1528 return 'typing_extensions.TypeAlias'
1529
1530 class _TypeAliasBase(typing._FinalTypingBase, metaclass=_TypeAliasMeta, _root=True):
1531 """Special marker indicating that an assignment should
1532 be recognized as a proper type alias definition by type
1533 checkers.
1534
1535 For example::
1536
1537 Predicate: TypeAlias = Callable[..., bool]
1538
1539 It's invalid when used anywhere except as in the example above.
1540 """
1541 __slots__ = ()
1542
1543 def __instancecheck__(self, obj):
1544 raise TypeError("TypeAlias cannot be used with isinstance().")
1545
1546 def __subclasscheck__(self, cls):
1547 raise TypeError("TypeAlias cannot be used with issubclass().")
1548
1549 def __repr__(self):
1550 return 'typing_extensions.TypeAlias'
1551
1552 TypeAlias = _TypeAliasBase(_root=True)
1553
1554
1555 # Python 3.10+ has PEP 612
1556 if hasattr(typing, 'ParamSpecArgs'):
1557 ParamSpecArgs = typing.ParamSpecArgs
1558 ParamSpecKwargs = typing.ParamSpecKwargs
1559 # 3.6-3.9
1560 else:
1561 class _Immutable:
1562 """Mixin to indicate that object should not be copied."""
1563 __slots__ = ()
1564
1565 def __copy__(self):
1566 return self
1567
1568 def __deepcopy__(self, memo):
1569 return self
1570
1571 class ParamSpecArgs(_Immutable):
1572 """The args for a ParamSpec object.
1573
1574 Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.
1575
1576 ParamSpecArgs objects have a reference back to their ParamSpec:
1577
1578 P.args.__origin__ is P
1579
1580 This type is meant for runtime introspection and has no special meaning to
1581 static type checkers.
1582 """
1583 def __init__(self, origin):
1584 self.__origin__ = origin
1585
1586 def __repr__(self):
1587 return f"{self.__origin__.__name__}.args"
1588
1589 class ParamSpecKwargs(_Immutable):
1590 """The kwargs for a ParamSpec object.
1591
1592 Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs.
1593
1594 ParamSpecKwargs objects have a reference back to their ParamSpec:
1595
1596 P.kwargs.__origin__ is P
1597
1598 This type is meant for runtime introspection and has no special meaning to
1599 static type checkers.
1600 """
1601 def __init__(self, origin):
1602 self.__origin__ = origin
1603
1604 def __repr__(self):
1605 return f"{self.__origin__.__name__}.kwargs"
1606
1607 # 3.10+
1608 if hasattr(typing, 'ParamSpec'):
1609 ParamSpec = typing.ParamSpec
1610 # 3.6-3.9
1611 else:
1612
1613 # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
1614 class ParamSpec(list):
1615 """Parameter specification variable.
1616
1617 Usage::
1618
1619 P = ParamSpec('P')
1620
1621 Parameter specification variables exist primarily for the benefit of static
1622 type checkers. They are used to forward the parameter types of one
1623 callable to another callable, a pattern commonly found in higher order
1624 functions and decorators. They are only valid when used in ``Concatenate``,
1625 or s the first argument to ``Callable``. In Python 3.10 and higher,
1626 they are also supported in user-defined Generics at runtime.
1627 See class Generic for more information on generic types. An
1628 example for annotating a decorator::
1629
1630 T = TypeVar('T')
1631 P = ParamSpec('P')
1632
1633 def add_logging(f: Callable[P, T]) -> Callable[P, T]:
1634 '''A type-safe decorator to add logging to a function.'''
1635 def inner(*args: P.args, **kwargs: P.kwargs) -> T:
1636 logging.info(f'{f.__name__} was called')
1637 return f(*args, **kwargs)
1638 return inner
1639
1640 @add_logging
1641 def add_two(x: float, y: float) -> float:
1642 '''Add two numbers together.'''
1643 return x + y
1644
1645 Parameter specification variables defined with covariant=True or
1646 contravariant=True can be used to declare covariant or contravariant
1647 generic types. These keyword arguments are valid, but their actual semantics
1648 are yet to be decided. See PEP 612 for details.
1649
1650 Parameter specification variables can be introspected. e.g.:
1651
1652 P.__name__ == 'T'
1653 P.__bound__ == None
1654 P.__covariant__ == False
1655 P.__contravariant__ == False
1656
1657 Note that only parameter specification variables defined in global scope can
1658 be pickled.
1659 """
1660
1661 # Trick Generic __parameters__.
1662 __class__ = typing.TypeVar
1663
1664 @property
1665 def args(self):
1666 return ParamSpecArgs(self)
1667
1668 @property
1669 def kwargs(self):
1670 return ParamSpecKwargs(self)
1671
1672 def __init__(self, name, *, bound=None, covariant=False, contravariant=False):
1673 super().__init__([self])
1674 self.__name__ = name
1675 self.__covariant__ = bool(covariant)
1676 self.__contravariant__ = bool(contravariant)
1677 if bound:
1678 self.__bound__ = typing._type_check(bound, 'Bound must be a type.')
1679 else:
1680 self.__bound__ = None
1681
1682 # for pickling:
1683 try:
1684 def_mod = sys._getframe(1).f_globals.get('__name__', '__main__')
1685 except (AttributeError, ValueError):
1686 def_mod = None
1687 if def_mod != 'typing_extensions':
1688 self.__module__ = def_mod
1689
1690 def __repr__(self):
1691 if self.__covariant__:
1692 prefix = '+'
1693 elif self.__contravariant__:
1694 prefix = '-'
1695 else:
1696 prefix = '~'
1697 return prefix + self.__name__
1698
1699 def __hash__(self):
1700 return object.__hash__(self)
1701
1702 def __eq__(self, other):
1703 return self is other
1704
1705 def __reduce__(self):
1706 return self.__name__
1707
1708 # Hack to get typing._type_check to pass.
1709 def __call__(self, *args, **kwargs):
1710 pass
1711
1712 if not PEP_560:
1713 # Only needed in 3.6.
1714 def _get_type_vars(self, tvars):
1715 if self not in tvars:
1716 tvars.append(self)
1717
1718
1719 # 3.6-3.9
1720 if not hasattr(typing, 'Concatenate'):
1721 # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
1722 class _ConcatenateGenericAlias(list):
1723
1724 # Trick Generic into looking into this for __parameters__.
1725 if PEP_560:
1726 __class__ = typing._GenericAlias
1727 else:
1728 __class__ = typing._TypingBase
1729
1730 # Flag in 3.8.
1731 _special = False
1732 # Attribute in 3.6 and earlier.
1733 _gorg = typing.Generic
1734
1735 def __init__(self, origin, args):
1736 super().__init__(args)
1737 self.__origin__ = origin
1738 self.__args__ = args
1739
1740 def __repr__(self):
1741 _type_repr = typing._type_repr
1742 return (f'{_type_repr(self.__origin__)}'
1743 f'[{", ".join(_type_repr(arg) for arg in self.__args__)}]')
1744
1745 def __hash__(self):
1746 return hash((self.__origin__, self.__args__))
1747
1748 # Hack to get typing._type_check to pass in Generic.
1749 def __call__(self, *args, **kwargs):
1750 pass
1751
1752 @property
1753 def __parameters__(self):
1754 return tuple(
1755 tp for tp in self.__args__ if isinstance(tp, (typing.TypeVar, ParamSpec))
1756 )
1757
1758 if not PEP_560:
1759 # Only required in 3.6.
1760 def _get_type_vars(self, tvars):
1761 if self.__origin__ and self.__parameters__:
1762 typing._get_type_vars(self.__parameters__, tvars)
1763
1764
1765 # 3.6-3.9
1766 @typing._tp_cache
1767 def _concatenate_getitem(self, parameters):
1768 if parameters == ():
1769 raise TypeError("Cannot take a Concatenate of no types.")
1770 if not isinstance(parameters, tuple):
1771 parameters = (parameters,)
1772 if not isinstance(parameters[-1], ParamSpec):
1773 raise TypeError("The last parameter to Concatenate should be a "
1774 "ParamSpec variable.")
1775 msg = "Concatenate[arg, ...]: each arg must be a type."
1776 parameters = tuple(typing._type_check(p, msg) for p in parameters)
1777 return _ConcatenateGenericAlias(self, parameters)
1778
1779
1780 # 3.10+
1781 if hasattr(typing, 'Concatenate'):
1782 Concatenate = typing.Concatenate
1783 _ConcatenateGenericAlias = typing._ConcatenateGenericAlias # noqa
1784 # 3.9
1785 elif sys.version_info[:2] >= (3, 9):
1786 @_TypeAliasForm
1787 def Concatenate(self, parameters):
1788 """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
1789 higher order function which adds, removes or transforms parameters of a
1790 callable.
1791
1792 For example::
1793
1794 Callable[Concatenate[int, P], int]
1795
1796 See PEP 612 for detailed information.
1797 """
1798 return _concatenate_getitem(self, parameters)
1799 # 3.7-8
1800 elif sys.version_info[:2] >= (3, 7):
1801 class _ConcatenateForm(typing._SpecialForm, _root=True):
1802 def __repr__(self):
1803 return 'typing_extensions.' + self._name
1804
1805 def __getitem__(self, parameters):
1806 return _concatenate_getitem(self, parameters)
1807
1808 Concatenate = _ConcatenateForm(
1809 'Concatenate',
1810 doc="""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
1811 higher order function which adds, removes or transforms parameters of a
1812 callable.
1813
1814 For example::
1815
1816 Callable[Concatenate[int, P], int]
1817
1818 See PEP 612 for detailed information.
1819 """)
1820 # 3.6
1821 else:
1822 class _ConcatenateAliasMeta(typing.TypingMeta):
1823 """Metaclass for Concatenate."""
1824
1825 def __repr__(self):
1826 return 'typing_extensions.Concatenate'
1827
1828 class _ConcatenateAliasBase(typing._FinalTypingBase,
1829 metaclass=_ConcatenateAliasMeta,
1830 _root=True):
1831 """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
1832 higher order function which adds, removes or transforms parameters of a
1833 callable.
1834
1835 For example::
1836
1837 Callable[Concatenate[int, P], int]
1838
1839 See PEP 612 for detailed information.
1840 """
1841 __slots__ = ()
1842
1843 def __instancecheck__(self, obj):
1844 raise TypeError("Concatenate cannot be used with isinstance().")
1845
1846 def __subclasscheck__(self, cls):
1847 raise TypeError("Concatenate cannot be used with issubclass().")
1848
1849 def __repr__(self):
1850 return 'typing_extensions.Concatenate'
1851
1852 def __getitem__(self, parameters):
1853 return _concatenate_getitem(self, parameters)
1854
1855 Concatenate = _ConcatenateAliasBase(_root=True)
1856
1857 # 3.10+
1858 if hasattr(typing, 'TypeGuard'):
1859 TypeGuard = typing.TypeGuard
1860 # 3.9
1861 elif sys.version_info[:2] >= (3, 9):
1862 class _TypeGuardForm(typing._SpecialForm, _root=True):
1863 def __repr__(self):
1864 return 'typing_extensions.' + self._name
1865
1866 @_TypeGuardForm
1867 def TypeGuard(self, parameters):
1868 """Special typing form used to annotate the return type of a user-defined
1869 type guard function. ``TypeGuard`` only accepts a single type argument.
1870 At runtime, functions marked this way should return a boolean.
1871
1872 ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
1873 type checkers to determine a more precise type of an expression within a
1874 program's code flow. Usually type narrowing is done by analyzing
1875 conditional code flow and applying the narrowing to a block of code. The
1876 conditional expression here is sometimes referred to as a "type guard".
1877
1878 Sometimes it would be convenient to use a user-defined boolean function
1879 as a type guard. Such a function should use ``TypeGuard[...]`` as its
1880 return type to alert static type checkers to this intention.
1881
1882 Using ``-> TypeGuard`` tells the static type checker that for a given
1883 function:
1884
1885 1. The return value is a boolean.
1886 2. If the return value is ``True``, the type of its argument
1887 is the type inside ``TypeGuard``.
1888
1889 For example::
1890
1891 def is_str(val: Union[str, float]):
1892 # "isinstance" type guard
1893 if isinstance(val, str):
1894 # Type of ``val`` is narrowed to ``str``
1895 ...
1896 else:
1897 # Else, type of ``val`` is narrowed to ``float``.
1898 ...
1899
1900 Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
1901 form of ``TypeA`` (it can even be a wider form) and this may lead to
1902 type-unsafe results. The main reason is to allow for things like
1903 narrowing ``List[object]`` to ``List[str]`` even though the latter is not
1904 a subtype of the former, since ``List`` is invariant. The responsibility of
1905 writing type-safe type guards is left to the user.
1906
1907 ``TypeGuard`` also works with type variables. For more information, see
1908 PEP 647 (User-Defined Type Guards).
1909 """
1910 item = typing._type_check(parameters, f'{self} accepts only single type.')
1911 return typing._GenericAlias(self, (item,))
1912 # 3.7-3.8
1913 elif sys.version_info[:2] >= (3, 7):
1914 class _TypeGuardForm(typing._SpecialForm, _root=True):
1915
1916 def __repr__(self):
1917 return 'typing_extensions.' + self._name
1918
1919 def __getitem__(self, parameters):
1920 item = typing._type_check(parameters,
1921 f'{self._name} accepts only a single type')
1922 return typing._GenericAlias(self, (item,))
1923
1924 TypeGuard = _TypeGuardForm(
1925 'TypeGuard',
1926 doc="""Special typing form used to annotate the return type of a user-defined
1927 type guard function. ``TypeGuard`` only accepts a single type argument.
1928 At runtime, functions marked this way should return a boolean.
1929
1930 ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
1931 type checkers to determine a more precise type of an expression within a
1932 program's code flow. Usually type narrowing is done by analyzing
1933 conditional code flow and applying the narrowing to a block of code. The
1934 conditional expression here is sometimes referred to as a "type guard".
1935
1936 Sometimes it would be convenient to use a user-defined boolean function
1937 as a type guard. Such a function should use ``TypeGuard[...]`` as its
1938 return type to alert static type checkers to this intention.
1939
1940 Using ``-> TypeGuard`` tells the static type checker that for a given
1941 function:
1942
1943 1. The return value is a boolean.
1944 2. If the return value is ``True``, the type of its argument
1945 is the type inside ``TypeGuard``.
1946
1947 For example::
1948
1949 def is_str(val: Union[str, float]):
1950 # "isinstance" type guard
1951 if isinstance(val, str):
1952 # Type of ``val`` is narrowed to ``str``
1953 ...
1954 else:
1955 # Else, type of ``val`` is narrowed to ``float``.
1956 ...
1957
1958 Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
1959 form of ``TypeA`` (it can even be a wider form) and this may lead to
1960 type-unsafe results. The main reason is to allow for things like
1961 narrowing ``List[object]`` to ``List[str]`` even though the latter is not
1962 a subtype of the former, since ``List`` is invariant. The responsibility of
1963 writing type-safe type guards is left to the user.
1964
1965 ``TypeGuard`` also works with type variables. For more information, see
1966 PEP 647 (User-Defined Type Guards).
1967 """)
1968 # 3.6
1969 else:
1970 class _TypeGuard(typing._FinalTypingBase, _root=True):
1971 """Special typing form used to annotate the return type of a user-defined
1972 type guard function. ``TypeGuard`` only accepts a single type argument.
1973 At runtime, functions marked this way should return a boolean.
1974
1975 ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
1976 type checkers to determine a more precise type of an expression within a
1977 program's code flow. Usually type narrowing is done by analyzing
1978 conditional code flow and applying the narrowing to a block of code. The
1979 conditional expression here is sometimes referred to as a "type guard".
1980
1981 Sometimes it would be convenient to use a user-defined boolean function
1982 as a type guard. Such a function should use ``TypeGuard[...]`` as its
1983 return type to alert static type checkers to this intention.
1984
1985 Using ``-> TypeGuard`` tells the static type checker that for a given
1986 function:
1987
1988 1. The return value is a boolean.
1989 2. If the return value is ``True``, the type of its argument
1990 is the type inside ``TypeGuard``.
1991
1992 For example::
1993
1994 def is_str(val: Union[str, float]):
1995 # "isinstance" type guard
1996 if isinstance(val, str):
1997 # Type of ``val`` is narrowed to ``str``
1998 ...
1999 else:
2000 # Else, type of ``val`` is narrowed to ``float``.
2001 ...
2002
2003 Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
2004 form of ``TypeA`` (it can even be a wider form) and this may lead to
2005 type-unsafe results. The main reason is to allow for things like
2006 narrowing ``List[object]`` to ``List[str]`` even though the latter is not
2007 a subtype of the former, since ``List`` is invariant. The responsibility of
2008 writing type-safe type guards is left to the user.
2009
2010 ``TypeGuard`` also works with type variables. For more information, see
2011 PEP 647 (User-Defined Type Guards).
2012 """
2013
2014 __slots__ = ('__type__',)
2015
2016 def __init__(self, tp=None, **kwds):
2017 self.__type__ = tp
2018
2019 def __getitem__(self, item):
2020 cls = type(self)
2021 if self.__type__ is None:
2022 return cls(typing._type_check(item,
2023 f'{cls.__name__[1:]} accepts only a single type.'),
2024 _root=True)
2025 raise TypeError(f'{cls.__name__[1:]} cannot be further subscripted')
2026
2027 def _eval_type(self, globalns, localns):
2028 new_tp = typing._eval_type(self.__type__, globalns, localns)
2029 if new_tp == self.__type__:
2030 return self
2031 return type(self)(new_tp, _root=True)
2032
2033 def __repr__(self):
2034 r = super().__repr__()
2035 if self.__type__ is not None:
2036 r += f'[{typing._type_repr(self.__type__)}]'
2037 return r
2038
2039 def __hash__(self):
2040 return hash((type(self).__name__, self.__type__))
2041
2042 def __eq__(self, other):
2043 if not isinstance(other, _TypeGuard):
2044 return NotImplemented
2045 if self.__type__ is not None:
2046 return self.__type__ == other.__type__
2047 return self is other
2048
2049 TypeGuard = _TypeGuard(_root=True)
2050
2051 if hasattr(typing, "Self"):
2052 Self = typing.Self
2053 elif sys.version_info[:2] >= (3, 7):
2054 # Vendored from cpython typing._SpecialFrom
2055 class _SpecialForm(typing._Final, _root=True):
2056 __slots__ = ('_name', '__doc__', '_getitem')
2057
2058 def __init__(self, getitem):
2059 self._getitem = getitem
2060 self._name = getitem.__name__
2061 self.__doc__ = getitem.__doc__
2062
2063 def __getattr__(self, item):
2064 if item in {'__name__', '__qualname__'}:
2065 return self._name
2066
2067 raise AttributeError(item)
2068
2069 def __mro_entries__(self, bases):
2070 raise TypeError(f"Cannot subclass {self!r}")
2071
2072 def __repr__(self):
2073 return f'typing_extensions.{self._name}'
2074
2075 def __reduce__(self):
2076 return self._name
2077
2078 def __call__(self, *args, **kwds):
2079 raise TypeError(f"Cannot instantiate {self!r}")
2080
2081 def __or__(self, other):
2082 return typing.Union[self, other]
2083
2084 def __ror__(self, other):
2085 return typing.Union[other, self]
2086
2087 def __instancecheck__(self, obj):
2088 raise TypeError(f"{self} cannot be used with isinstance()")
2089
2090 def __subclasscheck__(self, cls):
2091 raise TypeError(f"{self} cannot be used with issubclass()")
2092
2093 @typing._tp_cache
2094 def __getitem__(self, parameters):
2095 return self._getitem(self, parameters)
2096
2097 @_SpecialForm
2098 def Self(self, params):
2099 """Used to spell the type of "self" in classes.
2100
2101 Example::
2102
2103 from typing import Self
2104
2105 class ReturnsSelf:
2106 def parse(self, data: bytes) -> Self:
2107 ...
2108 return self
2109
2110 """
2111
2112 raise TypeError(f"{self} is not subscriptable")
2113 else:
2114 class _Self(typing._FinalTypingBase, _root=True):
2115 """Used to spell the type of "self" in classes.
2116
2117 Example::
2118
2119 from typing import Self
2120
2121 class ReturnsSelf:
2122 def parse(self, data: bytes) -> Self:
2123 ...
2124 return self
2125
2126 """
2127
2128 __slots__ = ()
2129
2130 def __instancecheck__(self, obj):
2131 raise TypeError(f"{self} cannot be used with isinstance().")
2132
2133 def __subclasscheck__(self, cls):
2134 raise TypeError(f"{self} cannot be used with issubclass().")
2135
2136 Self = _Self(_root=True)
2137
2138
2139 if hasattr(typing, 'Required'):
2140 Required = typing.Required
2141 NotRequired = typing.NotRequired
2142 elif sys.version_info[:2] >= (3, 9):
2143 class _ExtensionsSpecialForm(typing._SpecialForm, _root=True):
2144 def __repr__(self):
2145 return 'typing_extensions.' + self._name
2146
2147 @_ExtensionsSpecialForm
2148 def Required(self, parameters):
2149 """A special typing construct to mark a key of a total=False TypedDict
2150 as required. For example:
2151
2152 class Movie(TypedDict, total=False):
2153 title: Required[str]
2154 year: int
2155
2156 m = Movie(
2157 title='The Matrix', # typechecker error if key is omitted
2158 year=1999,
2159 )
2160
2161 There is no runtime checking that a required key is actually provided
2162 when instantiating a related TypedDict.
2163 """
2164 item = typing._type_check(parameters, f'{self._name} accepts only single type')
2165 return typing._GenericAlias(self, (item,))
2166
2167 @_ExtensionsSpecialForm
2168 def NotRequired(self, parameters):
2169 """A special typing construct to mark a key of a TypedDict as
2170 potentially missing. For example:
2171
2172 class Movie(TypedDict):
2173 title: str
2174 year: NotRequired[int]
2175
2176 m = Movie(
2177 title='The Matrix', # typechecker error if key is omitted
2178 year=1999,
2179 )
2180 """
2181 item = typing._type_check(parameters, f'{self._name} accepts only single type')
2182 return typing._GenericAlias(self, (item,))
2183
2184 elif sys.version_info[:2] >= (3, 7):
2185 class _RequiredForm(typing._SpecialForm, _root=True):
2186 def __repr__(self):
2187 return 'typing_extensions.' + self._name
2188
2189 def __getitem__(self, parameters):
2190 item = typing._type_check(parameters,
2191 '{} accepts only single type'.format(self._name))
2192 return typing._GenericAlias(self, (item,))
2193
2194 Required = _RequiredForm(
2195 'Required',
2196 doc="""A special typing construct to mark a key of a total=False TypedDict
2197 as required. For example:
2198
2199 class Movie(TypedDict, total=False):
2200 title: Required[str]
2201 year: int
2202
2203 m = Movie(
2204 title='The Matrix', # typechecker error if key is omitted
2205 year=1999,
2206 )
2207
2208 There is no runtime checking that a required key is actually provided
2209 when instantiating a related TypedDict.
2210 """)
2211 NotRequired = _RequiredForm(
2212 'NotRequired',
2213 doc="""A special typing construct to mark a key of a TypedDict as
2214 potentially missing. For example:
2215
2216 class Movie(TypedDict):
2217 title: str
2218 year: NotRequired[int]
2219
2220 m = Movie(
2221 title='The Matrix', # typechecker error if key is omitted
2222 year=1999,
2223 )
2224 """)
2225 else:
2226 # NOTE: Modeled after _Final's implementation when _FinalTypingBase available
2227 class _MaybeRequired(typing._FinalTypingBase, _root=True):
2228 __slots__ = ('__type__',)
2229
2230 def __init__(self, tp=None, **kwds):
2231 self.__type__ = tp
2232
2233 def __getitem__(self, item):
2234 cls = type(self)
2235 if self.__type__ is None:
2236 return cls(typing._type_check(item,
2237 '{} accepts only single type.'.format(cls.__name__[1:])),
2238 _root=True)
2239 raise TypeError('{} cannot be further subscripted'
2240 .format(cls.__name__[1:]))
2241
2242 def _eval_type(self, globalns, localns):
2243 new_tp = typing._eval_type(self.__type__, globalns, localns)
2244 if new_tp == self.__type__:
2245 return self
2246 return type(self)(new_tp, _root=True)
2247
2248 def __repr__(self):
2249 r = super().__repr__()
2250 if self.__type__ is not None:
2251 r += '[{}]'.format(typing._type_repr(self.__type__))
2252 return r
2253
2254 def __hash__(self):
2255 return hash((type(self).__name__, self.__type__))
2256
2257 def __eq__(self, other):
2258 if not isinstance(other, type(self)):
2259 return NotImplemented
2260 if self.__type__ is not None:
2261 return self.__type__ == other.__type__
2262 return self is other
2263
2264 class _Required(_MaybeRequired, _root=True):
2265 """A special typing construct to mark a key of a total=False TypedDict
2266 as required. For example:
2267
2268 class Movie(TypedDict, total=False):
2269 title: Required[str]
2270 year: int
2271
2272 m = Movie(
2273 title='The Matrix', # typechecker error if key is omitted
2274 year=1999,
2275 )
2276
2277 There is no runtime checking that a required key is actually provided
2278 when instantiating a related TypedDict.
2279 """
2280
2281 class _NotRequired(_MaybeRequired, _root=True):
2282 """A special typing construct to mark a key of a TypedDict as
2283 potentially missing. For example:
2284
2285 class Movie(TypedDict):
2286 title: str
2287 year: NotRequired[int]
2288
2289 m = Movie(
2290 title='The Matrix', # typechecker error if key is omitted
2291 year=1999,
2292 )
2293 """
2294
2295 Required = _Required(_root=True)
2296 NotRequired = _NotRequired(_root=True)