o ?Ogi@sdZddlmZmZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl m Z mZmZmZgdZddddd Zdddd d Zd dZddZdddZddZddZddZddZddZgZdddddZefd d!ZGd"d#d#Z Gd$d%d%Z!Gd&d'd'e d d(Z"Gd)d*d*e"d d(Z#e"d+d,Z$e"d-d.Z%e"d/d0Z&e"d1d2Z'e"d3d4Z(e"d5d6Z)e#ed dd7d8Z*e"d9d:Z+e"d;d<Z,e"d=d>Z-Gd?d@d@e d d(Z.GdAdBdBZ/GdCdDdDe e!e/d d(Z0GdEdFdFe e!d d(Z1GdGdHdHe e!d d(Z2GdIdJdJe e!e/d d(Z3dKdLZ4GdMdNdNe d d(Z5GdOdPdPe5d d(Z6GdQdRdRe5d d(Z7GdSdTdTe6d d(Z8GdUdVdVe7d d(Z9GdWdXdXe7d d(Z:GdYdZdZe6d d(Z;d[d\ZGdadbdbZ?GdcddddZ@GdedfdfZAgdgZBgdhZCeBeCdigZDdjdkZEdldmZFdndoZGddrdsZHddudvZIgdwdxdygdzZJGd{d|d|eZKGd}d~d~e?eKdZLGddde6d d(ZMGdddZNddZOddZPddZQe jRe jSe jTe jUe eefZVdddZWddZXddZYddZZddZ[ddZ\ddZ]ddZ^ddZ_ddZ`e0dZae0dZbe0dZce0dd dZde0dd dZee0dd dZfe0dd dZge0dd ehdZie0dejekZle7ZmemejjndZnemejjodpZoemejjpdtZpemejjqdpZqemejjrdpZremejjsdpZsemejjtdpZtemejjudpZuemejjvdZvemejjwdpZwemejjxdpZxe9ejjydZydey_emejjzdpddZ{emejj|dpZ|emejj}dZ}emejj~dZ~emejjdpZemejjdpZemejjdZe:eddddZde_emedpdddZemejdpddZemedpdddZzemedpdddZemejjdpZemejjdpZemejjdZemejjdpZemejdpddZemejdpddZemeddddZemejdddZemejdZemejdpZemejdZemejjdtZemejjdZemehdpdddZde_eOGdddeLZeOGdddeLZeOGdddeLZeOGddÄdeLZeOGddńdeLZeOGddDŽdeLedZeOGddɄdeLedZddd̄ZehdͣZehdΣZGddЄdehZddd҄ZeheddiZddԄZee_GddքdehZdd dלddلZeheddiZddۄe_Gdd݄d݃ZekZdZGdd߄de?elZGdddeejZGdddeekZGdddZede_ee jej<eme jdpZeme jdpZGdddZ ede _e e je j<dS)aU The typing module: Support for gradual typing as defined by PEP 484. At large scale, the structure of the module is following: * Imports and exports, all public names should be explicitly added to __all__. * Internal helper functions: these should never be used in code outside this module. * _SpecialForm and its instances (special forms): Any, NoReturn, ClassVar, Union, Optional, Concatenate * Classes whose instances can be type arguments in addition to types: ForwardRef, TypeVar and ParamSpec * The core of internal generics API: _GenericAlias and _VariadicGenericAlias, the latter is currently only used by Tuple and Callable. All subscripted types like X[int], Union[int, str], etc., are instances of either of these classes. * The public counterpart of the generics API consists of two classes: Generic and Protocol. * Public helper functions: get_type_hints, overload, cast, no_type_check, no_type_check_decorator. * Generic aliases for collections.abc ABCs and few additional protocols. * Special types: NewType, NamedTuple, TypedDict. * Wrapper submodules for re and io related types. )abstractmethodABCMetaN)WrapperDescriptorTypeMethodWrapperTypeMethodDescriptorType GenericAlias)T AnnotatedAnyCallableClassVar ConcatenateFinal ForwardRefGenericLiteralOptional ParamSpecProtocolTupleTypeTypeVarUnion AbstractSet ByteString ContainerContextManagerHashable ItemsViewIterableIteratorKeysViewMapping MappingViewMutableMappingMutableSequence MutableSetSequenceSized ValuesView Awaitable AsyncIterator AsyncIterable Coroutine CollectionAsyncGeneratorAsyncContextManager Reversible SupportsAbs SupportsBytesSupportsComplex SupportsFloat SupportsIndex SupportsInt SupportsRoundChainMapCounterDequeDict DefaultDictList OrderedDictSet FrozenSet NamedTuple TypedDict GeneratorBinaryIOIOMatchPatternTextIOAnyStrcastfinalget_args get_originget_type_hints is_typeddictNewType no_type_checkno_type_check_decoratorNoReturnoverload ParamSpecArgsParamSpecKwargsruntime_checkableText TYPE_CHECKING TypeAlias TypeGuardFallow_special_formscCs,|durtdSt|trt|||dS|S)z=For converting None to type(None), and strings to ForwardRef.N)moduleis_class)type isinstancestrr)argr^r]rd-/opt/alt/python310/lib64/python3.10/typing.py _type_converts  rfTc Csttf}|s|tf7}|r|tf7}t|||d}t|tr*|j|vr*t|d|t t tt fvr4|St|t s?|ttfvrGtd|dt|t tttjtttfrV|St|set|d|dd|S)aCheck that the argument is a type, and return it (internal helper). As a special case, accept None and return type(None) instead. Also wrap strings into ForwardRef instances. Consider several corner cases, for example plain special forms like Union are not valid, while Union[int, str] is OK, etc. The msg argument is a human-readable error message, e.g:: "Union[arg, ...]: arg should be a type." We append the repr() of the actual value (truncated to 100 chars). )r^r]z is not valid as type argumentzPlain z Got z.100.)rrr r rfra _GenericAlias __origin__ TypeErrorr rSrZ _SpecialFormr`rrtypes UnionTyperrUrVcallable)rcmsg is_argumentr^r]Zinvalid_generic_formsrdrdre _type_checks(     rqcCs|dup t|ttttfS)N.)ratuplelistr_ConcatenateGenericAlias)rcrdrdre_is_param_exprs  rucCsft|tjr t|St|tr |jdkr|jS|jd|jS|dur&dSt|tjr/|jSt|S)a;Return the repr() of an object, special-casing types (internal helper). If obj is a type, we return a shorter version than the default type.__repr__, based on the module and qualified name, which is typically enough to uniquely identify a type. For everything else, we fall back on repr(obj). builtinsrg.z...) rarlrreprr` __module__ __qualname__ FunctionType__name__)objrdrdre _type_reprs    r}csj|durt}g|D]&}t||r|vr|t|tttjfr0fdd|jDq t S)zCollect all type variable contained in types in order of first appearance (lexicographic order). For example:: _collect_type_vars((T, List[S, T])) == (T, S) Ncsg|]}|vr|qSrdrd.0ttvarsrdre z&_collect_type_vars..) rraappendrhrrlrmextend__parameters__rr)Ztypes_ typevar_typesrrdrre_collect_type_varss rc CsR|s t|dt|}||kr'td||krdndd|d|d|dS) zCheck correct count for parameters of a generic cls (internal helper). This gives a nice error message in case of count mismatch. z is not a generic classzToo manyfewz arguments for z ; actual z , expected N)rjlen)cls parametersZelenZalenrdrdre_check_genericsrcCs~t|jdkr|rt|ds|fSt||t|jg}t||jD]\}}t|tr5t|tr5t|}| |q#t|S)z`Prepares the parameters for a Generic containing ParamSpec variables (internal helper). r) rrrurziprarrsrrr)rparamsZ_paramspZtvarrdrdre_prepare_paramspec_paramss  rcCsJt|}t|t|kr#g}|D]}||vr ||||q|}|SN)setrrremove)rZ all_paramsZ new_paramsrrdrdre _deduplicates  rcCsxg}|D]1}t|ttjfr||jqt|tr0t|dkr0|dtur0||ddq| |qtt |S)zyAn internal helper for Union creation and substitution: flatten Unions among parameters, then remove duplicates. rrN) ra_UnionGenericAliasrlrmr__args__rrrrrrrrrrdrdre_remove_dups_flatten s"  rcCs8g}|D]}t|tr||jq||qt|S)zJAn internal helper for Literal creation: flatten Literals among parameters)ra_LiteralGenericAliasrrrrrrrdrdre_flatten_literal_paramss   rtypedcs fdd}|dur||S|S)zInternal wrapper caching __getitem__ of generic types with a fallback to original function for non-hashable arguments. cs8tjdtjtfdd}|S)Nrcs2z|i|WStyYnw|i|Srrjargskwdscachedfuncrdreinner2s  z+_tp_cache..decorator..inner) functools lru_cache _cleanupsr cache_clearwraps)rrrrre decorator.s  z_tp_cache..decoratorNrd)rrrrdrre _tp_cache*s  rcst|tr |St|tttjfrGtfdd|jD}||jkr*|St|tr5t|j |St|tjrBt t j |S||S|S)zEvaluate all forward references in the given type t. For use of globalns and localns see the docstring for get_type_hints(). recursive_guard is used to prevent infinite recursion with a recursive ForwardRef. c3s|] }t|VqdSr) _eval_typeraglobalnslocalnsrecursive_guardrdre Iz_eval_type..)rar _evaluaterhrrlrmrrrrirreduceoperatoror_ copy_with)rrrrZev_argsrdrrer@s      rc@seZdZdZdZddZdS)_FinalzMixin to prohibit subclassing) __weakref__cOsd|vrtddS)N_rootz&Cannot subclass special typing classesrselfrrrdrdre__init_subclass__Zsz_Final.__init_subclass__N)r{rxry__doc__ __slots__rrdrdrdrerUs rc@s$eZdZdZdZddZddZdS) _Immutablez3Mixin to indicate that object should not be copied.rdcC|Srrdrrdrdre__copy__bz_Immutable.__copy__cCrrrd)rZmemordrdre __deepcopy__erz_Immutable.__deepcopy__N)r{rxryrrrrrdrdrdrer^s  rc@sleZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ eddZdS)rk)_namer_getitemcCs||_|j|_|j|_dSr)rr{rr)rgetitemrdrdre__init__ns z_SpecialForm.__init__cCs|dvr|jSt|)N>r{ry)rAttributeError)ritemrdrdre __getattr__ssz_SpecialForm.__getattr__cCtd|)NCannot subclass r)rbasesrdrdre__mro_entries__yz_SpecialForm.__mro_entries__cC d|jSNtyping.rrrdrdre__repr__| z_SpecialForm.__repr__cC|jSrrrrdrdre __reduce__z_SpecialForm.__reduce__cOr)NzCannot instantiate rrrdrdre__call__rz_SpecialForm.__call__cC t||fSrrrotherrdrdre__or__ z_SpecialForm.__or__cC t||fSrrrrdrdre__ror__rz_SpecialForm.__ror__cCt|d)Nz! cannot be used with isinstance()rrr|rdrdre__instancecheck__rz_SpecialForm.__instancecheck__cCr)Nz! cannot be used with issubclass()rrrrdrdre__subclasscheck__rz_SpecialForm.__subclasscheck__cCs |||Sr)rrrrdrdre __getitem__s z_SpecialForm.__getitem__N)r{rxryrrrrrrrrrrrrrrdrdrdrerkksrk)rc@eZdZddZdS)_LiteralSpecialFormcCs"t|ts|f}|j|g|RSr)rarrrrrdrdrers z_LiteralSpecialForm.__getitem__N)r{rxryrrdrdrdrers rcCr)a`Special type indicating an unconstrained type. - Any is compatible with every type. - Any assumed to have all methods. - All values assumed to be instances of Any. Note that all the above statements are true from the point of view of static type checkers. At runtime, Any should not be used with instance or class checks.  is not subscriptablerrrdrdrer  r cCr)aSpecial type indicating functions that never return. Example:: from typing import NoReturn def stop() -> NoReturn: raise Exception('no way') This type is invalid in other positions, e.g., ``List[NoReturn]`` will fail in static type checkers. rrrrdrdrerSs rScCt||d}t||fS)a3Special type construct to mark class variables. An annotation wrapped in ClassVar indicates that a given attribute is intended to be used as a class variable and should not be set on instances of that class. Usage:: class Starship: stats: ClassVar[Dict[str, int]] = {} # class variable damage: int = 10 # instance variable ClassVar accepts only types and cannot be further subscribed. Note that ClassVar is not a class itself, and should not be used with isinstance() or issubclass().  accepts only single type.rqrhrrrrdrdrer s r cCr)aSpecial typing construct to indicate final names to type checkers. A final name cannot be re-assigned or overridden in a subclass. For example: MAX_SIZE: Final = 9000 MAX_SIZE += 1 # Error reported by type checker class Connection: TIMEOUT: Final[int] = 10 class FastConnector(Connection): TIMEOUT = 1 # Error reported by type checker There is no runtime checking of these properties. rrrrdrdrer s r cs|dkrtdt|ts|f}dtfdd|D}t|}t|dkr+|dSt|dkr>td |vr>t||d d St||S) a'Union type; Union[X, Y] means either X or Y. To define a union, use e.g. Union[int, str]. Details: - The arguments must be types and there must be at least one. - None as an argument is a special case and is replaced by type(None). - Unions of unions are flattened, e.g.:: Union[Union[int, str], float] == Union[int, str, float] - Unions of a single argument vanish, e.g.:: Union[int] == int # The constructor actually returns int - Redundant arguments are skipped, e.g.:: Union[int, str, int] == Union[int, str] - When comparing unions, the argument order is ignored, e.g.:: Union[int, str] == Union[str, int] - You cannot subclass or instantiate a union. - You can use Optional[X] as a shorthand for Union[X, None]. rdz Cannot take a Union of no types.z)Union[arg, ...]: each arg must be a type.c3|]}t|VqdSrrqrrrordrerzUnion..rrNrname)rjrarrrrr`rrrdrrers   rcCs t||d}t|tdfS)zEOptional type. Optional[X] is equivalent to Union[X, None]. z requires a single type.N)rqrr`)rrrcrdrdrer srcGsHt|}ztddttt|D}Wn tyYnwt||S)aSpecial typing form to define literal types (a.k.a. value types). This form can be used to indicate to type checkers that the corresponding variable or function parameter has a value equivalent to the provided literal (or one of several literals): def validate_simple(data: Any) -> Literal[True]: # always returns True ... MODE = Literal['r', 'rb', 'w', 'wb'] def open_helper(file: str, mode: MODE) -> str: ... open_helper('/some/path', 'r') # Passes type check open_helper('/other/path', 'typo') # Error in type checker Literal[...] cannot be subclassed. At runtime, an arbitrary value is allowed as type argument to Literal[...], but type checkers may impose restrictions. css|]\}}|VqdSrrd)rr_rdrdrer0zLiteral..)rrrrrs_value_and_type_iterrjrrrdrdrers"  rcCr)aSpecial marker indicating that an assignment should be recognized as a proper type alias definition by type checkers. For example:: Predicate: TypeAlias = Callable[..., bool] It's invalid when used anywhere except as in the example above. rrrrdrdrerZ7rrZcsv|dkrtdt|ts|f}t|dtstddgfdd|ddD|dR}t||ttfd d S) aUsed in conjunction with ``ParamSpec`` and ``Callable`` to represent a higher order function which adds, removes or transforms parameters of a callable. For example:: Callable[Concatenate[int, P], int] See PEP 612 for detailed information. rdz&Cannot take a Concatenate of no types.AThe last parameter to Concatenate should be a ParamSpec variable.z/Concatenate[arg, ...]: each arg must be a type.c3rrrrrrdrerZrzConcatenate..NT_typevar_types_paramspec_tvars)rjrarrrrtrrrdrrer Fs  (r cCr)aSpecial typing form used to annotate the return type of a user-defined type guard function. ``TypeGuard`` only accepts a single type argument. At runtime, functions marked this way should return a boolean. ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static type checkers to determine a more precise type of an expression within a program's code flow. Usually type narrowing is done by analyzing conditional code flow and applying the narrowing to a block of code. The conditional expression here is sometimes referred to as a "type guard". Sometimes it would be convenient to use a user-defined boolean function as a type guard. Such a function should use ``TypeGuard[...]`` as its return type to alert static type checkers to this intention. Using ``-> TypeGuard`` tells the static type checker that for a given function: 1. The return value is a boolean. 2. If the return value is ``True``, the type of its argument is the type inside ``TypeGuard``. For example:: def is_str(val: Union[str, float]): # "isinstance" type guard if isinstance(val, str): # Type of ``val`` is narrowed to ``str`` ... else: # Else, type of ``val`` is narrowed to ``float``. ... Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower form of ``TypeA`` (it can even be a wider form) and this may lead to type-unsafe results. The main reason is to allow for things like narrowing ``List[object]`` to ``List[str]`` even though the latter is not a subtype of the former, since ``List`` is invariant. The responsibility of writing type-safe type guards is left to the user. ``TypeGuard`` also works with type variables. For more information, see PEP 647 (User-Defined Type Guards). rrrrdrdrer[`s, r[c@sDeZdZdZdZdddddZd d Zd d Zd dZddZ dS)rz-Internal wrapper to hold a forward reference.)__forward_arg____forward_code____forward_evaluated____forward_value____forward_is_argument____forward_is_class____forward_module__TNF)r_cCstt|ts td|zt|dd}Wnty"td|w||_||_d|_d|_||_ ||_ ||_ dS)Nz*Forward reference must be a string -- got zevalz/Forward reference must be an expression -- got F) rarbrjcompile SyntaxErrorr r r r r rr)rrcrpr^r_coderdrdrers   zForwardRef.__init__cCs|j|vr|S|jr||urW|dur|duri}}n |dur"|}n|dur(|}|jdur9ttj|jdd|}tt|j ||d|j |j d}t |||||jhB|_ d|_|j S)N__dict__z*Forward references must evaluate to types.)rpr]T)r r rgetattrsysmodulesgetrqrr r rrr )rrrrZtype_rdrdrers0    zForwardRef._evaluatecCsJt|tstS|jr|jr|j|jko|j|jkS|j|jko$|j|jkSr)rarNotImplementedr r r rrrdrdre__eq__s      zForwardRef.__eq__cCt|j|jfSr)hashr rrrdrdre__hash__zForwardRef.__hash__cCsd|jdS)Nz ForwardRef())r rrdrdrerrzForwardRef.__repr__TN) r{rxryrrrrrrrrdrdrdrers rc@s8eZdZdZddZddZddZdd Zd d Zd S) _TypeVarLikez5Mixin for TypeVar-like types (TypeVar and ParamSpec).cCsB|r|rtdt||_t||_|rt|d|_dSd|_dS)zfUsed to setup TypeVars and ParamSpec's bound, covariant and contravariant attributes. z"Bivariant types are not supported.zBound must be a type.N) ValueErrorbool __covariant____contravariant__rq __bound__)rbound covariant contravariantrdrdrers   z_TypeVarLike.__init__cCrrrrrightrdrdrerrz_TypeVarLike.__or__cCrrrrleftrdrdrerrz_TypeVarLike.__ror__cCs&|jrd}n|jr d}nd}||jS)N+-~)r$r%r{)rprefixrdrdrers  z_TypeVarLike.__repr__cCrr)r{rrdrdrerrz_TypeVarLike.__reduce__N) r{rxryrrrrrrrdrdrdrer!s  r!cs.eZdZdZdZddddfdd ZZS)raType variable. Usage:: T = TypeVar('T') # Can be anything A = TypeVar('A', str, bytes) # Must be str or bytes Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function definitions. See class Generic for more information on generic types. Generic functions work as follows: def repeat(x: T, n: int) -> List[T]: '''Return a list containing n references to x.''' return [x]*n def longest(x: A, y: A) -> A: '''Return the longest of two strings.''' return x if len(x) >= len(y) else y The latter example's signature is essentially the overloading of (str, str) -> str and (bytes, bytes) -> bytes. Also note that if the arguments are instances of some subclass of str, the return type is still plain str. At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError. Type variables defined with covariant=True or contravariant=True can be used to declare covariant or contravariant generic types. See PEP 484 for more details. By default generic types are invariant in all type variables. Type variables can be introspected. e.g.: T.__name__ == 'T' T.__constraints__ == () T.__covariant__ == False T.__contravariant__ = False A.__constraints__ == (str, bytes) Note that only type variables defined in global scope can be pickled. )r{r&__constraints__r$r%rNFr'r(r)c s||_t||||r|durtd|r!t|dkr!tddtfdd|D|_z tdj dd}Wn t t fyHd}Ynw|d krR||_ dSdS) Nz-Constraints cannot be combined with bound=...rz"A single constraint is not allowedz:TypeVar(name, constraint, ...): constraints must be types.c3rrrr~rrdrer*rz#TypeVar.__init__..r{__main__typing)r{superrrjrrrr2r _getframe f_globalsrrr"rx)rrr'r(r)Z constraintsdef_mod __class__rrer!s   zTypeVar.__init__)r{rxryrrr __classcell__rdrdr:rers +rc@(eZdZdZddZddZddZdS) rUa<The args for a ParamSpec object. Given a ParamSpec object P, P.args is an instance of ParamSpecArgs. ParamSpecArgs objects have a reference back to their ParamSpec: P.args.__origin__ is P This type is meant for runtime introspection and has no special meaning to static type checkers. cC ||_dSrriroriginrdrdrer?rzParamSpecArgs.__init__cC|jjdS)Nz.argsrir{rrdrdrerBrzParamSpecArgs.__repr__cCt|tstS|j|jkSr)rarUrrirrdrdrerE  zParamSpecArgs.__eq__Nr{rxryrrrrrdrdrdrerU3   rUc@r=) rVaFThe kwargs for a ParamSpec object. Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs. ParamSpecKwargs objects have a reference back to their ParamSpec: P.kwargs.__origin__ is P This type is meant for runtime introspection and has no special meaning to static type checkers. cCr>rr?r@rdrdrerWrzParamSpecKwargs.__init__cCrB)Nz.kwargsrCrrdrdrerZrzParamSpecKwargs.__repr__cCrDr)rarVrrirrdrdrer]rEzParamSpecKwargs.__eq__NrFrdrdrdrerVKrGrVcsFeZdZdZdZeddZeddZdddd fd d ZZ S) raqParameter specification variable. Usage:: P = ParamSpec('P') Parameter specification variables exist primarily for the benefit of static type checkers. They are used to forward the parameter types of one callable to another callable, a pattern commonly found in higher order functions and decorators. They are only valid when used in ``Concatenate``, or as the first argument to ``Callable``, or as parameters for user-defined Generics. See class Generic for more information on generic types. An example for annotating a decorator:: T = TypeVar('T') P = ParamSpec('P') def add_logging(f: Callable[P, T]) -> Callable[P, T]: '''A type-safe decorator to add logging to a function.''' def inner(*args: P.args, **kwargs: P.kwargs) -> T: logging.info(f'{f.__name__} was called') return f(*args, **kwargs) return inner @add_logging def add_two(x: float, y: float) -> float: '''Add two numbers together.''' return x + y Parameter specification variables defined with covariant=True or contravariant=True can be used to declare covariant or contravariant generic types. These keyword arguments are valid, but their actual semantics are yet to be decided. See PEP 612 for details. Parameter specification variables can be introspected. e.g.: P.__name__ == 'P' P.__bound__ == None P.__covariant__ == False P.__contravariant__ == False Note that only parameter specification variables defined in global scope can be pickled. )r{r&r$r%rcCt|Sr)rUrrdrdrerzParamSpec.argscCrHr)rVrrdrdrekwargsrIzParamSpec.kwargsNFr3c s`||_t|||z tdjdd}Wn ttfy$d}Ynw|dkr.||_ dSdS)Nrr{r4r5) r{r6rrr7r8rrr"rx)rrr'r(r)r9r:rdrers zParamSpec.__init__) r{rxryrrpropertyrrJrr<rdrdr:rercs-  rcCs|do |dS)N__) startswithendswith)attrrdrdre _is_dundersrPcsdeZdZdZdddddZddZd d Zd d Zfd dZddZ ddZ fddZ Z S)_BaseGenericAliasaThe central part of internal API. This represents a generic version of type 'origin' with type arguments 'params'. There are two kind of these aliases: user defined and special. The special ones are wrappers around builtin collections and ABCs in collections.abc. These must have 'name' always set. If 'inst' is False, then the alias can't be instantiated, this is used by e.g. typing.List and typing.Dict. TNinstrcCs||_||_||_d|_dSr)_instrrir)rrArSrrdrdrers z_BaseGenericAlias.__init__cOsT|jstd|jd|jjd|j|i|}z||_W|Sty)Y|Sw)NzType z cannot be instantiated; use z () instead)rTrjrrir{__orig_class__r)rrrJresultrdrdrers   z_BaseGenericAlias.__call__cCsjg}|j|vr ||j||}||ddD]}t|ts&t|tr+t|Sq|tt|S)Nr)ririndexrarQ issubclassrrr)rrresibrdrdrers    z!_BaseGenericAlias.__mro_entries__cCs<|dvr |jp |jjSd|jvrt|st|j|St|)N>r{ryri)rrir{rrPrrrrOrdrdrers  z_BaseGenericAlias.__getattr__cs4t|s|dvrt||dSt|j||dS)N>r_nparamsrTrr)rPr6 __setattr__setattrri)rrOvalr:rdrer^sz_BaseGenericAlias.__setattr__cC|t|Srrr`rrdrdrerrz#_BaseGenericAlias.__instancecheck__cCtd)NzBSubscripted generics cannot be used with class and instance checksrrrdrdrerz#_BaseGenericAlias.__subclasscheck__cs&tttddt|jDS)NcSsg|]}t|s|qSrd)rPrrOrdrdrerrz-_BaseGenericAlias.__dir__..)rsrr6__dir__dirrirr:rdrerfs z_BaseGenericAlias.__dir__) r{rxryrrrrrr^rrrfr<rdrdr:rerQs  rQcsxeZdZddeddfdd ZddZd d Zd d Zd dZe ddZ ddZ ddZ ddZ fddZZS)rhTNF)rSrrrcsdtj|||dt|ts|f}tdd|D|_t||d|_||_||_|s0|j |_ dSdS)NrRcss,|]}|tur dn|turdn|VqdS).rdN)_TypingEllipsis _TypingEmptyrrdrdrers  z)_GenericAlias.__init__..)r) r6rrarrrrrrrrx)rrArrSrrrr:rdrers   z_GenericAlias.__init__cC&t|tstS|j|jko|j|jkSr)rarhrrirrrdrdrer   z_GenericAlias.__eq__cCrr)rrirrrdrdrer rz_GenericAlias.__hash__cCrrrr*rdrdrerrz_GenericAlias.__or__cCrrrr,rdrdrerrz_GenericAlias.__ror__csL|jttfvrtd|t|ts|f}tdd|D}|jr2tdd|jDr2t ||}n t ||t |jt t |j|g}|jD]V}t||jrjt|tre|}t|sdtd|n"|}nt|tttjfr|j}|rtfdd|D}||}|jtjjkrt|tr||qH||qH|t|S)Nz%Cannot subscript already-subscripted cs|]}t|VqdSrrfrrdrdrerrz,_GenericAlias.__getitem__..cs|]}t|tVqdSrrarr~rdrdrerrzFExpected a list of types, an ellipsis, ParamSpec, or Concatenate. Got c3s|]}|VqdSrrd)rxsubstrdrer2r)rirrrjrarrranyrrrrdictrrrrrurhrrlrm collectionsabcr rrr)rrnew_argsrc subparamssubargsrdrqrers>        z_GenericAlias.__getitem__cCs |j|j||j|j|j|jdS)NrrSrr)r;rirrTrrrrrdrdrer;sz_GenericAlias.copy_withcCsB|jr d|j}nt|j}ddd|jD}|d|dS)Nr, cSg|]}t|qSrdr}rrdrdrerEz*_GenericAlias.__repr__..[])rr}rijoinr)rrrrdrdrer@s   z_GenericAlias.__repr__cCsb|jr t|j}n|j}t|j}t|dkr*t|dtr'|tur*|ds*|\}tj ||ffS)Nrr) rglobalsrirrrrrarrr)rrArrdrdrerHs z_GenericAlias.__reduce__cst|jtr td||jrt|S|jtur=t|vr!dS| |}||ddD]}t|t r<||ur<dSq.|jfS)Nrrdr) rarirkrjrr6rrrrWrQ)rrrZr[r:rdrerSs    z_GenericAlias.__mro_entries__)r{rxryrrrrrrrrrrrrr<rdrdr:rerhs $ rhcsdeZdZdddfdd ZeddZdd Zd d Zfd d ZddZ ddZ ddZ Z S)_SpecialGenericAliasTNrRcs`|dur|j}tj|||d||_|jdkr"d|jd|_dSd|jd|jd|_dS)NrRrvzA generic version of rg)r{r6rr]rxryr)rrAZnparamsrSrr:rdrerhs z_SpecialGenericAlias.__init__csBt|ts|f}dtfdd|D}t|||j||S)Nz*Parameters to generic types must be types.c3rrrrrrdrerwrz3_SpecialGenericAlias.__getitem__..)rarrrr]rr{rdrrerrs  z _SpecialGenericAlias.__getitem__cCst|j||j|jdS)N)rrS)rhrirrTr{rdrdrer{sz_SpecialGenericAlias.copy_withcCrrrrrdrdrerrz_SpecialGenericAlias.__repr__cs:t|tr t|j|jSt|tst||jSt|Sr)rarrXrirhr6rrr:rdrers    z&_SpecialGenericAlias.__subclasscheck__cCrrrrrdrdrerrz_SpecialGenericAlias.__reduce__cCrrrr*rdrdrerrz_SpecialGenericAlias.__or__cCrrrr,rdrdrerrz_SpecialGenericAlias.__ror__) r{rxryrrrrrrrrrr<rdrdr:rergs  rcs$eZdZfddZddZZS)_CallableGenericAliascsZ|j}t|dkrt|drtSdddd|ddDdt|dd S) Nrrztyping.Callable[[r|cSr}rdr~rrdrdrerrz2_CallableGenericAlias.__repr__..rz], r)rrrur6rrr}rrr:rdrers  z_CallableGenericAlias.__repr__cCsD|j}t|dkrt|dst|dd|df}tjt|ffS)Nrrr)rrrursrrr rrdrdrersz _CallableGenericAlias.__reduce__)r{rxryrrr<rdrdr:rers  rc@s(eZdZddZddZeddZdS) _CallableTypecCst|j||j|jttfddS)NTrz)rrirrTrrr{rdrdrers z_CallableType.copy_withcCsPt|tr t|dkrtd|\}}t|trt||f}n||f}||S)Nrz6Callable must be used as Callable[[arg, ...], result].)rarrrrjrs__getitem_inner__)rrrrVrdrdrers  z_CallableType.__getitem__cCsb|\}}d}t||}|tur|t|fSt|ts|f}tdd|D}||f}||S)Nz.Callable[args, result]: result must be a type.csrlrrm)rrcrdrdrerrz2_CallableType.__getitem_inner__..)rqEllipsisrrhrarr)rrrrVrordrdrers    z_CallableType.__getitem_inner__N)r{rxryrrrrrdrdrdrers rc@seZdZeddZdS) _TupleTypecs|dkr |tfSt|ts|f}t|dkr.|ddur.dt|d}||tfSdtfdd |D}||S) Nrdrr.z Tuple[t, ...]: t must be a type.rz*Tuple[t0, t1, ...]: each t must be a type.c3rrrrrrdrerrz)_TupleType.__getitem__..)rrirarrrrqrh)rrrrdrrers   z_TupleType.__getitem__N)r{rxryrrrdrdrdrersrcsPeZdZddZddZddZfddZd d Zd d Zfd dZ Z S)rcCst|Srrr{rdrdrerrdz_UnionGenericAlias.copy_withcCs(t|ttjfs tSt|jt|jkSr)rarrlrmrrrrrdrdrersz_UnionGenericAlias.__eq__cCstt|jSr)r frozensetrrrdrdrerrz_UnionGenericAlias.__hash__csd|j}t|dkr-|dtdurdt|ddS|dtdur-dt|ddStS)Nrrztyping.Optional[rr)rrr`r}r6rrr:rdrers  z_UnionGenericAlias.__repr__cCrarrbrrdrdrerrz$_UnionGenericAlias.__instancecheck__cCs |jD] }t||r dSqdS)NT)rrX)rrrcrdrdrers  z$_UnionGenericAlias.__subclasscheck__cst\}\}}|t|ffSr)r6rr)rrrArr:rdrers z_UnionGenericAlias.__reduce__) r{rxryrrrrrrrr<rdrdr:rers  rcCsdd|DS)Ncss|] }|t|fVqdSr)r`rrdrdrersz'_value_and_type_iter..rd)rrdrdrerrrc@seZdZddZddZdS)rcCs*t|tstStt|jtt|jkSr)rarrrrrrrdrdrers z_LiteralGenericAlias.__eq__cCsttt|jSr)rrrrrrdrdrerz_LiteralGenericAlias.__hash__N)r{rxryrrrdrdrdrers rceZdZfddZZS)rtcszt|dttfrg|dd|dRSt|dtr,g|dd|djR}n t|dts7tdt|S)Nrr) rarsrrrtrrrjr6rr{r:rdrer s z"_ConcatenateGenericAlias.copy_with)r{rxryrr<rdrdr:rertsrtcs4eZdZdZdZdZeddZfddZZ S)raCAbstract base class for generic types. A generic type is typically declared by inheriting from this class parameterized with one or more type variables. For example, a generic mapping type might be defined as:: class Mapping(Generic[KT, VT]): def __getitem__(self, key: KT) -> VT: ... # Etc. This class can then be used as follows:: def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT: try: return mapping[key] except KeyError: return default rdFcCst|ts|f}|s|turtd|jdtdd|D}|ttfvrLtdd|Ds8td|jdt t |t |krKtd|jdnt d d|j Dr\t ||}n t||t |j t||ttfd d S) NzParameter list to z[...] cannot be emptycsrlrrmrrdrdrer2rz,Generic.__class_getitem__..css|] }t|ttfVqdSr)rarrrrdrdrer5rzParameters to zF[...] must all be type variables or parameter specification variables.z[...] must all be uniquecsrnrror~rdrdrer>rTr)rarrrrjryrrallr{rrrsrrrrhrr)rrrdrdre__class_getitem__+s0       zGeneric.__class_getitem__c stj|i|g}d|jvrt|jv}n t|jvo|jdk}|r&tdd|jvrt|jt t f}d}|jD]}t |t rO|j turO|durLtd|j}q8|durt|}t||ksdfdd|D}ddd|D} td |d | d |}t||_dS) N__orig_bases__rz!Cannot inherit from plain Genericz0Cannot inherit from Generic[...] multiple types.r|c3s |] }|vrt|VqdSrrbr~Zgvarsetrdrerbz,Generic.__init_subclass__..csrlrr)rgrdrdrercrzSome type variables (z) are not listed in Generic[r)r6rrrr __bases__r{rjrrrrarhrirrrrr) rrrJrerrorZgvarsbaseZtvarsetZs_varsZs_argsr:rrerFs<        zGeneric.__init_subclass__) r{rxryrr _is_protocolrrrr<rdrdr:rers rc@eZdZdZdS)rizInternal placeholder for () or []. Used by TupleMeta and CallableMeta to allow empty list/tuple in specific places, without allowing them to sneak in where prohibited. Nr{rxryrrdrdrdrerijric@r)rhz(Internal placeholder for ... (ellipsis).Nrrdrdrdrerhqrrh)rrrUr_is_runtime_protocol) __abstractmethods____annotations__rrrrx__new__r__subclasshook__rr_MutableMapping__markercCsrt}|jddD],}|jdvrq t|di}t|jt|D]}|ds5|tvr5| |q%q |S)zCollect protocol members from a protocol class objects. This includes names actually defined in the class dictionary, as well as names that appear in annotations. Special names (above) are skipped. Nr)rrrZ_abc_) r__mro__r{rrsrkeysrMEXCLUDED_ATTRIBUTESadd)rZattrsr annotationsrOrdrdre_get_protocol_attrss   rcstfddtDS)Nc3s |] }tt|dVqdSr)rnrrerrdrerrz,_is_callable_members_only..)rrrrdrre_is_callable_members_onlysrcOstt|}|jr td|jturdS|jD]}|jdt}|tur'||_nqtj|_|j|g|Ri|dS)Nz Protocols cannot be instantiatedr) r`rrjr_no_init_or_replace_initrrrobject)rrrJrrZinitrdrdrers  rrr4c Cs4z t|djd|WSttfyYdSw)Nrr{)rr7r8rrr")depthdefaultrdrdre_callers rc Cs0z t|jddvWSttfyYdSw)zAllow instance and class checks for special stdlib modules. The abc and functools modules indiscriminately call isinstance() and issubclass() on the whole MRO of a user class, which may contain protocols. r{)rvrT)rr7r8rr"rrdrdre_allow_reckless_class_checkss r) r r)rrr+rr'rr-r0AbstractContextManagerAbstractAsyncContextManager)zcollections.abc contextlibcr) _ProtocolMetacstddrtddstddstdtddrtr'tjr'dSjr:tfdd tDr:dSt S) NrFrrrLInstance and class checks can only be used with @runtime_checkable protocolsTc3s:|]}t|ott|d pt|duVqdSr)hasattrrnrrerinstancerdrers   z2_ProtocolMeta.__instancecheck__..) rrrjrrXr;rrrr6rrr:rrers&     z_ProtocolMeta.__instancecheck__)r{rxryrr<rdrdr:rersrcs,eZdZdZdZdZdZfddZZS)raZBase class for protocol classes. Protocol classes are defined as:: class Proto(Protocol): def meth(self) -> int: ... Such classes are primarily used with static type checkers that recognize structural subtyping (static duck-typing), for example:: class C: def meth(self) -> int: return 0 def func(x: Proto) -> int: return x.meth() func(C()) # Passes static type check See PEP 544 for details. Protocol classes decorated with @typing.runtime_checkable act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures. Protocol classes can be generic, they are defined as:: class GenProto(Protocol[T]): def meth(self) -> T: ... rdTFcstj|i|jddstddjD_fdd}djvr)|_js.dSjD]#}|tt fvsT|j t vrF|j t |j vsTt |t rN|jsTtd|q1t_dS) NrFcss|]}|tuVqdSr)r)rr[rdrdrerrz-Protocol.__init_subclass__..csjdds tStddstrtStdts%tr!tStdt|ts.tdt D];}|j D]1}||jvrM|j|durKtSn t|di}t|t j j rh||vrht|trh|jrhnq7tSq2dS) NrFrrz._proto_hookrz7Protocols can only inherit from other protocols, got %r)r6rrrrsrrrrrrx_PROTO_ALLOWLISTr{rXrjrr)rrrJrrr:rrer s*  &    zProtocol.__init_subclass__) r{rxryrrrrrr<rdrdr:rers r) metaclasscsTeZdZdZfddZddZddZdd Zd d Zd d Z fddZ Z S)_AnnotatedAliasa7Runtime representation of an annotated type. At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't' with extra annotations. The alias behaves like a normal typing alias, instantiating is the same as instantiating the underlying type, binding it to types is also the same. cs2t|tr |j|}|j}t||||_dSr)rar __metadata__rir6r)rrAmetadatar:rdrerUs   z_AnnotatedAlias.__init__cCs|d}t||jS)Nr)rr)rrZnew_typerdrdrer\s z_AnnotatedAlias.copy_withcCs$dt|jddd|jDS)Nztyping.Annotated[{}, {}]r|csrlr)rwrrdrdrerdrz+_AnnotatedAlias.__repr__..)formatr}rirrrrdrdrerasz_AnnotatedAlias.__repr__cCstjt|jf|jffSr)rrrrirrrdrdrergsz_AnnotatedAlias.__reduce__cCrjr)rarrrirrrdrdrerlrkz_AnnotatedAlias.__eq__cCrr)rrirrrdrdrerrrz_AnnotatedAlias.__hash__cs|dvrdSt|S)N>r{ryr)r6rr\r:rdrerus z_AnnotatedAlias.__getattr__) r{rxryrrrrrrrrr<rdrdr:rerMs rc@s0eZdZdZdZddZeddZddZd S) raAdd context specific metadata to a type. Example: Annotated[int, runtime_check.Unsigned] indicates to the hypothetical runtime_check module that this type is an unsigned int. Every other consumer of this type can ignore this metadata and treat this type as int. The first argument to Annotated must be a valid type. Details: - It's an error to call `Annotated` with less than two arguments. - Nested Annotated are flattened:: Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3] - Instantiating an annotated type is equivalent to instantiating the underlying type:: Annotated[C, Ann1](5) == C(5) - Annotated can be used as a generic type alias:: Optimized = Annotated[T, runtime.Optimize()] Optimized[int] == Annotated[int, runtime.Optimize()] OptimizedList = Annotated[List[T], runtime.Optimize()] OptimizedList[int] == Annotated[List[int], runtime.Optimize()] rdcOrc)Nz&Type Annotated cannot be instantiated.rrrrJrdrdrerrdzAnnotated.__new__cCsNt|tr t|dkrtdd}t|d|dd}t|dd}t||S)NrzUAnnotated[...] should be used with at least two arguments (a type and an annotation).z$Annotated[t, ...]: t must be a type.rTr\r)rarrrrjrqr)rrrorArrdrdrers  zAnnotated.__class_getitem__cOstd|j)NzCannot subclass {}.Annotated)rjrrxrrdrdrers zAnnotated.__init_subclass__N) r{rxryrrrrrrrdrdrdrer{s  rcCs&t|tr|jstd|d|_|S)a9Mark a protocol class as a runtime protocol. Such protocol can be used with isinstance() and issubclass(). Raise TypeError if applied to a non-protocol class. This allows a simple-minded structural check very similar to one trick ponies in collections.abc such as Iterable. For example:: @runtime_checkable class Closable(Protocol): def close(self): ... assert isinstance(open('/some/file'), Closable) Warning: this will check only the presence of the required methods, not their type signatures! zB@runtime_checkable can be only applied to protocol classes, got %rT)rXrrrjrrrdrdrerWs rWcC|S)zCast a value to a type. This returns the value unchanged. To the type checker this signals that the return value has the designated type, but at runtime we intentionally don't check anything (we want this to be as fast as possible). rd)typr`rdrdrerJsrJc Csz|j}Wn tyiYSw|j}|j}|d|}|jp!d}|j}|r+t|ni}|t|}t||d|D]\}} | ||<q<|S)z:Internal helper to extract the default arguments, by name.Nrd) __code__r co_argcount co_varnames __defaults____kwdefaults__rtrr) rrZ pos_countZ arg_namesdefaultsZ kwdefaultsrYZ pos_offsetrvaluerdrdre _get_defaultss      rc Cs@t|ddriSt|tri}t|jD]d}|dur'ttj|jddi}n|}|j di}t|t j r8i}|durBt t |n|}|durQ|durQ||}}|D]"\} } | duratd} t| trmt| ddd} t| ||} | || <qUq|r}|Sdd |DS|durt|t jr|j }n|} t| d r| j} t| d st| d i}|dur|}n|dur|}t|dd}|durt|triStd |t|} t |}|D]7\} } | durtd} t| trt| t|t j dd} t| ||} | | vr | | dur t| } | || <q|r|Sd d |DS)aHReturn type hints for an object. This is often the same as obj.__annotations__, but it handles forward references encoded as string literals, adds Optional[t] if a default value equal to None is set and recursively replaces all 'Annotated[T, ...]' with 'T' (unless 'include_extras=True'). The argument may be a module, class, method, or function. The annotations are returned as a dictionary. For classes, annotations include also inherited members. TypeError is raised if the argument is not of a type that can contain annotations, and an empty dictionary is returned if no annotations are present. BEWARE -- the behavior of globalns and localns is counterintuitive (unless you are familiar with how eval() and exec() work). The search order is locals first, then globals. - If no dict arguments are passed, an attempt is made to use the globals from obj (or the respective module's globals for classes), and these are also used as the locals. If the object does not appear to have globals, an empty dictionary is used. For classes, the search order is globals first then locals. - If one dict argument is passed, it is used for both globals and locals. - If two dict arguments are passed, they specify globals and locals, respectively. __no_type_check__NrrFT)rpr_cSi|] \}}|t|qSrd_strip_annotationsrkrrdrdre +z"get_type_hints.. __wrapped__ __globals__z1{!r} is not a module, class, method, or function.cSrrdrrrdrdrerSr)rrar`reversedrrrrrxrrlGetSetDescriptorTypertvarsitemsrbrr ModuleTyperr_allowed_typesrjrrr) r|rrZinclude_extrasZhintsrZ base_globalsannZ base_localsrrZnsobjrrdrdrerNsv !               rNcCst|tr t|jSt|tr%tdd|jD}||jkr |S||St|trAtdd|jD}||jkr;|St|j|St|t j r_tdd|jD}||jkrX|St t j|S|S)z.Strips the annotations from a given type. csrlrrrrdrdrer\rz%_strip_annotations..csrlrrrrdrdrerarcsrlrrrrdrdrerfr)rarrrirhrrrrrrlrmrrrr)rZ stripped_argsrdrdrerVs$          rcCsHt|trtSt|ttttfr|jS|turtSt|t j r"t j SdS)a Get the unsubscripted version of a type. This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar and Annotated. Return None for unsupported types. Examples:: get_origin(Literal[42]) is Literal get_origin(int) is None get_origin(ClassVar[int]) is ClassVar get_origin(Generic) is Generic get_origin(Generic[T]) is Generic get_origin(Union[T, int]) is Union get_origin(List[Tuple[T, T]][int]) == list get_origin(P.args) is P N) rarrrQrrUrVrirrlrmtprdrdrerMns  rMcCst|tr |jf|jSt|ttfr7|j}|jtjj ur5t |dkr)t |ds5t |dd|df}|St|t jr@|jSdS)aGet type arguments with all substitutions performed. For unions, basic simplifications used by Union constructor are performed. Examples:: get_args(Dict[str, int]) == (str, int) get_args(int) == () get_args(Union[int, Union[T, int], str][int]) == (int, str) get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int]) get_args(Callable[[], T][int]) == ([], int) rrNrrd)rarrirrhrrrurvr rrursrlrm)rrYrdrdrerLs  rLcCs t|tS)zCheck if an annotation is a TypedDict class For example:: class Film(TypedDict): title: str year: int is_typeddict(Film) # => True is_typeddict(Union[list, str]) # => False )ra_TypedDictMetarrdrdrerOs rOcCst|tr:|j}|jD]\}}||j|fvr ||q|D]}t|tj r0d|_ t|tr9t |q%zd|_ W|St yJY|Sw)aIDecorator to indicate that annotations are not type hints. The argument must be a class or function; if it is a class, it applies recursively to all methods and classes defined in that class (but not to methods defined in its superclasses or subclasses). This mutates the function(s) or class(es) in place. T) rar`rcopyrrpopvaluesrlrzrrQrj)rcZ arg_attrsrOr`r|rdrdrerQs&      rQcstfdd}|S)zDecorator to give another decorator the @no_type_check effect. This wraps the decorator with something that wraps the decorated function in @no_type_check. cs|i|}t|}|Sr)rQ)rrrrrdrewrapped_decoratorsz2no_type_check_decorator..wrapped_decorator)rr)rrrdrrerRsrRcOrc)z*Helper for @overload to raise when called.zYou should not call an overloaded function. A series of @overload-decorated functions outside a stub module should always be followed by an implementation that is not @overload-ed.)NotImplementedErrorrrdrdre_overload_dummysrcCstS)a Decorator for overloaded functions/methods. In a stub file, place two or more stub definitions for the same function in a row, each decorated with @overload. For example: @overload def utf8(value: None) -> None: ... @overload def utf8(value: bytes) -> bytes: ... @overload def utf8(value: str) -> bytes: ... In a non-stub file (i.e. a regular .py file), do the same but follow it with an implementation. The implementation should *not* be decorated with @overload. For example: @overload def utf8(value: None) -> None: ... @overload def utf8(value: bytes) -> bytes: ... @overload def utf8(value: str) -> bytes: ... def utf8(value): # implementation goes here )r)rrdrdrerTsrTcCr)aVA decorator to indicate final methods and final classes. Use this decorator to indicate to type checkers that the decorated method cannot be overridden, and decorated class cannot be subclassed. For example: class Base: @final def done(self) -> None: ... class Sub(Base): def done(self) -> None: # Error reported by type checker ... @final class Leaf: ... class Other(Leaf): # Error reported by type checker ... There is no runtime checking of these properties. rd)frdrdrerKsrKTKTVTT_co)r(V_coVT_coT_contra)r)CT_co)r(r'rIraCallable type; Callable[[int], str] is a function of (int) -> str. The subscription syntax must always be used with exactly two values: the argument list and the return type. The argument list must be a list of types or ellipsis; the return type must be a single type. There is no syntax to indicate optional or keyword arguments, such function types are rarely used as callback types. rrrrrRa@Tuple type; Tuple[X, Y] is the cross-product type of X and Y. Example: Tuple[T1, T2] is a tuple of two elements corresponding to type variables T1 and T2. Tuple[int, float, str] is a tuple of an int, a float and a string. To specify a variable-length tuple of homogeneous type, use Tuple[T, ...]. r=r:r?r@rr/r;r<raA special construct usable to annotate class objects. For example, suppose we have the following classes:: class User: ... # Abstract base for User classes class BasicUser(User): ... class ProUser(User): ... class TeamUser(User): ... And a function that takes a class argument that's a subclass of User and returns an instance of the corresponding class:: U = TypeVar('U', bound=User) def new_user(user_class: Type[U]) -> U: user = user_class() # (Here we could write the user object to a database) return user joe = new_user(BasicUser) At this point the type checker knows that joe has type BasicUser. c@&eZdZdZdZedefddZdS)r6z(An ABC with one abstract method __int__.rdreturncCdSrrdrrdrdre__int__zSupportsInt.__int__N)r{rxryrrrintrrdrdrdrer6 r6c@r)r4z*An ABC with one abstract method __float__.rdrcCrrrdrrdrdre __float__rzSupportsFloat.__float__N)r{rxryrrrfloatrrdrdrdrer4rr4c@r)r3z,An ABC with one abstract method __complex__.rdrcCrrrdrrdrdre __complex__rzSupportsComplex.__complex__N)r{rxryrrrcomplexrrdrdrdrer3rr3c@r)r2z*An ABC with one abstract method __bytes__.rdrcCrrrdrrdrdre __bytes__rzSupportsBytes.__bytes__N)r{rxryrrrbytesrrdrdrdrer2rr2c@r)r5z*An ABC with one abstract method __index__.rdrcCrrrdrrdrdre __index__rzSupportsIndex.__index__N)r{rxryrrrrrrdrdrdrer5rr5c@r)r1zMAn ABC with one abstract method __abs__ that is covariant in its return type.rdrcCrrrdrrdrdre__abs__rzSupportsAbs.__abs__N)r{rxryrrrrrrdrdrdrer1rr1c@s,eZdZdZdZed dedefddZdS) r7zOAn ABC with one abstract method __round__ that is covariant in its return type.rdrndigitsrcCrrrd)rrrdrdre __round__rzSupportsRound.__round__Nr) r{rxryrrrrrrrdrdrdrer7s r7rdcCs@dd|D}dd|D}tj||||d}||_|j_|S)NcSsg|]\}}|qSrdrdrnrrdrdrerrz!_make_nmtuple..cSs$i|]\}}|t|d|dqS)zfield z annotation must be a typerrrdrdrersz!_make_nmtuple..rr^)ru namedtuplerr)rrlr^rfieldsnm_tplrdrdre _make_nmtuplesr> _makerr_field_defaults_replace_asdict_fieldsr__getnewargs__Z_source>rxrr{c@r)NamedTupleMetac sdi}g}|D]&}|vr||q |r0td|dt|dkr%dnddd|q t||fd d |Dd d }D]}|tvrRtd ||t vrc||j vrct |||qF|S)NrzNon-default namedtuple field z cannot follow default fieldrs r|csg|]}|qSrdrd)rrnsrdrerrz*NamedTupleMeta.__new__..rxrz&Cannot overwrite NamedTuple attribute ) rrrjrrrr _prohibitedr_specialr r_) rtypenamerrrlZ default_namesZ field_namerkeyrdrrers.     zNamedTupleMeta.__new__N)r{rxryrrdrdrdrers rc Ks`|dur |}n|rtdz tdjdd}Wn ttfy(d}Ynwt|||dS)aTyped version of namedtuple. Usage in Python versions >= 3.6:: class Employee(NamedTuple): name: str id: int This is equivalent to:: Employee = collections.namedtuple('Employee', ['name', 'id']) The resulting class has an extra __annotations__ attribute, giving a dict that maps field names to types. (The field names are also in the _fields attribute, which is part of the namedtuple API.) Alternative equivalent keyword syntax is also accepted:: Employee = NamedTuple('Employee', name=str, id=int) In Python versions <= 3.5 use:: Employee = NamedTuple('Employee', [('name', str), ('id', int)]) NzIEither list of fields or keywords can be provided to NamedTuple, not bothrr{r4r^) rrjrr7r8rrr"r)rrrJr^rdrdrerAs rAcCst|dkr tdtfS)Nrz5Multiple inheritance with NamedTuple is not supported)rrj _NamedTuplerrdrdre_namedtuple_mro_entries s rc@s&eZdZdddZeZddZeZdS)rTc s |D] }t|turtdqtt|tf|i}|di}t|}dfdd|D}t} t} |D] }| |j di| |j dd| |j ddq<| ||rj| |n| ||_ t | _ t | _td s|_S) a5Create new typed dict class object. This method is called when TypedDict is subclassed, or when TypedDict is instantiated. This way TypedDict supports all three syntax forms described in its docstring. Subclasses and instances of TypedDict return actual dictionaries. zHcannot inherit from both a TypedDict type and a non-TypedDict base classrz?TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a typecs"i|] \}}|t|jdqS)r)rqrx)rrrroZtp_dictrdrer4 sz*_TypedDictMeta.__new__..__required_keys__rd__optional_keys__ __total__)r`rrjrrtrrrrupdaterrrrrrr ) rrrrtotalrrZown_annotationsZown_annotation_keysZ required_keysZ optional_keysrdrrer" s8          z_TypedDictMeta.__new__cCrc)Nz4TypedDict does not support instance and class checksr)rrrdrdrerO rIz _TypedDictMeta.__subclasscheck__N)T)r{rxryrrtrrrrdrdrdrer! s  +rr"c Ksj|dur|}n|r tddt|i}ztdjdd|d<Wn ttfy,Ynwt|d||d S) aSA simple typed namespace. At runtime it is equivalent to a plain dict. TypedDict creates a dictionary type that expects all of its instances to have a certain set of keys, where each key is associated with a value of a consistent type. This expectation is not checked at runtime but is only enforced by type checkers. Usage:: class Point2D(TypedDict): x: int y: int label: str a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first') The type info can be accessed via the Point2D.__annotations__ dict, and the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets. TypedDict supports two additional equivalent forms:: Point2D = TypedDict('Point2D', x=int, y=int, label=str) Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) By default, all keys must be present in a TypedDict. It is possible to override this by specifying totality. Usage:: class point2D(TypedDict, total=False): x: int y: int This means that a point2D TypedDict can have any of the keys omitted.A type checker is only expected to support a literal False or True as the value of the total argument. True is the default, and makes all items defined in the class body be required. The class syntax is only supported in Python 3.6+, while two other syntax forms work for Python 2.7 and 3.2+ Nz@TypedDict takes either a dict or keyword arguments, but not bothrrr{r4rxrdr#) rjrtrr7r8rrr"r)rrr"rJrrdrdrerBV s* rBcCstfSr) _TypedDictrrdrdre sr%c@s@eZdZdZddZddZddZdd Zd d Zd d Z dS)rPa%NewType creates simple unique types with almost zero runtime overhead. NewType(name, tp) is considered a subtype of tp by static type checkers. At runtime, NewType(name, tp) returns a dummy callable that simply returns its argument. Usage:: UserId = NewType('UserId', int) def name_by_id(user_id: UserId) -> str: ... UserId('user') # Fails type check name_by_id(42) # Fails type check name_by_id(UserId(42)) # OK num = UserId(5) + 1 # type: int cCsD||_d|vr|dd}||_||_t}|dkr ||_dSdS)Nrgrr5)ry rpartitionr{Z __supertype__rrx)rrrr9rdrdrer s zNewType.__init__cCs|jd|jS)Nrg)rxryrrdrdrer rzNewType.__repr__cCrrrd)rrprdrdrer rzNewType.__call__cCrr)ryrrdrdrer rzNewType.__reduce__cCrrrrrdrdrer rzNewType.__or__cCrrrrrdrdrer rzNewType.__ror__N) r{rxryrrrrrrrrdrdrdrerP s  rPc@seZdZdZdZeedefddZeedefddZ ed8d d Z eede fd d Z ede fd dZed8ddZede fddZed9de defddZede fddZed9de defddZed9de deefddZed:d e d!e de fd"d#Zede fd$d%Zede fd&d'Zed;d(e de fd)d*Zede fd+d,Zed-ede fd.d/Zed0eeddfd1d2Zedrdrdre writelines rz IO.writelines IO[AnyStr]cCrrrdrrdrdre __enter__" rz IO.__enter__cCrrrd)rr`r tracebackrdrdre__exit__& rz IO.__exit__)rN)rrr)rr@) r{rxryrrrKrrbr'rr)r#r*rr+r,r-rIr.r/r1r=r3r6r7r8r:r;r=r?rArCrdrdrdrerE s\    rEc@s@eZdZdZdZedeeefde fddZ ed ddZ d S) rDz5Typed version of the return of open() in binary mode.rdrrcCrrrdr<rdrdrer=0 rzBinaryIO.writecCrrrdrrdrdrerA4 rzBinaryIO.__enter__N)rrD) r{rxryrrrrr bytearrayrr=rArdrdrdrerD+ srDc@seZdZdZdZeedefddZeede fddZ eede e fdd Z eede fd d Zeedefd d ZedddZdS)rHz3Typed version of the return of open() in text mode.rdrcCrrrdrrdrdrebuffer> r(z TextIO.buffercCrrrdrrdrdreencodingC r(zTextIO.encodingcCrrrdrrdrdreerrorsH r(z TextIO.errorscCrrrdrrdrdreline_bufferingM r(zTextIO.line_bufferingcCrrrdrrdrdrenewlinesR r(zTextIO.newlinescCrrrdrrdrdrerAW rzTextIO.__enter__N)rrH)r{rxryrrrKrrDrErbrFrrGr#rHr rIrArdrdrdrerH9 s(rHc@s$eZdZdZgdZeZeZeZdS)ioz)Wrapper namespace for IO generic classes.)rErHrDN)r{rxryr__all__rErHrDrdrdrdrerJ\ s rJz.ioc@s eZdZdZddgZeZeZdS)rez&Wrapper namespace for re type aliases.rGrFN)r{rxryrrKrGrFrdrdrdrerLk s rLz.rerr )rr4)r)NNF)rd)rrvrrruZcollections.abcrrrrLZ stdlib_rerrlrrrrrKrfrqrur}rrrrrrrrrrrrrkrr rSr r rrrrZr r[rr!rrUrVrrPrQrhrrrrrrrrtrrirhZ_TYPING_INTERNALSZ_SPECIAL_NAMESrrrrrrrrrrrrWrJrrzBuiltinFunctionType MethodTyperrrNrrMrLrOrQrRrrTrKrrrrrrrr`rrrbrIZ_aliasrr)r,r+r*rrr0r'rr-r r?rr%r!r#r&r$rrrrrsr=dequer:rr@r"r rr(rrrr/rtr; defaultdictr<r>r9r8rCr.rr6r4r3r2r5r1r7rrrrrArrrrrrBr$rPrXrYrErDrHrJr{rrGrFrdrdrdresg "     +     '  !   /@"ADMp+#"  V    b.5  i                   #59 .c#