codekingpro/portable-devtools
114k
1import abc2import collections3import collections.abc4import functools5import operator6import sys7import types as _types8import typing9 10 11__all__ = [12 # Super-special typing primitives.13 'Any',14 'ClassVar',15 'Concatenate',16 'Final',17 'LiteralString',18 'ParamSpec',19 'ParamSpecArgs',20 'ParamSpecKwargs',21 'Self',22 'Type',23 'TypeVar',24 'TypeVarTuple',25 'Unpack',26 27 # ABCs (from collections.abc).28 'Awaitable',29 'AsyncIterator',30 'AsyncIterable',31 'Coroutine',32 'AsyncGenerator',33 'AsyncContextManager',34 'ChainMap',35 36 # Concrete collection types.37 'ContextManager',38 'Counter',39 'Deque',40 'DefaultDict',41 'NamedTuple',42 'OrderedDict',43 'TypedDict',44 45 # Structural checks, a.k.a. protocols.46 'SupportsIndex',47 48 # One-off things.49 'Annotated',50 'assert_never',51 'assert_type',52 'clear_overloads',53 'dataclass_transform',54 'get_overloads',55 'final',56 'get_args',57 'get_origin',58 'get_type_hints',59 'IntVar',60 'is_typeddict',61 'Literal',62 'NewType',63 'overload',64 'override',65 'Protocol',66 'reveal_type',67 'runtime',68 'runtime_checkable',69 'Text',70 'TypeAlias',71 'TypeGuard',72 'TYPE_CHECKING',73 'Never',74 'NoReturn',75 'Required',76 'NotRequired',77]78 79# for backward compatibility80PEP_560 = True81GenericMeta = type82 83# The functions below are modified copies of typing internal helpers.84# They are needed by _ProtocolMeta and they provide support for PEP 646.85 86_marker = object()87 88 89def _check_generic(cls, parameters, elen=_marker):90 """Check correct count for parameters of a generic cls (internal helper).91 This gives a nice error message in case of count mismatch.92 """93 if not elen:94 raise TypeError(f"{cls} is not a generic class")95 if elen is _marker:96 if not hasattr(cls, "__parameters__") or not cls.__parameters__:97 raise TypeError(f"{cls} is not a generic class")98 elen = len(cls.__parameters__)99 alen = len(parameters)100 if alen != elen:101 if hasattr(cls, "__parameters__"):102 parameters = [p for p in cls.__parameters__ if not _is_unpack(p)]103 num_tv_tuples = sum(isinstance(p, TypeVarTuple) for p in parameters)104 if (num_tv_tuples > 0) and (alen >= elen - num_tv_tuples):105 return106 raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};"107 f" actual {alen}, expected {elen}")108 109 110if sys.version_info >= (3, 10):111 def _should_collect_from_parameters(t):112 return isinstance(113 t, (typing._GenericAlias, _types.GenericAlias, _types.UnionType)114 )115elif sys.version_info >= (3, 9):116 def _should_collect_from_parameters(t):117 return isinstance(t, (typing._GenericAlias, _types.GenericAlias))118else:119 def _should_collect_from_parameters(t):120 return isinstance(t, typing._GenericAlias) and not t._special121 122 123def _collect_type_vars(types, typevar_types=None):124 """Collect all type variable contained in types in order of125 first appearance (lexicographic order). For example::126 127 _collect_type_vars((T, List[S, T])) == (T, S)128 """129 if typevar_types is None:130 typevar_types = typing.TypeVar131 tvars = []132 for t in types:133 if (134 isinstance(t, typevar_types) and135 t not in tvars and136 not _is_unpack(t)137 ):138 tvars.append(t)139 if _should_collect_from_parameters(t):140 tvars.extend([t for t in t.__parameters__ if t not in tvars])141 return tuple(tvars)142 143 144NoReturn = typing.NoReturn145 146# Some unconstrained type variables. These are used by the container types.147# (These are not for export.)148T = typing.TypeVar('T') # Any type.149KT = typing.TypeVar('KT') # Key type.150VT = typing.TypeVar('VT') # Value type.151T_co = typing.TypeVar('T_co', covariant=True) # Any type covariant containers.152T_contra = typing.TypeVar('T_contra', contravariant=True) # Ditto contravariant.153 154 155if sys.version_info >= (3, 11):156 from typing import Any157else:158 159 class _AnyMeta(type):160 def __instancecheck__(self, obj):161 if self is Any:162 raise TypeError("typing_extensions.Any cannot be used with isinstance()")163 return super().__instancecheck__(obj)164 165 def __repr__(self):166 if self is Any:167 return "typing_extensions.Any"168 return super().__repr__()169 170 class Any(metaclass=_AnyMeta):171 """Special type indicating an unconstrained type.172 - Any is compatible with every type.173 - Any assumed to have all methods.174 - All values assumed to be instances of Any.175 Note that all the above statements are true from the point of view of176 static type checkers. At runtime, Any should not be used with instance177 checks.178 """179 def __new__(cls, *args, **kwargs):180 if cls is Any:181 raise TypeError("Any cannot be instantiated")182 return super().__new__(cls, *args, **kwargs)183 184 185ClassVar = typing.ClassVar186 187# On older versions of typing there is an internal class named "Final".188# 3.8+189if hasattr(typing, 'Final') and sys.version_info[:2] >= (3, 7):190 Final = typing.Final191# 3.7192else:193 class _FinalForm(typing._SpecialForm, _root=True):194 195 def __repr__(self):196 return 'typing_extensions.' + self._name197 198 def __getitem__(self, parameters):199 item = typing._type_check(parameters,200 f'{self._name} accepts only a single type.')201 return typing._GenericAlias(self, (item,))202 203 Final = _FinalForm('Final',204 doc="""A special typing construct to indicate that a name205 cannot be re-assigned or overridden in a subclass.206 For example:207 208 MAX_SIZE: Final = 9000209 MAX_SIZE += 1 # Error reported by type checker210 211 class Connection:212 TIMEOUT: Final[int] = 10213 class FastConnector(Connection):214 TIMEOUT = 1 # Error reported by type checker215 216 There is no runtime checking of these properties.""")217 218if sys.version_info >= (3, 11):219 final = typing.final220else:221 # @final exists in 3.8+, but we backport it for all versions222 # before 3.11 to keep support for the __final__ attribute.223 # See https://bugs.python.org/issue46342224 def final(f):225 """This decorator can be used to indicate to type checkers that226 the decorated method cannot be overridden, and decorated class227 cannot be subclassed. For example:228 229 class Base:230 @final231 def done(self) -> None:232 ...233 class Sub(Base):234 def done(self) -> None: # Error reported by type checker235 ...236 @final237 class Leaf:238 ...239 class Other(Leaf): # Error reported by type checker240 ...241 242 There is no runtime checking of these properties. The decorator243 sets the ``__final__`` attribute to ``True`` on the decorated object244 to allow runtime introspection.245 """246 try:247 f.__final__ = True248 except (AttributeError, TypeError):249 # Skip the attribute silently if it is not writable.250 # AttributeError happens if the object has __slots__ or a251 # read-only property, TypeError if it's a builtin class.252 pass253 return f254 255 256def IntVar(name):257 return typing.TypeVar(name)258 259 260# 3.8+:261if hasattr(typing, 'Literal'):262 Literal = typing.Literal263# 3.7:264else:265 class _LiteralForm(typing._SpecialForm, _root=True):266 267 def __repr__(self):268 return 'typing_extensions.' + self._name269 270 def __getitem__(self, parameters):271 return typing._GenericAlias(self, parameters)272 273 Literal = _LiteralForm('Literal',274 doc="""A type that can be used to indicate to type checkers275 that the corresponding value has a value literally equivalent276 to the provided parameter. For example:277 278 var: Literal[4] = 4279 280 The type checker understands that 'var' is literally equal to281 the value 4 and no other value.282 283 Literal[...] cannot be subclassed. There is no runtime284 checking verifying that the parameter is actually a value285 instead of a type.""")286 287 288_overload_dummy = typing._overload_dummy # noqa289 290 291if hasattr(typing, "get_overloads"): # 3.11+292 overload = typing.overload293 get_overloads = typing.get_overloads294 clear_overloads = typing.clear_overloads295else:296 # {module: {qualname: {firstlineno: func}}}297 _overload_registry = collections.defaultdict(298 functools.partial(collections.defaultdict, dict)299 )300 301 def overload(func):302 """Decorator for overloaded functions/methods.303 304 In a stub file, place two or more stub definitions for the same305 function in a row, each decorated with @overload. For example:306 307 @overload308 def utf8(value: None) -> None: ...309 @overload310 def utf8(value: bytes) -> bytes: ...311 @overload312 def utf8(value: str) -> bytes: ...313 314 In a non-stub file (i.e. a regular .py file), do the same but315 follow it with an implementation. The implementation should *not*316 be decorated with @overload. For example:317 318 @overload319 def utf8(value: None) -> None: ...320 @overload321 def utf8(value: bytes) -> bytes: ...322 @overload323 def utf8(value: str) -> bytes: ...324 def utf8(value):325 # implementation goes here326 327 The overloads for a function can be retrieved at runtime using the328 get_overloads() function.329 """330 # classmethod and staticmethod331 f = getattr(func, "__func__", func)332 try:333 _overload_registry[f.__module__][f.__qualname__][334 f.__code__.co_firstlineno335 ] = func336 except AttributeError:337 # Not a normal function; ignore.338 pass339 return _overload_dummy340 341 def get_overloads(func):342 """Return all defined overloads for *func* as a sequence."""343 # classmethod and staticmethod344 f = getattr(func, "__func__", func)345 if f.__module__ not in _overload_registry:346 return []347 mod_dict = _overload_registry[f.__module__]348 if f.__qualname__ not in mod_dict:349 return []350 return list(mod_dict[f.__qualname__].values())351 352 def clear_overloads():353 """Clear all overloads in the registry."""354 _overload_registry.clear()355 356 357# This is not a real generic class. Don't use outside annotations.358Type = typing.Type359 360# Various ABCs mimicking those in collections.abc.361# A few are simply re-exported for completeness.362 363 364Awaitable = typing.Awaitable365Coroutine = typing.Coroutine366AsyncIterable = typing.AsyncIterable367AsyncIterator = typing.AsyncIterator368Deque = typing.Deque369ContextManager = typing.ContextManager370AsyncContextManager = typing.AsyncContextManager371DefaultDict = typing.DefaultDict372 373# 3.7.2+374if hasattr(typing, 'OrderedDict'):375 OrderedDict = typing.OrderedDict376# 3.7.0-3.7.2377else:378 OrderedDict = typing._alias(collections.OrderedDict, (KT, VT))379 380Counter = typing.Counter381ChainMap = typing.ChainMap382AsyncGenerator = typing.AsyncGenerator383NewType = typing.NewType384Text = typing.Text385TYPE_CHECKING = typing.TYPE_CHECKING386 387 388_PROTO_WHITELIST = ['Callable', 'Awaitable',389 'Iterable', 'Iterator', 'AsyncIterable', 'AsyncIterator',390 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible',391 'ContextManager', 'AsyncContextManager']392 393 394def _get_protocol_attrs(cls):395 attrs = set()396 for base in cls.__mro__[:-1]: # without object397 if base.__name__ in ('Protocol', 'Generic'):398 continue399 annotations = getattr(base, '__annotations__', {})400 for attr in list(base.__dict__.keys()) + list(annotations.keys()):401 if (not attr.startswith('_abc_') and attr not in (402 '__abstractmethods__', '__annotations__', '__weakref__',403 '_is_protocol', '_is_runtime_protocol', '__dict__',404 '__args__', '__slots__',405 '__next_in_mro__', '__parameters__', '__origin__',406 '__orig_bases__', '__extra__', '__tree_hash__',407 '__doc__', '__subclasshook__', '__init__', '__new__',408 '__module__', '_MutableMapping__marker', '_gorg')):409 attrs.add(attr)410 return attrs411 412 413def _is_callable_members_only(cls):414 return all(callable(getattr(cls, attr, None)) for attr in _get_protocol_attrs(cls))415 416 417def _maybe_adjust_parameters(cls):418 """Helper function used in Protocol.__init_subclass__ and _TypedDictMeta.__new__.419 420 The contents of this function are very similar421 to logic found in typing.Generic.__init_subclass__422 on the CPython main branch.423 """424 tvars = []425 if '__orig_bases__' in cls.__dict__:426 tvars = typing._collect_type_vars(cls.__orig_bases__)427 # Look for Generic[T1, ..., Tn] or Protocol[T1, ..., Tn].428 # If found, tvars must be a subset of it.429 # If not found, tvars is it.430 # Also check for and reject plain Generic,431 # and reject multiple Generic[...] and/or Protocol[...].432 gvars = None433 for base in cls.__orig_bases__:434 if (isinstance(base, typing._GenericAlias) and435 base.__origin__ in (typing.Generic, Protocol)):436 # for error messages437 the_base = base.__origin__.__name__438 if gvars is not None:439 raise TypeError(440 "Cannot inherit from Generic[...]"441 " and/or Protocol[...] multiple types.")442 gvars = base.__parameters__443 if gvars is None:444 gvars = tvars445 else:446 tvarset = set(tvars)447 gvarset = set(gvars)448 if not tvarset <= gvarset:449 s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)450 s_args = ', '.join(str(g) for g in gvars)451 raise TypeError(f"Some type variables ({s_vars}) are"452 f" not listed in {the_base}[{s_args}]")453 tvars = gvars454 cls.__parameters__ = tuple(tvars)455 456 457# 3.8+458if hasattr(typing, 'Protocol'):459 Protocol = typing.Protocol460# 3.7461else:462 463 def _no_init(self, *args, **kwargs):464 if type(self)._is_protocol:465 raise TypeError('Protocols cannot be instantiated')466 467 class _ProtocolMeta(abc.ABCMeta): # noqa: B024468 # This metaclass is a bit unfortunate and exists only because of the lack469 # of __instancehook__.470 def __instancecheck__(cls, instance):471 # We need this method for situations where attributes are472 # assigned in __init__.473 if ((not getattr(cls, '_is_protocol', False) or474 _is_callable_members_only(cls)) and475 issubclass(instance.__class__, cls)):476 return True477 if cls._is_protocol:478 if all(hasattr(instance, attr) and479 (not callable(getattr(cls, attr, None)) or480 getattr(instance, attr) is not None)481 for attr in _get_protocol_attrs(cls)):482 return True483 return super().__instancecheck__(instance)484 485 class Protocol(metaclass=_ProtocolMeta):486 # There is quite a lot of overlapping code with typing.Generic.487 # Unfortunately it is hard to avoid this while these live in two different488 # modules. The duplicated code will be removed when Protocol is moved to typing.489 """Base class for protocol classes. Protocol classes are defined as::490 491 class Proto(Protocol):492 def meth(self) -> int:493 ...494 495 Such classes are primarily used with static type checkers that recognize496 structural subtyping (static duck-typing), for example::497 498 class C:499 def meth(self) -> int:500 return 0501 502 def func(x: Proto) -> int:503 return x.meth()504 505 func(C()) # Passes static type check506 507 See PEP 544 for details. Protocol classes decorated with508 @typing_extensions.runtime act as simple-minded runtime protocol that checks509 only the presence of given attributes, ignoring their type signatures.510 511 Protocol classes can be generic, they are defined as::512 513 class GenProto(Protocol[T]):514 def meth(self) -> T:515 ...516 """517 __slots__ = ()518 _is_protocol = True519 520 def __new__(cls, *args, **kwds):521 if cls is Protocol:522 raise TypeError("Type Protocol cannot be instantiated; "523 "it can only be used as a base class")524 return super().__new__(cls)525 526 @typing._tp_cache527 def __class_getitem__(cls, params):528 if not isinstance(params, tuple):529 params = (params,)530 if not params and cls is not typing.Tuple:531 raise TypeError(532 f"Parameter list to {cls.__qualname__}[...] cannot be empty")533 msg = "Parameters to generic types must be types."534 params = tuple(typing._type_check(p, msg) for p in params) # noqa535 if cls is Protocol:536 # Generic can only be subscripted with unique type variables.537 if not all(isinstance(p, typing.TypeVar) for p in params):538 i = 0539 while isinstance(params[i], typing.TypeVar):540 i += 1541 raise TypeError(542 "Parameters to Protocol[...] must all be type variables."543 f" Parameter {i + 1} is {params[i]}")544 if len(set(params)) != len(params):545 raise TypeError(546 "Parameters to Protocol[...] must all be unique")547 else:548 # Subscripting a regular Generic subclass.549 _check_generic(cls, params, len(cls.__parameters__))550 return typing._GenericAlias(cls, params)551 552 def __init_subclass__(cls, *args, **kwargs):553 if '__orig_bases__' in cls.__dict__:554 error = typing.Generic in cls.__orig_bases__555 else:556 error = typing.Generic in cls.__bases__557 if error:558 raise TypeError("Cannot inherit from plain Generic")559 _maybe_adjust_parameters(cls)560 561 # Determine if this is a protocol or a concrete subclass.562 if not cls.__dict__.get('_is_protocol', None):563 cls._is_protocol = any(b is Protocol for b in cls.__bases__)564 565 # Set (or override) the protocol subclass hook.566 def _proto_hook(other):567 if not cls.__dict__.get('_is_protocol', None):568 return NotImplemented569 if not getattr(cls, '_is_runtime_protocol', False):570 if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']:571 return NotImplemented572 raise TypeError("Instance and class checks can only be used with"573 " @runtime protocols")574 if not _is_callable_members_only(cls):575 if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']:576 return NotImplemented577 raise TypeError("Protocols with non-method members"578 " don't support issubclass()")579 if not isinstance(other, type):580 # Same error as for issubclass(1, int)581 raise TypeError('issubclass() arg 1 must be a class')582 for attr in _get_protocol_attrs(cls):583 for base in other.__mro__:584 if attr in base.__dict__:585 if base.__dict__[attr] is None:586 return NotImplemented587 break588 annotations = getattr(base, '__annotations__', {})589 if (isinstance(annotations, typing.Mapping) and590 attr in annotations and591 isinstance(other, _ProtocolMeta) and592 other._is_protocol):593 break594 else:595 return NotImplemented596 return True597 if '__subclasshook__' not in cls.__dict__:598 cls.__subclasshook__ = _proto_hook599 600 # We have nothing more to do for non-protocols.601 if not cls._is_protocol:602 return603 604 # Check consistency of bases.605 for base in cls.__bases__:606 if not (base in (object, typing.Generic) or607 base.__module__ == 'collections.abc' and608 base.__name__ in _PROTO_WHITELIST or609 isinstance(base, _ProtocolMeta) and base._is_protocol):610 raise TypeError('Protocols can only inherit from other'611 f' protocols, got {repr(base)}')612 cls.__init__ = _no_init613 614 615# 3.8+616if hasattr(typing, 'runtime_checkable'):617 runtime_checkable = typing.runtime_checkable618# 3.7619else:620 def runtime_checkable(cls):621 """Mark a protocol class as a runtime protocol, so that it622 can be used with isinstance() and issubclass(). Raise TypeError623 if applied to a non-protocol class.624 625 This allows a simple-minded structural check very similar to the626 one-offs in collections.abc such as Hashable.627 """628 if not isinstance(cls, _ProtocolMeta) or not cls._is_protocol:629 raise TypeError('@runtime_checkable can be only applied to protocol classes,'630 f' got {cls!r}')631 cls._is_runtime_protocol = True632 return cls633 634 635# Exists for backwards compatibility.636runtime = runtime_checkable637 638 639# 3.8+640if hasattr(typing, 'SupportsIndex'):641 SupportsIndex = typing.SupportsIndex642# 3.7643else:644 @runtime_checkable645 class SupportsIndex(Protocol):646 __slots__ = ()647 648 @abc.abstractmethod649 def __index__(self) -> int:650 pass651 652 653if hasattr(typing, "Required"):654 # The standard library TypedDict in Python 3.8 does not store runtime information655 # about which (if any) keys are optional. See https://bugs.python.org/issue38834656 # The standard library TypedDict in Python 3.9.0/1 does not honour the "total"657 # keyword with old-style TypedDict(). See https://bugs.python.org/issue42059658 # The standard library TypedDict below Python 3.11 does not store runtime659 # information about optional and required keys when using Required or NotRequired.660 # Generic TypedDicts are also impossible using typing.TypedDict on Python <3.11.661 TypedDict = typing.TypedDict662 _TypedDictMeta = typing._TypedDictMeta663 is_typeddict = typing.is_typeddict664else:665 def _check_fails(cls, other):666 try:667 if sys._getframe(1).f_globals['__name__'] not in ['abc',668 'functools',669 'typing']:670 # Typed dicts are only for static structural subtyping.671 raise TypeError('TypedDict does not support instance and class checks')672 except (AttributeError, ValueError):673 pass674 return False675 676 def _dict_new(*args, **kwargs):677 if not args:678 raise TypeError('TypedDict.__new__(): not enough arguments')679 _, args = args[0], args[1:] # allow the "cls" keyword be passed680 return dict(*args, **kwargs)681 682 _dict_new.__text_signature__ = '($cls, _typename, _fields=None, /, **kwargs)'683 684 def _typeddict_new(*args, total=True, **kwargs):685 if not args:686 raise TypeError('TypedDict.__new__(): not enough arguments')687 _, args = args[0], args[1:] # allow the "cls" keyword be passed688 if args:689 typename, args = args[0], args[1:] # allow the "_typename" keyword be passed690 elif '_typename' in kwargs:691 typename = kwargs.pop('_typename')692 import warnings693 warnings.warn("Passing '_typename' as keyword argument is deprecated",694 DeprecationWarning, stacklevel=2)695 else:696 raise TypeError("TypedDict.__new__() missing 1 required positional "697 "argument: '_typename'")698 if args:699 try:700 fields, = args # allow the "_fields" keyword be passed701 except ValueError:702 raise TypeError('TypedDict.__new__() takes from 2 to 3 '703 f'positional arguments but {len(args) + 2} '704 'were given')705 elif '_fields' in kwargs and len(kwargs) == 1:706 fields = kwargs.pop('_fields')707 import warnings708 warnings.warn("Passing '_fields' as keyword argument is deprecated",709 DeprecationWarning, stacklevel=2)710 else:711 fields = None712 713 if fields is None:714 fields = kwargs715 elif kwargs:716 raise TypeError("TypedDict takes either a dict or keyword arguments,"717 " but not both")718 719 ns = {'__annotations__': dict(fields)}720 try:721 # Setting correct module is necessary to make typed dict classes pickleable.722 ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__')723 except (AttributeError, ValueError):724 pass725 726 return _TypedDictMeta(typename, (), ns, total=total)727 728 _typeddict_new.__text_signature__ = ('($cls, _typename, _fields=None,'729 ' /, *, total=True, **kwargs)')730 731 class _TypedDictMeta(type):732 def __init__(cls, name, bases, ns, total=True):733 super().__init__(name, bases, ns)734 735 def __new__(cls, name, bases, ns, total=True):736 # Create new typed dict class object.737 # This method is called directly when TypedDict is subclassed,738 # or via _typeddict_new when TypedDict is instantiated. This way739 # TypedDict supports all three syntaxes described in its docstring.740 # Subclasses and instances of TypedDict return actual dictionaries741 # via _dict_new.742 ns['__new__'] = _typeddict_new if name == 'TypedDict' else _dict_new743 # Don't insert typing.Generic into __bases__ here,744 # or Generic.__init_subclass__ will raise TypeError745 # in the super().__new__() call.746 # Instead, monkey-patch __bases__ onto the class after it's been created.747 tp_dict = super().__new__(cls, name, (dict,), ns)748 749 if any(issubclass(base, typing.Generic) for base in bases):750 tp_dict.__bases__ = (typing.Generic, dict)751 _maybe_adjust_parameters(tp_dict)752 753 annotations = {}754 own_annotations = ns.get('__annotations__', {})755 msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"756 own_annotations = {757 n: typing._type_check(tp, msg) for n, tp in own_annotations.items()758 }759 required_keys = set()760 optional_keys = set()761 762 for base in bases:763 annotations.update(base.__dict__.get('__annotations__', {}))764 required_keys.update(base.__dict__.get('__required_keys__', ()))765 optional_keys.update(base.__dict__.get('__optional_keys__', ()))766 767 annotations.update(own_annotations)768 for annotation_key, annotation_type in own_annotations.items():769 annotation_origin = get_origin(annotation_type)770 if annotation_origin is Annotated:771 annotation_args = get_args(annotation_type)772 if annotation_args:773 annotation_type = annotation_args[0]774 annotation_origin = get_origin(annotation_type)775 776 if annotation_origin is Required:777 required_keys.add(annotation_key)778 elif annotation_origin is NotRequired:779 optional_keys.add(annotation_key)780 elif total:781 required_keys.add(annotation_key)782 else:783 optional_keys.add(annotation_key)784 785 tp_dict.__annotations__ = annotations786 tp_dict.__required_keys__ = frozenset(required_keys)787 tp_dict.__optional_keys__ = frozenset(optional_keys)788 if not hasattr(tp_dict, '__total__'):789 tp_dict.__total__ = total790 return tp_dict791 792 __instancecheck__ = __subclasscheck__ = _check_fails793 794 TypedDict = _TypedDictMeta('TypedDict', (dict,), {})795 TypedDict.__module__ = __name__796 TypedDict.__doc__ = \797 """A simple typed name space. At runtime it is equivalent to a plain dict.798 799 TypedDict creates a dictionary type that expects all of its800 instances to have a certain set of keys, with each key801 associated with a value of a consistent type. This expectation802 is not checked at runtime but is only enforced by type checkers.803 Usage::804 805 class Point2D(TypedDict):806 x: int807 y: int808 label: str809 810 a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK811 b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check812 813 assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')814 815 The type info can be accessed via the Point2D.__annotations__ dict, and816 the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.817 TypedDict supports two additional equivalent forms::818 819 Point2D = TypedDict('Point2D', x=int, y=int, label=str)820 Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})821 822 The class syntax is only supported in Python 3.6+, while two other823 syntax forms work for Python 2.7 and 3.2+824 """825 826 if hasattr(typing, "_TypedDictMeta"):827 _TYPEDDICT_TYPES = (typing._TypedDictMeta, _TypedDictMeta)828 else:829 _TYPEDDICT_TYPES = (_TypedDictMeta,)830 831 def is_typeddict(tp):832 """Check if an annotation is a TypedDict class833 834 For example::835 class Film(TypedDict):836 title: str837 year: int838 839 is_typeddict(Film) # => True840 is_typeddict(Union[list, str]) # => False841 """842 return isinstance(tp, tuple(_TYPEDDICT_TYPES))843 844 845if hasattr(typing, "assert_type"):846 assert_type = typing.assert_type847 848else:849 def assert_type(__val, __typ):850 """Assert (to the type checker) that the value is of the given type.851 852 When the type checker encounters a call to assert_type(), it853 emits an error if the value is not of the specified type::854 855 def greet(name: str) -> None:856 assert_type(name, str) # ok857 assert_type(name, int) # type checker error858 859 At runtime this returns the first argument unchanged and otherwise860 does nothing.861 """862 return __val863 864 865if hasattr(typing, "Required"):866 get_type_hints = typing.get_type_hints867else:868 import functools869 import types870 871 # replaces _strip_annotations()872 def _strip_extras(t):873 """Strips Annotated, Required and NotRequired from a given type."""874 if isinstance(t, _AnnotatedAlias):875 return _strip_extras(t.__origin__)876 if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired):877 return _strip_extras(t.__args__[0])878 if isinstance(t, typing._GenericAlias):879 stripped_args = tuple(_strip_extras(a) for a in t.__args__)880 if stripped_args == t.__args__:881 return t882 return t.copy_with(stripped_args)883 if hasattr(types, "GenericAlias") and isinstance(t, types.GenericAlias):884 stripped_args = tuple(_strip_extras(a) for a in t.__args__)885 if stripped_args == t.__args__:886 return t887 return types.GenericAlias(t.__origin__, stripped_args)888 if hasattr(types, "UnionType") and isinstance(t, types.UnionType):889 stripped_args = tuple(_strip_extras(a) for a in t.__args__)890 if stripped_args == t.__args__:891 return t892 return functools.reduce(operator.or_, stripped_args)893 894 return t895 896 def get_type_hints(obj, globalns=None, localns=None, include_extras=False):897 """Return type hints for an object.898 899 This is often the same as obj.__annotations__, but it handles900 forward references encoded as string literals, adds Optional[t] if a901 default value equal to None is set and recursively replaces all902 'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T'903 (unless 'include_extras=True').904 905 The argument may be a module, class, method, or function. The annotations906 are returned as a dictionary. For classes, annotations include also907 inherited members.908 909 TypeError is raised if the argument is not of a type that can contain910 annotations, and an empty dictionary is returned if no annotations are911 present.912 913 BEWARE -- the behavior of globalns and localns is counterintuitive914 (unless you are familiar with how eval() and exec() work). The915 search order is locals first, then globals.916 917 - If no dict arguments are passed, an attempt is made to use the918 globals from obj (or the respective module's globals for classes),919 and these are also used as the locals. If the object does not appear920 to have globals, an empty dictionary is used.921 922 - If one dict argument is passed, it is used for both globals and923 locals.924 925 - If two dict arguments are passed, they specify globals and926 locals, respectively.927 """928 if hasattr(typing, "Annotated"):929 hint = typing.get_type_hints(930 obj, globalns=globalns, localns=localns, include_extras=True931 )932 else:933 hint = typing.get_type_hints(obj, globalns=globalns, localns=localns)934 if include_extras:935 return hint936 return {k: _strip_extras(t) for k, t in hint.items()}937 938 939# Python 3.9+ has PEP 593 (Annotated)940if hasattr(typing, 'Annotated'):941 Annotated = typing.Annotated942 # Not exported and not a public API, but needed for get_origin() and get_args()943 # to work.944 _AnnotatedAlias = typing._AnnotatedAlias945# 3.7-3.8946else:947 class _AnnotatedAlias(typing._GenericAlias, _root=True):948 """Runtime representation of an annotated type.949 950 At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'951 with extra annotations. The alias behaves like a normal typing alias,952 instantiating is the same as instantiating the underlying type, binding953 it to types is also the same.954 """955 def __init__(self, origin, metadata):956 if isinstance(origin, _AnnotatedAlias):957 metadata = origin.__metadata__ + metadata958 origin = origin.__origin__959 super().__init__(origin, origin)960 self.__metadata__ = metadata961 962 def copy_with(self, params):963 assert len(params) == 1964 new_type = params[0]965 return _AnnotatedAlias(new_type, self.__metadata__)966 967 def __repr__(self):968 return (f"typing_extensions.Annotated[{typing._type_repr(self.__origin__)}, "969 f"{', '.join(repr(a) for a in self.__metadata__)}]")970 971 def __reduce__(self):972 return operator.getitem, (973 Annotated, (self.__origin__,) + self.__metadata__974 )975 976 def __eq__(self, other):977 if not isinstance(other, _AnnotatedAlias):978 return NotImplemented979 if self.__origin__ != other.__origin__:980 return False981 return self.__metadata__ == other.__metadata__982 983 def __hash__(self):984 return hash((self.__origin__, self.__metadata__))985 986 class Annotated:987 """Add context specific metadata to a type.988 989 Example: Annotated[int, runtime_check.Unsigned] indicates to the990 hypothetical runtime_check module that this type is an unsigned int.991 Every other consumer of this type can ignore this metadata and treat992 this type as int.993 994 The first argument to Annotated must be a valid type (and will be in995 the __origin__ field), the remaining arguments are kept as a tuple in996 the __extra__ field.997 998 Details:999 1000 - It's an error to call `Annotated` with less than two arguments.1001 - Nested Annotated are flattened::1002 1003 Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]1004 1005 - Instantiating an annotated type is equivalent to instantiating the1006 underlying type::1007 1008 Annotated[C, Ann1](5) == C(5)1009 1010 - Annotated can be used as a generic type alias::1011 1012 Optimized = Annotated[T, runtime.Optimize()]1013 Optimized[int] == Annotated[int, runtime.Optimize()]1014 1015 OptimizedList = Annotated[List[T], runtime.Optimize()]1016 OptimizedList[int] == Annotated[List[int], runtime.Optimize()]1017 """1018 1019 __slots__ = ()1020 1021 def __new__(cls, *args, **kwargs):1022 raise TypeError("Type Annotated cannot be instantiated.")1023 1024 @typing._tp_cache1025 def __class_getitem__(cls, params):1026 if not isinstance(params, tuple) or len(params) < 2:1027 raise TypeError("Annotated[...] should be used "1028 "with at least two arguments (a type and an "1029 "annotation).")1030 allowed_special_forms = (ClassVar, Final)1031 if get_origin(params[0]) in allowed_special_forms:1032 origin = params[0]1033 else:1034 msg = "Annotated[t, ...]: t must be a type."1035 origin = typing._type_check(params[0], msg)1036 metadata = tuple(params[1:])1037 return _AnnotatedAlias(origin, metadata)1038 1039 def __init_subclass__(cls, *args, **kwargs):1040 raise TypeError(1041 f"Cannot subclass {cls.__module__}.Annotated"1042 )1043 1044# Python 3.8 has get_origin() and get_args() but those implementations aren't1045# Annotated-aware, so we can't use those. Python 3.9's versions don't support1046# ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do.1047if sys.version_info[:2] >= (3, 10):1048 get_origin = typing.get_origin1049 get_args = typing.get_args1050# 3.7-3.91051else:1052 try:1053 # 3.9+1054 from typing import _BaseGenericAlias1055 except ImportError:1056 _BaseGenericAlias = typing._GenericAlias1057 try:1058 # 3.9+1059 from typing import GenericAlias as _typing_GenericAlias1060 except ImportError:1061 _typing_GenericAlias = typing._GenericAlias1062 1063 def get_origin(tp):1064 """Get the unsubscripted version of a type.1065 1066 This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar1067 and Annotated. Return None for unsupported types. Examples::1068 1069 get_origin(Literal[42]) is Literal1070 get_origin(int) is None1071 get_origin(ClassVar[int]) is ClassVar1072 get_origin(Generic) is Generic1073 get_origin(Generic[T]) is Generic1074 get_origin(Union[T, int]) is Union1075 get_origin(List[Tuple[T, T]][int]) == list1076 get_origin(P.args) is P1077 """1078 if isinstance(tp, _AnnotatedAlias):1079 return Annotated1080 if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias, _BaseGenericAlias,1081 ParamSpecArgs, ParamSpecKwargs)):1082 return tp.__origin__1083 if tp is typing.Generic:1084 return typing.Generic1085 return None1086 1087 def get_args(tp):1088 """Get type arguments with all substitutions performed.1089 1090 For unions, basic simplifications used by Union constructor are performed.1091 Examples::1092 get_args(Dict[str, int]) == (str, int)1093 get_args(int) == ()1094 get_args(Union[int, Union[T, int], str][int]) == (int, str)1095 get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])1096 get_args(Callable[[], T][int]) == ([], int)1097 """1098 if isinstance(tp, _AnnotatedAlias):1099 return (tp.__origin__,) + tp.__metadata__1100 if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias)):1101 if getattr(tp, "_special", False):1102 return ()1103 res = tp.__args__1104 if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis:1105 res = (list(res[:-1]), res[-1])1106 return res1107 return ()1108 1109 1110# 3.10+1111if hasattr(typing, 'TypeAlias'):1112 TypeAlias = typing.TypeAlias1113# 3.91114elif sys.version_info[:2] >= (3, 9):1115 class _TypeAliasForm(typing._SpecialForm, _root=True):1116 def __repr__(self):1117 return 'typing_extensions.' + self._name1118 1119 @_TypeAliasForm1120 def TypeAlias(self, parameters):1121 """Special marker indicating that an assignment should1122 be recognized as a proper type alias definition by type1123 checkers.1124 1125 For example::1126 1127 Predicate: TypeAlias = Callable[..., bool]1128 1129 It's invalid when used anywhere except as in the example above.1130 """1131 raise TypeError(f"{self} is not subscriptable")1132# 3.7-3.81133else:1134 class _TypeAliasForm(typing._SpecialForm, _root=True):1135 def __repr__(self):1136 return 'typing_extensions.' + self._name1137 1138 TypeAlias = _TypeAliasForm('TypeAlias',1139 doc="""Special marker indicating that an assignment should1140 be recognized as a proper type alias definition by type1141 checkers.1142 1143 For example::1144 1145 Predicate: TypeAlias = Callable[..., bool]1146 1147 It's invalid when used anywhere except as in the example1148 above.""")1149 1150 1151class _DefaultMixin:1152 """Mixin for TypeVarLike defaults."""1153 1154 __slots__ = ()1155 1156 def __init__(self, default):1157 if isinstance(default, (tuple, list)):1158 self.__default__ = tuple((typing._type_check(d, "Default must be a type")1159 for d in default))1160 elif default:1161 self.__default__ = typing._type_check(default, "Default must be a type")1162 else:1163 self.__default__ = None1164 1165 1166# Add default and infer_variance parameters from PEP 696 and 6951167class TypeVar(typing.TypeVar, _DefaultMixin, _root=True):1168 """Type variable."""1169 1170 __module__ = 'typing'1171 1172 def __init__(self, name, *constraints, bound=None,1173 covariant=False, contravariant=False,1174 default=None, infer_variance=False):1175 super().__init__(name, *constraints, bound=bound, covariant=covariant,1176 contravariant=contravariant)1177 _DefaultMixin.__init__(self, default)1178 self.__infer_variance__ = infer_variance1179 1180 # for pickling:1181 try:1182 def_mod = sys._getframe(1).f_globals.get('__name__', '__main__')1183 except (AttributeError, ValueError):1184 def_mod = None1185 if def_mod != 'typing_extensions':1186 self.__module__ = def_mod1187 1188 1189# Python 3.10+ has PEP 6121190if hasattr(typing, 'ParamSpecArgs'):1191 ParamSpecArgs = typing.ParamSpecArgs1192 ParamSpecKwargs = typing.ParamSpecKwargs1193# 3.7-3.91194else:1195 class _Immutable:1196 """Mixin to indicate that object should not be copied."""1197 __slots__ = ()1198 1199 def __copy__(self):1200 return self