8 # After PEP 560, internal typing API was substantially reworked.
9 # This is especially important for Protocol class which uses internal APIs
11 PEP_560
= sys
.version_info
[:3] >= (3, 7, 0)
17 from typing
import GenericMeta
, _type_vars
# noqa
19 # The two functions below are copies of typing internal helpers.
20 # They are needed by _ProtocolMeta
23 def _no_slots_copy(dct
):
25 if '__slots__' in dict_copy
:
26 for slot
in dict_copy
['__slots__']:
27 dict_copy
.pop(slot
, None)
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
__)
37 raise TypeError(f
"Too {'many' if alen > elen else 'few'} arguments for {cls};"
38 f
" actual {alen}, expected {elen}")
41 # Please keep __all__ alphabetized within each category.
43 # Super-special typing primitives.
51 # ABCs (from collections.abc).
57 'AsyncContextManager',
60 # Concrete collection types.
68 # Structural checks, a.k.a. protocols.
88 __all__
.extend(["get_args", "get_origin", "get_type_hints"])
91 if hasattr(typing
, 'NoReturn'):
92 NoReturn
= typing
.NoReturn
95 class _NoReturn(typing
._FinalTypingBase
, _root
=True):
96 """Special type indicating functions that never return.
99 from typing import NoReturn
101 def stop() -> NoReturn:
102 raise Exception('no way')
104 This type is invalid in other positions, e.g., ``List[NoReturn]``
105 will fail in static type checkers.
109 def __instancecheck__(self
, obj
):
110 raise TypeError("NoReturn cannot be used with isinstance().")
112 def __subclasscheck__(self
, cls
):
113 raise TypeError("NoReturn cannot be used with issubclass().")
115 NoReturn
= _NoReturn(_root
=True)
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.
125 ClassVar
= typing
.ClassVar
127 # On older versions of typing there is an internal class named "Final".
129 if hasattr(typing
, 'Final') and sys
.version_info
[:2] >= (3, 7):
132 elif sys
.version_info
[:2] >= (3, 7):
133 class _FinalForm(typing
._SpecialForm
, _root
=True):
136 return 'typing_extensions.' + self
._name
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
,))
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.
148 MAX_SIZE: Final = 9000
149 MAX_SIZE += 1 # Error reported by type checker
152 TIMEOUT: Final[int] = 10
153 class FastConnector(Connection):
154 TIMEOUT = 1 # Error reported by type checker
156 There is no runtime checking of these properties.""")
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.
164 MAX_SIZE: Final = 9000
165 MAX_SIZE += 1 # Error reported by type checker
168 TIMEOUT: Final[int] = 10
169 class FastConnector(Connection):
170 TIMEOUT = 1 # Error reported by type checker
172 There is no runtime checking of these properties.
175 __slots__
= ('__type__',)
177 def __init__(self
, tp
=None, **kwds
):
180 def __getitem__(self
, item
):
182 if self
.__type
__ is None:
183 return cls(typing
._type
_check
(item
,
184 f
'{cls.__name__[1:]} accepts only single type.'),
186 raise TypeError(f
'{cls.__name__[1:]} cannot be further subscripted')
188 def _eval_type(self
, globalns
, localns
):
189 new_tp
= typing
._eval
_type
(self
.__type
__, globalns
, localns
)
190 if new_tp
== self
.__type
__:
192 return type(self
)(new_tp
, _root
=True)
195 r
= super().__repr
__()
196 if self
.__type
__ is not None:
197 r
+= f
'[{typing._type_repr(self.__type__)}]'
201 return hash((type(self
).__name
__, self
.__type
__))
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
__
210 Final
= _Final(_root
=True)
214 if hasattr(typing
, 'final'):
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:
225 def done(self) -> None:
228 def done(self) -> None: # Error reported by type checker
233 class Other(Leaf): # Error reported by type checker
236 There is no runtime checking of these properties.
242 return typing
.TypeVar(name
)
246 if hasattr(typing
, 'Literal'):
247 Literal
= typing
.Literal
249 elif sys
.version_info
[:2] >= (3, 7):
250 class _LiteralForm(typing
._SpecialForm
, _root
=True):
253 return 'typing_extensions.' + self
._name
255 def __getitem__(self
, parameters
):
256 return typing
._GenericAlias
(self
, parameters
)
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:
265 The type checker understands that 'var' is literally equal to
266 the value 4 and no other value.
268 Literal[...] cannot be subclassed. There is no runtime
269 checking verifying that the parameter is actually a value
270 instead of a type.""")
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:
280 The type checker understands that 'var' is literally equal to the
281 value 4 and no other value.
283 Literal[...] cannot be subclassed. There is no runtime checking
284 verifying that the parameter is actually a value instead of a type.
287 __slots__
= ('__values__',)
289 def __init__(self
, values
=None, **kwds
):
290 self
.__values
__ = values
292 def __getitem__(self
, values
):
294 if self
.__values
__ is None:
295 if not isinstance(values
, tuple):
297 return cls(values
, _root
=True)
298 raise TypeError(f
'{cls.__name__[1:]} cannot be further subscripted')
300 def _eval_type(self
, globalns
, localns
):
304 r
= super().__repr
__()
305 if self
.__values
__ is not None:
306 r
+= f
'[{", ".join(map(typing._type_repr, self.__values__))}]'
310 return hash((type(self
).__name
__, self
.__values
__))
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
__
319 Literal
= _Literal(_root
=True)
322 _overload_dummy
= typing
._overload
_dummy
# noqa
323 overload
= typing
.overload
326 # This is not a real generic class. Don't use outside annotations.
329 # Various ABCs mimicking those in collections.abc.
330 # A few are simply re-exported for completeness.
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.
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")
345 if not self
.__extra
__:
346 return super().__subclasscheck
__(subclass
)
347 res
= self
.__extra
__.__subclasshook
__(subclass
)
348 if res
is not NotImplemented:
350 if self
.__extra
__ in subclass
.__mro
__:
352 for scls
in self
.__extra
__.__subclasses
__():
353 if isinstance(scls
, GenericMeta
):
355 if issubclass(subclass
, scls
):
360 Awaitable
= typing
.Awaitable
361 Coroutine
= typing
.Coroutine
362 AsyncIterable
= typing
.AsyncIterable
363 AsyncIterator
= typing
.AsyncIterator
366 if hasattr(typing
, 'Deque'):
370 class Deque(collections
.deque
, typing
.MutableSequence
[T
],
371 metaclass
=_ExtensionsGenericMeta
,
372 extra
=collections
.deque
):
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
)
380 ContextManager
= typing
.ContextManager
382 if hasattr(typing
, 'AsyncContextManager'):
383 AsyncContextManager
= typing
.AsyncContextManager
386 from _collections_abc
import _check_methods
as _check_methods_in_mro
# noqa
388 class AsyncContextManager(typing
.Generic
[T_co
]):
391 async def __aenter__(self
):
395 async def __aexit__(self
, exc_type
, exc_value
, traceback
):
399 def __subclasshook__(cls
, C
):
400 if cls
is AsyncContextManager
:
401 return _check_methods_in_mro(C
, "__aenter__", "__aexit__")
402 return NotImplemented
404 DefaultDict
= typing
.DefaultDict
407 if hasattr(typing
, 'OrderedDict'):
408 OrderedDict
= typing
.OrderedDict
410 elif (3, 7, 0) <= sys
.version_info
[:3] < (3, 7, 2):
411 OrderedDict
= typing
._alias
(collections
.OrderedDict
, (KT
, VT
))
414 class OrderedDict(collections
.OrderedDict
, typing
.MutableMapping
[KT
, VT
],
415 metaclass
=_ExtensionsGenericMeta
,
416 extra
=collections
.OrderedDict
):
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
)
426 if hasattr(typing
, 'Counter'):
427 Counter
= typing
.Counter
430 class Counter(collections
.Counter
,
432 metaclass
=_ExtensionsGenericMeta
, extra
=collections
.Counter
):
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
)
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
):
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
)
457 if hasattr(typing
, 'AsyncGenerator'):
458 AsyncGenerator
= typing
.AsyncGenerator
461 class AsyncGenerator(AsyncIterator
[T_co
], typing
.Generic
[T_co
, T_contra
],
462 metaclass
=_ExtensionsGenericMeta
,
463 extra
=collections
.abc
.AsyncGenerator
):
466 NewType
= typing
.NewType
468 TYPE_CHECKING
= typing
.TYPE_CHECKING
472 """This function exists for compatibility with old typing versions."""
473 assert isinstance(cls
, GenericMeta
)
474 if hasattr(cls
, '_gorg'):
476 while cls
.__origin
__ is not None:
481 _PROTO_WHITELIST
= ['Callable', 'Awaitable',
482 'Iterable', 'Iterator', 'AsyncIterable', 'AsyncIterator',
483 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible',
484 'ContextManager', 'AsyncContextManager']
487 def _get_protocol_attrs(cls
):
489 for base
in cls
.__mro
__[:-1]: # without object
490 if base
.__name
__ in ('Protocol', 'Generic'):
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')):
506 def _is_callable_members_only(cls
):
507 return all(callable(getattr(cls
, attr
, None)) for attr
in _get_protocol_attrs(cls
))
511 if hasattr(typing
, 'Protocol'):
512 Protocol
= typing
.Protocol
515 from typing
import _collect_type_vars
# noqa
517 def _no_init(self
, *args
, **kwargs
):
518 if type(self
)._is
_protocol
:
519 raise TypeError('Protocols cannot be instantiated')
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
)):
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
)):
537 return super().__instancecheck
__(instance
)
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::
545 class Proto(Protocol):
546 def meth(self) -> int:
549 Such classes are primarily used with static type checkers that recognize
550 structural subtyping (static duck-typing), for example::
553 def meth(self) -> int:
556 def func(x: Proto) -> int:
559 func(C()) # Passes static type check
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.
565 Protocol classes can be generic, they are defined as::
567 class GenProto(Protocol[T]):
574 def __new__(cls
, *args
, **kwds
):
576 raise TypeError("Type Protocol cannot be instantiated; "
577 "it can only be used as a base class")
578 return super().__new
__(cls
)
581 def __class_getitem__(cls
, params
):
582 if not isinstance(params
, tuple):
584 if not params
and cls
is not typing
.Tuple
:
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
590 # Generic can only be subscripted with unique type variables.
591 if not all(isinstance(p
, typing
.TypeVar
) for p
in params
):
593 while isinstance(params
[i
], typing
.TypeVar
):
596 "Parameters to Protocol[...] must all be type variables."
597 f
" Parameter {i + 1} is {params[i]}")
598 if len(set(params
)) != len(params
):
600 "Parameters to Protocol[...] must all be unique")
602 # Subscripting a regular Generic subclass.
603 _check_generic(cls
, params
)
604 return typing
._GenericAlias
(cls
, params
)
606 def __init_subclass__(cls
, *args
, **kwargs
):
608 if '__orig_bases__' in cls
.__dict
__:
609 error
= typing
.Generic
in cls
.__orig
_bases
__
611 error
= typing
.Generic
in cls
.__bases
__
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[...].
622 for base
in cls
.__orig
_bases
__:
623 if (isinstance(base
, typing
._GenericAlias
) and
624 base
.__origin
__ in (typing
.Generic
, Protocol
)):
626 the_base
= base
.__origin
__.__name
__
627 if gvars
is not None:
629 "Cannot inherit from Generic[...]"
630 " and/or Protocol[...] multiple types.")
631 gvars
= base
.__parameters
__
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}]")
643 cls
.__parameters
__ = tuple(tvars
)
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
__)
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
672 annotations
= getattr(base
, '__annotations__', {})
673 if (isinstance(annotations
, typing
.Mapping
) and
674 attr
in annotations
and
675 isinstance(other
, _ProtocolMeta
) and
679 return NotImplemented
681 if '__subclasshook__' not in cls
.__dict
__:
682 cls
.__subclasshook
__ = _proto_hook
684 # We have nothing more to do for non-protocols.
685 if not cls
._is
_protocol
:
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
699 from typing
import _next_in_mro
, _type_check
# noqa
701 def _no_init(self
, *args
, **kwargs
):
702 if type(self
)._is
_protocol
:
703 raise TypeError('Protocols cannot be instantiated')
705 class _ProtocolMeta(GenericMeta
):
706 """Internal metaclass for Protocol.
708 This exists so Protocol classes can be generic without deriving
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
720 tvars
= _type_vars(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:
729 "Cannot inherit from Generic[...] or"
730 " Protocol[...] multiple times.")
731 gvars
= base
.__parameters
__
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}]")
746 initial_bases
= bases
747 if (extra
is not None and type(extra
) is abc
.ABCMeta
and
749 bases
= (extra
,) + bases
750 bases
= tuple(_gorg(b
) if isinstance(b
, GenericMeta
) else b
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
,
757 super(GenericMeta
, self
).__setattr
__('_gorg',
758 self
if not origin
else
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
__())
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
__)
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)}')
793 cls
.__init
__ = _no_init
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
807 annotations
= getattr(base
, '__annotations__', {})
808 if (isinstance(annotations
, typing
.Mapping
) and
809 attr
in annotations
and
810 isinstance(other
, _ProtocolMeta
) and
814 return NotImplemented
816 if '__subclasshook__' not in cls
.__dict
__:
817 cls
.__subclasshook
__ = _proto_hook
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
)):
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
)):
832 return super(GenericMeta
, self
).__instancecheck
__(instance
)
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")
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',
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',
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
)
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):
864 if not params
and _gorg(self
) is not typing
.Tuple
:
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
):
872 f
"Parameters to {repr(self)}[...] must all be type variables")
873 if len(set(params
)) != len(params
):
875 f
"Parameters to {repr(self)}[...] must all be unique")
878 elif self
in (typing
.Tuple
, typing
.Callable
):
879 tvars
= _type_vars(params
)
881 elif self
.__origin
__ in (typing
.Generic
, Protocol
):
882 raise TypeError(f
"Cannot subscript already-subscripted {repr(self)}")
884 _check_generic(self
, params
)
885 tvars
= _type_vars(params
)
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
__),
895 extra
=self
.__extra
__,
896 orig_bases
=self
.__orig
_bases
__)
898 class Protocol(metaclass
=_ProtocolMeta
):
899 """Base class for protocol classes. Protocol classes are defined as::
901 class Proto(Protocol):
902 def meth(self) -> int:
905 Such classes are primarily used with static type checkers that recognize
906 structural subtyping (static duck-typing), for example::
909 def meth(self) -> int:
912 def func(x: Proto) -> int:
915 func(C()) # Passes static type check
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.
921 Protocol classes can be generic, they are defined as::
923 class GenProto(Protocol[T]):
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
)
938 if hasattr(typing
, 'runtime_checkable'):
939 runtime_checkable
= typing
.runtime_checkable
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.
947 This allows a simple-minded structural check very similar to the
948 one-offs in collections.abc such as Hashable.
950 if not isinstance(cls
, _ProtocolMeta
) or not cls
._is
_protocol
:
951 raise TypeError('@runtime_checkable can be only applied to protocol classes,'
953 cls
._is
_runtime
_protocol
= True
957 # Exists for backwards compatibility.
958 runtime
= runtime_checkable
962 if hasattr(typing
, 'SupportsIndex'):
963 SupportsIndex
= typing
.SupportsIndex
967 class SupportsIndex(Protocol
):
971 def __index__(self
) -> int:
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
982 def _check_fails(cls
, other
):
984 if sys
._getframe
(1).f_globals
['__name__'] not in ['abc',
987 # Typed dicts are only for static structural subtyping.
988 raise TypeError('TypedDict does not support instance and class checks')
989 except (AttributeError, ValueError):
993 def _dict_new(*args
, **kwargs
):
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
)
999 _dict_new
.__text
_signature
__ = '($cls, _typename, _fields=None, /, **kwargs)'
1001 def _typeddict_new(*args
, total
=True, **kwargs
):
1003 raise TypeError('TypedDict.__new__(): not enough arguments')
1004 _
, args
= args
[0], args
[1:] # allow the "cls" keyword be passed
1006 typename
, args
= args
[0], args
[1:] # allow the "_typename" keyword be passed
1007 elif '_typename' in kwargs
:
1008 typename
= kwargs
.pop('_typename')
1010 warnings
.warn("Passing '_typename' as keyword argument is deprecated",
1011 DeprecationWarning, stacklevel
=2)
1013 raise TypeError("TypedDict.__new__() missing 1 required positional "
1014 "argument: '_typename'")
1017 fields
, = args
# allow the "_fields" keyword be passed
1019 raise TypeError('TypedDict.__new__() takes from 2 to 3 '
1020 f
'positional arguments but {len(args) + 2} '
1022 elif '_fields' in kwargs
and len(kwargs
) == 1:
1023 fields
= kwargs
.pop('_fields')
1025 warnings
.warn("Passing '_fields' as keyword argument is deprecated",
1026 DeprecationWarning, stacklevel
=2)
1033 raise TypeError("TypedDict takes either a dict or keyword arguments,"
1036 ns
= {'__annotations__': dict(fields)}
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):
1043 return _TypedDictMeta(typename
, (), ns
, total
=total
)
1045 _typeddict_new
.__text
_signature
__ = ('($cls, _typename, _fields=None,'
1046 ' /, *, total=True, **kwargs)')
1048 class _TypedDictMeta(type):
1049 def __init__(cls
, name
, bases
, ns
, total
=True):
1050 super().__init
__(name
, bases
, ns
)
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
1059 ns
['__new__'] = _typeddict_new
if name
== 'TypedDict' else _dict_new
1060 tp_dict
= super().__new
__(cls
, name
, (dict,), ns
)
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"
1067 n
: typing
._type
_check
(tp
, msg
) for n
, tp
in own_annotations
.items()
1069 required_keys
= set()
1070 optional_keys
= set()
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__', ()))
1077 annotations
.update(own_annotations
)
1079 required_keys
.update(own_annotation_keys
)
1081 optional_keys
.update(own_annotation_keys
)
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
1090 __instancecheck__
= __subclasscheck__
= _check_fails
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.
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.
1103 class Point2D(TypedDict):
1108 a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
1109 b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
1111 assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
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::
1117 Point2D = TypedDict('Point2D', x=int, y=int, label=str)
1118 Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
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+
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()
1131 _AnnotatedAlias
= typing
._AnnotatedAlias
1134 class _AnnotatedAlias(typing
._GenericAlias
, _root
=True):
1135 """Runtime representation of an annotated type.
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.
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
1149 def copy_with(self
, params
):
1150 assert len(params
) == 1
1151 new_type
= params
[0]
1152 return _AnnotatedAlias(new_type
, self
.__metadata
__)
1155 return (f
"typing_extensions.Annotated[{typing._type_repr(self.__origin__)}, "
1156 f
"{', '.join(repr(a) for a in self.__metadata__)}]")
1158 def __reduce__(self
):
1159 return operator
.getitem
, (
1160 Annotated
, (self
.__origin
__,) + self
.__metadata
__
1163 def __eq__(self
, other
):
1164 if not isinstance(other
, _AnnotatedAlias
):
1165 return NotImplemented
1166 if self
.__origin
__ != other
.__origin
__:
1168 return self
.__metadata
__ == other
.__metadata
__
1171 return hash((self
.__origin
__, self
.__metadata
__))
1174 """Add context specific metadata to a type.
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
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.
1187 - It's an error to call `Annotated` with less than two arguments.
1188 - Nested Annotated are flattened::
1190 Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
1192 - Instantiating an annotated type is equivalent to instantiating the
1195 Annotated[C, Ann1](5) == C(5)
1197 - Annotated can be used as a generic type alias::
1199 Optimized = Annotated[T, runtime.Optimize()]
1200 Optimized[int] == Annotated[int, runtime.Optimize()]
1202 OptimizedList = Annotated[List[T], runtime.Optimize()]
1203 OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
1208 def __new__(cls
, *args
, **kwargs
):
1209 raise TypeError("Type Annotated cannot be instantiated.")
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 "
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
)
1222 def __init_subclass__(cls
, *args
, **kwargs
):
1224 f
"Cannot subclass {cls.__module__}.Annotated"
1227 def _strip_annotations(t
):
1228 """Strips the annotations from a given type.
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
__:
1236 res
= t
.copy_with(stripped_args
)
1237 res
._special
= t
._special
1241 def get_type_hints(obj
, globalns
=None, localns
=None, include_extras
=False):
1242 """Return type hints for an object.
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').
1249 The argument may be a module, class, method, or function. The annotations
1250 are returned as a dictionary. For classes, annotations include also
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
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.
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.
1266 - If one dict argument is passed, it is used for both globals and
1269 - If two dict arguments are passed, they specify globals and
1270 locals, respectively.
1272 hint
= typing
.get_type_hints(obj
, globalns
=globalns
, localns
=localns
)
1275 return {k: _strip_annotations(t) for k, t in hint.items()}
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('__')
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.
1287 class AnnotatedMeta(typing
.GenericMeta
):
1288 """Metaclass for Annotated"""
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
)
1296 def __metadata__(self
):
1297 return self
._subs
_tree
()[2]
1299 def _tree_repr(self
, tree
):
1300 cls
, origin
, metadata
= tree
1301 if not isinstance(origin
, tuple):
1302 tp_repr
= typing
._type
_repr
(origin
)
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}]'
1308 def _subs_tree(self
, tvars
=None, args
=None): # noqa
1309 if self
is 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
:
1315 sub_annot
= res
[1][2]
1316 return (Annotated
, sub_tp
, sub_annot
+ res
[2])
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
:
1327 if isinstance(tree
, tuple):
1333 def __getitem__(self
, params
):
1334 if not isinstance(params
, tuple):
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 "
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
__(
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
),
1356 def __call__(self
, *args
, **kwargs
):
1357 cons
= self
._get
_cons
()
1358 result
= cons(*args
, **kwargs
)
1360 result
.__orig
_class
__ = self
1361 except AttributeError:
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
)
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
)
1377 setattr(self
._get
_cons
(), attr
, value
)
1379 def __instancecheck__(self
, obj
):
1380 raise TypeError("Annotated cannot be used with isinstance().")
1382 def __subclasscheck__(self
, cls
):
1383 raise TypeError("Annotated cannot be used with issubclass().")
1385 class Annotated(metaclass
=AnnotatedMeta
):
1386 """Add context specific metadata to a type.
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
1393 The first argument to Annotated must be a valid type, the remaining
1394 arguments are kept as a tuple in the __metadata__ field.
1398 - It's an error to call `Annotated` with less than two arguments.
1399 - Nested Annotated are flattened::
1401 Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
1403 - Instantiating an annotated type is equivalent to instantiating the
1406 Annotated[C, Ann1](5) == C(5)
1408 - Annotated can be used as a generic type alias::
1410 Optimized = Annotated[T, runtime.Optimize()]
1411 Optimized[int] == Annotated[int, runtime.Optimize()]
1413 OptimizedList = Annotated[List[T], runtime.Optimize()]
1414 OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
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
1427 from typing
import _BaseGenericAlias
1429 _BaseGenericAlias
= typing
._GenericAlias
1432 from typing
import GenericAlias
1434 GenericAlias
= typing
._GenericAlias
1437 """Get the unsubscripted version of a type.
1439 This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
1440 and Annotated. Return None for unsupported types. Examples::
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
1451 if isinstance(tp
, _AnnotatedAlias
):
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
1461 """Get type arguments with all substitutions performed.
1463 For unions, basic simplifications used by Union constructor are performed.
1465 get_args(Dict[str, int]) == (str, 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)
1471 if isinstance(tp
, _AnnotatedAlias
):
1472 return (tp
.__origin
__,) + tp
.__metadata
__
1473 if isinstance(tp
, (typing
._GenericAlias
, GenericAlias
)):
1474 if getattr(tp
, "_special", False):
1477 if get_origin(tp
) is collections
.abc
.Callable
and res
[0] is not Ellipsis:
1478 res
= (list(res
[:-1]), res
[-1])
1484 if hasattr(typing
, 'TypeAlias'):
1485 TypeAlias
= typing
.TypeAlias
1487 elif sys
.version_info
[:2] >= (3, 9):
1488 class _TypeAliasForm(typing
._SpecialForm
, _root
=True):
1490 return 'typing_extensions.' + self
._name
1493 def TypeAlias(self
, parameters
):
1494 """Special marker indicating that an assignment should
1495 be recognized as a proper type alias definition by type
1500 Predicate: TypeAlias = Callable[..., bool]
1502 It's invalid when used anywhere except as in the example above.
1504 raise TypeError(f
"{self} is not subscriptable")
1506 elif sys
.version_info
[:2] >= (3, 7):
1507 class _TypeAliasForm(typing
._SpecialForm
, _root
=True):
1509 return 'typing_extensions.' + self
._name
1511 TypeAlias
= _TypeAliasForm('TypeAlias',
1512 doc
="""Special marker indicating that an assignment should
1513 be recognized as a proper type alias definition by type
1518 Predicate: TypeAlias = Callable[..., bool]
1520 It's invalid when used anywhere except as in the example
1524 class _TypeAliasMeta(typing
.TypingMeta
):
1525 """Metaclass for TypeAlias"""
1528 return 'typing_extensions.TypeAlias'
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
1537 Predicate: TypeAlias = Callable[..., bool]
1539 It's invalid when used anywhere except as in the example above.
1543 def __instancecheck__(self
, obj
):
1544 raise TypeError("TypeAlias cannot be used with isinstance().")
1546 def __subclasscheck__(self
, cls
):
1547 raise TypeError("TypeAlias cannot be used with issubclass().")
1550 return 'typing_extensions.TypeAlias'
1552 TypeAlias
= _TypeAliasBase(_root
=True)
1555 # Python 3.10+ has PEP 612
1556 if hasattr(typing
, 'ParamSpecArgs'):
1557 ParamSpecArgs
= typing
.ParamSpecArgs
1558 ParamSpecKwargs
= typing
.ParamSpecKwargs
1562 """Mixin to indicate that object should not be copied."""
1568 def __deepcopy__(self
, memo
):
1571 class ParamSpecArgs(_Immutable
):
1572 """The args for a ParamSpec object.
1574 Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.
1576 ParamSpecArgs objects have a reference back to their ParamSpec:
1578 P.args.__origin__ is P
1580 This type is meant for runtime introspection and has no special meaning to
1581 static type checkers.
1583 def __init__(self
, origin
):
1584 self
.__origin
__ = origin
1587 return f
"{self.__origin__.__name__}.args"
1589 class ParamSpecKwargs(_Immutable
):
1590 """The kwargs for a ParamSpec object.
1592 Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs.
1594 ParamSpecKwargs objects have a reference back to their ParamSpec:
1596 P.kwargs.__origin__ is P
1598 This type is meant for runtime introspection and has no special meaning to
1599 static type checkers.
1601 def __init__(self
, origin
):
1602 self
.__origin
__ = origin
1605 return f
"{self.__origin__.__name__}.kwargs"
1608 if hasattr(typing
, 'ParamSpec'):
1609 ParamSpec
= typing
.ParamSpec
1613 # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
1614 class ParamSpec(list):
1615 """Parameter specification variable.
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::
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)
1641 def add_two(x: float, y: float) -> float:
1642 '''Add two numbers together.'''
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.
1650 Parameter specification variables can be introspected. e.g.:
1654 P.__covariant__ == False
1655 P.__contravariant__ == False
1657 Note that only parameter specification variables defined in global scope can
1661 # Trick Generic __parameters__.
1662 __class__
= typing
.TypeVar
1666 return ParamSpecArgs(self
)
1670 return ParamSpecKwargs(self
)
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
)
1678 self
.__bound
__ = typing
._type
_check
(bound
, 'Bound must be a type.')
1680 self
.__bound
__ = None
1684 def_mod
= sys
._getframe
(1).f_globals
.get('__name__', '__main__')
1685 except (AttributeError, ValueError):
1687 if def_mod
!= 'typing_extensions':
1688 self
.__module
__ = def_mod
1691 if self
.__covariant
__:
1693 elif self
.__contravariant
__:
1697 return prefix
+ self
.__name
__
1700 return object.__hash
__(self
)
1702 def __eq__(self
, other
):
1703 return self
is other
1705 def __reduce__(self
):
1706 return self
.__name
__
1708 # Hack to get typing._type_check to pass.
1709 def __call__(self
, *args
, **kwargs
):
1713 # Only needed in 3.6.
1714 def _get_type_vars(self
, tvars
):
1715 if self
not in tvars
:
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):
1724 # Trick Generic into looking into this for __parameters__.
1726 __class__
= typing
._GenericAlias
1728 __class__
= typing
._TypingBase
1732 # Attribute in 3.6 and earlier.
1733 _gorg
= typing
.Generic
1735 def __init__(self
, origin
, args
):
1736 super().__init
__(args
)
1737 self
.__origin
__ = origin
1738 self
.__args
__ = args
1741 _type_repr
= typing
._type
_repr
1742 return (f
'{_type_repr(self.__origin__)}'
1743 f
'[{", ".join(_type_repr(arg) for arg in self.__args__)}]')
1746 return hash((self
.__origin
__, self
.__args
__))
1748 # Hack to get typing._type_check to pass in Generic.
1749 def __call__(self
, *args
, **kwargs
):
1753 def __parameters__(self
):
1755 tp
for tp
in self
.__args
__ if isinstance(tp
, (typing
.TypeVar
, ParamSpec
))
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
)
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
)
1781 if hasattr(typing
, 'Concatenate'):
1782 Concatenate
= typing
.Concatenate
1783 _ConcatenateGenericAlias
= typing
._ConcatenateGenericAlias
# noqa
1785 elif sys
.version_info
[:2] >= (3, 9):
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
1794 Callable[Concatenate[int, P], int]
1796 See PEP 612 for detailed information.
1798 return _concatenate_getitem(self
, parameters
)
1800 elif sys
.version_info
[:2] >= (3, 7):
1801 class _ConcatenateForm(typing
._SpecialForm
, _root
=True):
1803 return 'typing_extensions.' + self
._name
1805 def __getitem__(self
, parameters
):
1806 return _concatenate_getitem(self
, parameters
)
1808 Concatenate
= _ConcatenateForm(
1810 doc
="""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
1811 higher order function which adds, removes or transforms parameters of a
1816 Callable[Concatenate[int, P], int]
1818 See PEP 612 for detailed information.
1822 class _ConcatenateAliasMeta(typing
.TypingMeta
):
1823 """Metaclass for Concatenate."""
1826 return 'typing_extensions.Concatenate'
1828 class _ConcatenateAliasBase(typing
._FinalTypingBase
,
1829 metaclass
=_ConcatenateAliasMeta
,
1831 """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
1832 higher order function which adds, removes or transforms parameters of a
1837 Callable[Concatenate[int, P], int]
1839 See PEP 612 for detailed information.
1843 def __instancecheck__(self
, obj
):
1844 raise TypeError("Concatenate cannot be used with isinstance().")
1846 def __subclasscheck__(self
, cls
):
1847 raise TypeError("Concatenate cannot be used with issubclass().")
1850 return 'typing_extensions.Concatenate'
1852 def __getitem__(self
, parameters
):
1853 return _concatenate_getitem(self
, parameters
)
1855 Concatenate
= _ConcatenateAliasBase(_root
=True)
1858 if hasattr(typing
, 'TypeGuard'):
1859 TypeGuard
= typing
.TypeGuard
1861 elif sys
.version_info
[:2] >= (3, 9):
1862 class _TypeGuardForm(typing
._SpecialForm
, _root
=True):
1864 return 'typing_extensions.' + self
._name
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.
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".
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.
1882 Using ``-> TypeGuard`` tells the static type checker that for a given
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``.
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``
1897 # Else, type of ``val`` is narrowed to ``float``.
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.
1907 ``TypeGuard`` also works with type variables. For more information, see
1908 PEP 647 (User-Defined Type Guards).
1910 item
= typing
._type
_check
(parameters
, f
'{self} accepts only single type.')
1911 return typing
._GenericAlias
(self
, (item
,))
1913 elif sys
.version_info
[:2] >= (3, 7):
1914 class _TypeGuardForm(typing
._SpecialForm
, _root
=True):
1917 return 'typing_extensions.' + self
._name
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
,))
1924 TypeGuard
= _TypeGuardForm(
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.
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".
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.
1940 Using ``-> TypeGuard`` tells the static type checker that for a given
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``.
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``
1955 # Else, type of ``val`` is narrowed to ``float``.
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.
1965 ``TypeGuard`` also works with type variables. For more information, see
1966 PEP 647 (User-Defined Type Guards).
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.
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".
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.
1985 Using ``-> TypeGuard`` tells the static type checker that for a given
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``.
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``
2000 # Else, type of ``val`` is narrowed to ``float``.
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.
2010 ``TypeGuard`` also works with type variables. For more information, see
2011 PEP 647 (User-Defined Type Guards).
2014 __slots__
= ('__type__',)
2016 def __init__(self
, tp
=None, **kwds
):
2019 def __getitem__(self
, item
):
2021 if self
.__type
__ is None:
2022 return cls(typing
._type
_check
(item
,
2023 f
'{cls.__name__[1:]} accepts only a single type.'),
2025 raise TypeError(f
'{cls.__name__[1:]} cannot be further subscripted')
2027 def _eval_type(self
, globalns
, localns
):
2028 new_tp
= typing
._eval
_type
(self
.__type
__, globalns
, localns
)
2029 if new_tp
== self
.__type
__:
2031 return type(self
)(new_tp
, _root
=True)
2034 r
= super().__repr
__()
2035 if self
.__type
__ is not None:
2036 r
+= f
'[{typing._type_repr(self.__type__)}]'
2040 return hash((type(self
).__name
__, self
.__type
__))
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
2049 TypeGuard
= _TypeGuard(_root
=True)
2051 if hasattr(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')
2058 def __init__(self
, getitem
):
2059 self
._getitem
= getitem
2060 self
._name
= getitem
.__name
__
2061 self
.__doc
__ = getitem
.__doc
__
2063 def __getattr__(self
, item
):
2064 if item
in {'__name__', '__qualname__'}
:
2067 raise AttributeError(item
)
2069 def __mro_entries__(self
, bases
):
2070 raise TypeError(f
"Cannot subclass {self!r}")
2073 return f
'typing_extensions.{self._name}'
2075 def __reduce__(self
):
2078 def __call__(self
, *args
, **kwds
):
2079 raise TypeError(f
"Cannot instantiate {self!r}")
2081 def __or__(self
, other
):
2082 return typing
.Union
[self
, other
]
2084 def __ror__(self
, other
):
2085 return typing
.Union
[other
, self
]
2087 def __instancecheck__(self
, obj
):
2088 raise TypeError(f
"{self} cannot be used with isinstance()")
2090 def __subclasscheck__(self
, cls
):
2091 raise TypeError(f
"{self} cannot be used with issubclass()")
2094 def __getitem__(self
, parameters
):
2095 return self
._getitem
(self
, parameters
)
2098 def Self(self
, params
):
2099 """Used to spell the type of "self" in classes.
2103 from typing import Self
2106 def parse(self, data: bytes) -> Self:
2112 raise TypeError(f
"{self} is not subscriptable")
2114 class _Self(typing
._FinalTypingBase
, _root
=True):
2115 """Used to spell the type of "self" in classes.
2119 from typing import Self
2122 def parse(self, data: bytes) -> Self:
2130 def __instancecheck__(self
, obj
):
2131 raise TypeError(f
"{self} cannot be used with isinstance().")
2133 def __subclasscheck__(self
, cls
):
2134 raise TypeError(f
"{self} cannot be used with issubclass().")
2136 Self
= _Self(_root
=True)
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):
2145 return 'typing_extensions.' + self
._name
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:
2152 class Movie(TypedDict, total=False):
2153 title: Required[str]
2157 title='The Matrix', # typechecker error if key is omitted
2161 There is no runtime checking that a required key is actually provided
2162 when instantiating a related TypedDict.
2164 item
= typing
._type
_check
(parameters
, f
'{self._name} accepts only single type')
2165 return typing
._GenericAlias
(self
, (item
,))
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:
2172 class Movie(TypedDict):
2174 year: NotRequired[int]
2177 title='The Matrix', # typechecker error if key is omitted
2181 item
= typing
._type
_check
(parameters
, f
'{self._name} accepts only single type')
2182 return typing
._GenericAlias
(self
, (item
,))
2184 elif sys
.version_info
[:2] >= (3, 7):
2185 class _RequiredForm(typing
._SpecialForm
, _root
=True):
2187 return 'typing_extensions.' + self
._name
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
,))
2194 Required
= _RequiredForm(
2196 doc
="""A special typing construct to mark a key of a total=False TypedDict
2197 as required. For example:
2199 class Movie(TypedDict, total=False):
2200 title: Required[str]
2204 title='The Matrix', # typechecker error if key is omitted
2208 There is no runtime checking that a required key is actually provided
2209 when instantiating a related TypedDict.
2211 NotRequired
= _RequiredForm(
2213 doc
="""A special typing construct to mark a key of a TypedDict as
2214 potentially missing. For example:
2216 class Movie(TypedDict):
2218 year: NotRequired[int]
2221 title='The Matrix', # typechecker error if key is omitted
2226 # NOTE: Modeled after _Final's implementation when _FinalTypingBase available
2227 class _MaybeRequired(typing
._FinalTypingBase
, _root
=True):
2228 __slots__
= ('__type__',)
2230 def __init__(self
, tp
=None, **kwds
):
2233 def __getitem__(self
, item
):
2235 if self
.__type
__ is None:
2236 return cls(typing
._type
_check
(item
,
2237 '{} accepts only single type.'.format(cls
.__name
__[1:])),
2239 raise TypeError('{} cannot be further subscripted'
2240 .format(cls
.__name
__[1:]))
2242 def _eval_type(self
, globalns
, localns
):
2243 new_tp
= typing
._eval
_type
(self
.__type
__, globalns
, localns
)
2244 if new_tp
== self
.__type
__:
2246 return type(self
)(new_tp
, _root
=True)
2249 r
= super().__repr
__()
2250 if self
.__type
__ is not None:
2251 r
+= '[{}]'.format(typing
._type
_repr
(self
.__type
__))
2255 return hash((type(self
).__name
__, self
.__type
__))
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
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:
2268 class Movie(TypedDict, total=False):
2269 title: Required[str]
2273 title='The Matrix', # typechecker error if key is omitted
2277 There is no runtime checking that a required key is actually provided
2278 when instantiating a related TypedDict.
2281 class _NotRequired(_MaybeRequired
, _root
=True):
2282 """A special typing construct to mark a key of a TypedDict as
2283 potentially missing. For example:
2285 class Movie(TypedDict):
2287 year: NotRequired[int]
2290 title='The Matrix', # typechecker error if key is omitted
2295 Required
= _Required(_root
=True)
2296 NotRequired
= _NotRequired(_root
=True)