eaiovnaovbqoebvqoeavibavo B  fv>@sdZddlZddlmZmZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl m Z mZmZddddd d d d d ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;dd?d@dAdBg>ZddDdEZdFdGZdHdIZdJdKZdLdMZdNdOZgZdPdQZdRdSZGdTdUdUZGdVdWdWZGdXdYdYeedCdZZedd[d\Zed?d]d\Zedd^d\Zedd_d\Z ed d`d\Z!GdaddedCdZZ"Gdbd d eedCdZZ#d3d d1d5d6d0d2d ddc Z$dddeZ%GdfdgdgedCdZZ&Gdhdidie&dCdZZ'Gdjd d Z(GdkdldlZ)GdmdndnZ*dod:Z+dpdqZ,e j-e j.e j/e j0e eefZ1ddrd;Z2dsd=Z3dtd>Z4dudvZ5dwd@Z6Gdxdydye7Z8Gdzd{d{e(e8d|Z9e#d}Z:e#d~Z;e#dZe#ddCdZ?e#ddCdZ@e#ddCe7dZAe#d9eBeCZDdddZEeEejjFdZFeEejjGe=ZGeEejjHe=e@e>fZHeEejjIe=ZIeEejjJe=ZJeEejjKe=ZKeEejjLe=ZLeEejjMe=ZMeEejjNdZNeEejjOe=ZOeEejjPe=ZPe'ejjQddCdZQdeQ_eEejjRe=ZSeEejjTe:ZTeEejjUe;e?fZUeEejjVe;efZreEejjse=e@fZseEe7eAddZtdet_Gdd,d,e9ZuGdd+d+e9ZvGdd*d*e9ZwGdd)d)e9ZxGdd(d(e9e=ZyGdd-d-e9e=ZzddZ{dZ|dZ}Gddde7Z~Gdd7d7e~d|Zdd<ZeCZdZGddde(eDZGdddeeBZGdddeeCZGdddZede_ee jej<eEe jeDZeEe jeDZGdddZ ede _e e je j<dS)a 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 * Two classes whose instances can be type arguments in addition to types: ForwardRef and TypeVar * 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 (the latter is currently private, but will be made public after PEP 544 acceptance). * 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 (may be added soon). * Wrapper submodules for re and io related types. N)abstractmethodabstractproperty)WrapperDescriptorTypeMethodWrapperTypeMethodDescriptorTypeAnyCallableClassVar ForwardRefGenericOptionalTupleTypeTypeVarUnion AbstractSet ByteString ContainerContextManagerHashable ItemsViewIterableIteratorKeysViewMapping MappingViewMutableMappingMutableSequence MutableSetSequenceSized ValuesView Awaitable AsyncIterator AsyncIterable Coroutine CollectionAsyncGeneratorAsyncContextManager Reversible SupportsAbs SupportsBytesSupportsComplex SupportsFloat SupportsInt SupportsRoundChainMapCounterDequeDict DefaultDictList OrderedDictSet FrozenSet NamedTuple GeneratorAnyStrcastget_type_hintsNewType no_type_checkno_type_check_decoratorNoReturnoverloadText TYPE_CHECKINGTcCsttf}|r|tf}|dkr&tdSt|tr8t|St|trZ|j|krZt |dt|t rp|t t fks||ttfkrt d|dt|tt tfr|St|st |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). Nz is not valid as type argumentzPlain z Got z.100.)r _Protocolr type isinstancestrr _GenericAlias __origin__ TypeError _SpecialFormrrArcallable)argmsg is_argumentZinvalid_generic_formsrR+/opt/alt/python37/lib64/python3.7/typing.py _type_checkqs$      rTcCsRt|tr,|jdkr|jS|jd|jS|dkr8dSt|tjrJ|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). builtinsrE.z...)rHrG __module__ __qualname__types FunctionType__name__repr)objrRrRrS _type_reprs   r]cs`gxR|D]J}t|tr*|kr*|t|tr |js fdd|jDq WtS)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) csg|]}|kr|qSrRrR).0t)tvarsrRrS sz&_collect_type_vars..)rHrappendrJ_specialextend__parameters__tuple)rXr_rR)r`rS_collect_type_varss  rgcCst|ts|St|j}x\t|jD]N\}}t|trbx:t|D]\}}||kr@||||<q@Wq$t|||||<q$W|jtkrtt |S| t |S)zjSubstitute type variables 'tvars' with substitutions 'subs'. These two must have the same length. ) rHrJlist__args__ enumerater _subs_tvarsrKrrf copy_with)tpr`ZsubsZnew_argsarOiZtvarrRrRrSrks     rkc Cs^|jst|dt|}t|j}||krZtd||kr>dndd|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 ZmanyZfewz parameters for z ; actual z , expected N)rerLlen)cls parametersZalenZelenrRrRrS_check_generics  rscCsg}xn|D]f}t|tr0|jtkr0||jq t|trft|dkrf|dtkrf||ddq ||q Wt |}t|t|krg}x(|D] }||kr||| |qW|}|rt |t|S)zyAn internal helper for Union creation and substitution: flatten Unions among parameters, then remove duplicates. rN) rHrJrKrrdrirfrprbsetremoveAssertionError)rrparamspZ all_paramsZ new_paramsr_rRrRrS_remove_dups_flattens" "   rzcs4ttjtfdd}|S)zInternal wrapper caching __getitem__ of generic types with a fallback to original function for non-hashable arguments. cs*y ||Stk rYnX||S)N)rL)argskwds)cachedfuncrRrSinners  z_tp_cache..inner) functools lru_cache _cleanupsrb cache_clearwraps)r~rrR)r}r~rS _tp_caches  rcsbt|tr|St|tr^tfdd|jD}||jkrH|S||}|j|_|S|S)zEvaluate all forward reverences in the given type t. For use of globalns and localns see the docstring for get_type_hints(). c3s|]}t|VqdS)N) _eval_type)r^rn)globalnslocalnsrRrS sz_eval_type..)rHr _evaluaterJrfrirlrc)r_rrZev_argsresrR)rrrSrs     rc@seZdZdZdZddZdS)_FinalzMixin to prohibit subclassing) __weakref__cOsd|krtddS)N_rootz&Cannot subclass special typing classes)rL)selfr{r|rRrRrS__init_subclass__sz_Final.__init_subclass__N)rZrVrW__doc__ __slots__rrRrRrRrSrsrc@s eZdZdZddZddZdS) _Immutablez3Mixin to indicate that object should not be copied.cCs|S)NrR)rrRrRrS__copy__sz_Immutable.__copy__cCs|S)NrR)rZmemorRrRrS __deepcopy__!sz_Immutable.__deepcopy__N)rZrVrWrrrrRrRrRrSrsrcspeZdZdZdZfddZddZddZd d Zd d Z d dZ ddZ ddZ ddZ eddZZS)rMzhInternal indicator of special typing constructs. See _doc instance attribute for specific docs. )_name_doccsBt|dkr6t|dtr6t|dtr6td|t|S)zConstructor. This only exists to give a better error message in case someone tries to subclass a special typing object (not a good idea). rrtzCannot subclass )rprHrIrfrLsuper__new__)rqr{r|) __class__rRrSr,s  z_SpecialForm.__new__cCs||_||_dS)N)rr)rnamedocrRrRrS__init__9sz_SpecialForm.__init__cCst|tstS|j|jkS)N)rHrMNotImplementedr)rotherrRrRrS__eq__=s z_SpecialForm.__eq__cCs t|jfS)N)hashr)rrRrRrS__hash__Bsz_SpecialForm.__hash__cCs d|jS)Nztyping.)r)rrRrRrS__repr__Esz_SpecialForm.__repr__cCs|jS)N)r)rrRrRrS __reduce__Hsz_SpecialForm.__reduce__cOstd|dS)NzCannot instantiate )rL)rr{r|rRrRrS__call__Ksz_SpecialForm.__call__cCst|ddS)Nz! cannot be used with isinstance())rL)rr\rRrRrS__instancecheck__Nsz_SpecialForm.__instancecheck__cCst|ddS)Nz! cannot be used with issubclass())rL)rrqrRrRrS__subclasscheck__Qsz_SpecialForm.__subclasscheck__cs|jdkr t|d}t||fS|jdkr|dkr:tdt|tsJ|f}dtfdd|D}t|}t|d kr|d St||S|jd krt|d }t|t dfSt|d dS)Nr z"ClassVar accepts only single type.rrRz Cannot take a Union of no types.z)Union[arg, ...]: each arg must be a type.c3s|]}t|VqdS)N)rT)r^ry)rPrRrSr_sz+_SpecialForm.__getitem__..rtrr z#Optional[t] requires a single type.z is not subscriptable) rrTrJrLrHrfrzrprrG)rrritemrOrR)rPrS __getitem__Ts$         z_SpecialForm.__getitem__)rZrVrWrrrrrrrrrrrrr __classcell__rRrR)rrSrM%s rM)ra`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. )raSpecial 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. 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(). 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]. zEOptional type. Optional[X] is equivalent to Union[X, None]. c@s>eZdZdZdZdddZddZdd Zd d Zd d Z dS)r z-Internal wrapper to hold a forward reference.)__forward_arg____forward_code____forward_evaluated____forward_value____forward_is_argument__TcCsnt|tstd|yt|dd}Wn"tk rJtd|YnX||_||_d|_d|_||_ dS)Nz*Forward reference must be a string -- got zevalz/Forward reference must be an expression -- got F) rHrIrLcompile SyntaxErrorrrrrr)rrOrQcoderRrRrSrs zForwardRef.__init__cCsj|jr||k rd|dkr(|dkr(i}}n|dkr6|}n |dkrB|}tt|j||d|jd|_d|_|jS)Nz*Forward references must evaluate to types.)rQT)rrTrrrr)rrrrRrRrSrs   zForwardRef._evaluatecCs>t|tstS|jr2|jr2|j|jko0|j|jkS|j|jkS)N)rHr rrrr)rrrRrRrSrs     zForwardRef.__eq__cCs t|jS)N)rr)rrRrRrSrszForwardRef.__hash__cCsd|jdS)Nz ForwardRef())r)rrRrRrSrszForwardRef.__repr__N)T) rZrVrWrrrrrrrrRrRrRrSr s c@s6eZdZdZdZddddddZdd Zd d ZdS) 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. )rZ __bound____constraints__ __covariant____contravariant__NF)bound covariant contravariantc s||_|r|rtdt||_t||_|r>|dk r>td|rVt|dkrVtddtfdd|D|_|rt |d|_ nd|_ yt dj d d }Wnttfk rd}YnX|d kr||_dS) Nz"Bivariant types are not supported.z-Constraints cannot be combined with bound=...rtz"A single constraint is not allowedz:TypeVar(name, constraint, ...): constraints must be types.c3s|]}t|VqdS)N)rT)r^r_)rPrRrSr#sz#TypeVar.__init__..zBound must be a type.rZ__main__typing)rZ ValueErrorboolrrrLrprfrrTrsys _getframe f_globalsgetAttributeErrorrV)rrrrrZ constraintsZdef_modrR)rPrSrs(    zTypeVar.__init__cCs&|jr d}n|jrd}nd}||jS)N+-~)rrrZ)rprefixrRrRrSr/s zTypeVar.__repr__cCs|jS)N)rZ)rrRrRrSr8szTypeVar.__reduce__)rZrVrWrrrrrrRrRrRrSrs * ) rhrfdictru frozensetdeque defaultdictrGr7cCs|do|dS)N__) startswithendswith)attrrRrRrS _is_dunderSsrcseZdZdZddddddZedd Zd d Zd d ZddZ ddZ ddZ ddZ ddZ fddZddZddZddZZS) rJaThe 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. TFN)instspecialrcCsz||_||_|r*|dkr*|j}t||}||_t|ts@|f}||_tdd|D|_ t ||_ d|_ |sv|j |_ dS)Ncss*|]"}|tkrdn|tkrdn|VqdS).rRN)_TypingEllipsis _TypingEmpty)r^rnrRrRrSrjsz)_GenericAlias.__init__..)_instrcrZ_normalize_aliasrrrHrfrKrirgrerrV)roriginrxrrrZ orig_namerRrRrSr`s     z_GenericAlias.__init__cs^|jttfkrtd|t|ts,|f}dtfdd|D}t||t||j|S)Nz%Cannot subscript already-subscripted z*Parameters to generic types must be types.c3s|]}t|VqdS)N)rT)r^ry)rPrRrSrzsz,_GenericAlias.__getitem__..) rKr rFrLrHrfrsrkre)rrxrR)rPrSrrs  z_GenericAlias.__getitem__cCst|j||j|jdS)N)rr)rJrKrr)rrxrRrRrSrl~sz_GenericAlias.copy_withcCs|jdks&t|jdkrx|jdtkrx|jr8d|j}n t|j}|jshdddd|jDd }nd }||S|jrd Sd dd d|jddDdt|jdd S)Nrrztyping.[z, cSsg|] }t|qSrR)r])r^rnrRrRrSrasz*_GenericAlias.__repr__..]ztyping.Callableztyping.Callable[[cSsg|] }t|qSrR)r])r^rnrRrRrSrasz], )rrpriEllipsisr]rKrcjoin)rrr{rRrRrSrs     z_GenericAlias.__repr__cCsRt|tstS|j|jkrdS|jtkrF|jtkrFt|jt|jkS|j|jkS)NF)rHrJrrKrrri)rrrRrRrSrs  z_GenericAlias.__eq__cCs,|jtkrttt|jfSt|j|jfS)N)rKrrrri)rrRrRrSrs z_GenericAlias.__hash__cOsT|js$td|jd|jd|j||}y ||_Wntk rNYnX|S)NzType z cannot be instantiated; use z () instead)rrLrlowerrKZ__orig_class__r)rr{kwargsresultrRrRrSrs  z_GenericAlias.__call__cCs|jrZg}|j|kr ||j||}tdd||ddDsR|tt|S|jtkr||}x.||ddD]}t|tr||k rdSqW|jfS)Ncss"|]}t|tpt|tVqdS)N)rHrJ issubclassr )r^brRrRrSrsz0_GenericAlias.__mro_entries__..rtrR) rrKrbindexanyr rfrHrJ)rbasesrrorrRrRrS__mro_entries__s      z_GenericAlias.__mro_entries__cCs*d|jkrt|st|j|St|dS)NrK)__dict__rgetattrrKr)rrrRrRrS __getattr__s z_GenericAlias.__getattr__cs2t|s|dkr t||nt|j||dS)N)rrrc)rr __setattr__setattrrK)rrval)rrRrSrsz_GenericAlias.__setattr__cCs|t|S)N)rrG)rr\rRrRrSrsz_GenericAlias.__instancecheck__cCs<|jr0t|tst||jS|jr0t|j|jStddS)NzBSubscripted generics cannot be used with class and instance checks)rcrHrJrrKrL)rrqrRrRrSrs   z_GenericAlias.__subclasscheck__cCs|jr |jS|jr t|j}n|j}|tkrht|jdkrJ|jdtksht|jdd|jdf}n*t |j}t|dkrt |dt s|\}t j ||ffS)Nrrrrt) rcrglobalsrKrrprirrhrfrHoperatorgetitem)rrr{rRrRrSrs z_GenericAlias.__reduce__)rZrVrWrrrrrlrrrrrrrrrrrrRrR)rrSrJWs     rJcs,eZdZdZddZefddZZS)_VariadicGenericAliaszSame as _GenericAlias above but for variadic aliases. Currently, this is used only by special internal aliases: Tuple and Callable. cCs|jdks|js||St|tr0t|dkr8td|\}}|tkrRt|f}n$t|tsjtd|t||f}||S)Nrrz6Callable must be used as Callable[[arg, ...], result].z1Callable[args, result]: args must be a list. Got ) rrc__getitem_inner__rHrfrprLrrh)rrxr{rrRrRrSrs    z!_VariadicGenericAlias.__getitem__cs |jtkr|jr|dkr$|tfSt|ts4|f}t|dkrl|ddkrldt|d}||tfSdtfdd |D}||S|jt j j kr|jr|\}}d t|}|t kr|t|fSd tfd d |D}||f}||St |S) NrRrrt.z Tuple[t, ...]: t must be a type.rz*Tuple[t0, t1, ...]: each t must be a type.c3s|]}t|VqdS)N)rT)r^ry)rPrRrSr sz:_VariadicGenericAlias.__getitem_inner__..z.Callable[args, result]: result must be a type.z6Callable[[arg, ...], result]: each arg must be a type.c3s|]}t|VqdS)N)rT)r^rO)rPrRrSrs)rKrfrcrlrrHrprTr collectionsabcrrrr)rrxryr{r)r)rPrSrs.      z'_VariadicGenericAlias.__getitem_inner__)rZrVrWrrrrrrRrR)rrSrsrcs<eZdZdZdZfddZeddZfddZZ S) r aCAbstract 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 rRcsP|tkrtdtjtjkr8|jtjk r8t|}ntj|f||}|S)NzHType Generic cannot be instantiated; it can be used only as a base class)r rLrrobjectr)rqr{r|r\)rrRrSr.s zGeneric.__new__cst|ts|f}|s.|tk r.td|jddtfdd|D}|tkrtdd|Dsjtdtt|t|krtdn|t krn t ||t ||S) NzParameter list to z[...] cannot be emptyz*Parameters to generic types must be types.c3s|]}t|VqdS)N)rT)r^ry)rPrRrSr@sz,Generic.__class_getitem__..css|]}t|tVqdS)N)rHr)r^ryrRrRrSrCsz5Parameters to Generic[...] must all be type variablesz-Parameters to Generic[...] must all be unique) rHrfr rLrWr allrprurFrsrJ)rqrxrR)rPrS__class_getitem__8s$   zGeneric.__class_getitem__c stj||g}d|jkr(t|jk}nt|jko:|jdk}|rHtdd|jkr t|j}d}x8|jD].}t |t rj|j tkrj|dk rtd|j }qjW|dkr|}n`t |}t ||ksdfdd|D}ddd|D} td |d | d |}t||_ dS) N__orig_bases__rFz!Cannot inherit from plain Genericz0Cannot inherit from Generic[...] multiple types.z, c3s|]}|krt|VqdS)N)rI)r^r_)gvarsetrRrSrosz,Generic.__init_subclass__..css|]}t|VqdS)N)rI)r^grRrRrSrpszSome type variables (z) are not listed in Generic[r)rrrr r __bases__rZrLrgrHrJrKrerurrf) rqr{rr`errorZgvarsbaseZtvarsetZs_varsZs_args)r)rrSrQs6         zGeneric.__init_subclass__) rZrVrWrrrrrrrrRrR)rrSr s  c@seZdZdZdS)rzInternal placeholder for () or []. Used by TupleMeta and CallableMeta to allow empty list/tuple in specific places, without allowing them to sneak in where prohibited. N)rZrVrWrrRrRrRrSrwsrc@seZdZdZdS)rz(Internal placeholder for ... (ellipsis).N)rZrVrWrrRrRrRrSr~srcCs|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). rR)typrrRrRrSr<sc Csy |j}Wntk riSX|j}|j}|d|}|jp@d}|j}|rTt|ni}|t|}x2t||d|D]\}} ||kst | ||<qxW|S)z:Internal helper to extract the default arguments, by name.NrR) __code__r co_argcount co_varnames __defaults____kwdefaults__rrpziprw) r~rZ pos_countZ arg_namesdefaultsZ kwdefaultsrZ pos_offsetrvaluerRrRrS _get_defaultss      r c Cst|ddriSt|tri}xt|jD]~}|dkrFtj|jj}n|}|j di}xN| D]B\}}|dkrztd}t|t rt |dd}t |||}|||<qbWq*W|S|dkrt|tjr|j}n&|} xt| dr| j} qWt| di}|dkr|}n|dkr|}t|dd}|dkrFt|tr8iStd|t|} t|}xp| D]d\}}|dkrztd}t|t rt |}t |||}|| kr| |dkrt|}|||<q`W|S) aReturn type hints for an object. This is often the same as obj.__annotations__, but it handles forward references encoded as string literals, and if necessary adds Optional[t] if a default value equal to None is set. 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. - 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__N__annotations__F)rQ __wrapped__ __globals__z1{!r} is not a module, class, method, or function.)rrHrGreversed__mro__rmodulesrVrritemsrIr rrX ModuleTypehasattrr _allowed_typesrLformatr rr ) r\rrZhintsrZ base_globalsannrrZnsobjrrRrRrSr=s\                  cCst|tr||j}x0|jD]"\}}||j|fkr ||q Wx4|D](}t|tj rfd|_ t|trPt |qPWy d|_ Wnt k rYnX|S)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) rHrGrcopyrrpopvaluesrXrYr r?rL)rOZ arg_attrsrrr\rRrRrSr?s      cstfdd}|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||}t|}|S)N)r?)r{r|r~) decoratorrRrSwrapped_decorators z2no_type_check_decorator..wrapped_decorator)rr)rrrR)rrSr@scOs tddS)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.N)NotImplementedError)r{r|rRrRrS_overload_dummy&srcCstS)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)r~rRrRrSrB/scs0eZdZdZfddZddZddZZS) _ProtocolMetaz~Internal metaclass for _Protocol. This exists so _Protocol classes can be generic without deriving from Generic. cs"t|jkrt|StddS)Nz+Protocols cannot be used with isinstance().)rFrrrrL)rr\)rrRrSrSs  z_ProtocolMeta.__instancecheck__csL|js tS|tkrdS|}x(|D] tfdd|jDs$dSq$WdS)NTc3s|]}|jkVqdS)N)r)r^d)rrRrSresz2_ProtocolMeta.__subclasscheck__..F) _is_protocolrrF_get_protocol_attrsrr)rrqattrsrR)rrSrXs z_ProtocolMeta.__subclasscheck__cCs&g}x.|jD]$}t|ddr |jdkr ||q Wt}x|D]}x|jD]}x|jD]$}||k r^||jkr^t|dds^Pq^W|dsR|dkrR|dkrR|dkrR|dkrR|dkrR|d krR|d krR|d krR|d krR|d krR|dkrR|dkrR|dkrR|dkrR|dkrR|dkrR||qRWqBW|S)Nr FrFZ_abc___abstractmethods__r rZ_gorgrrirr!Z__next_in_mro__rerKrZ __extra__Z __tree_hash__rV) rrrZrbrurkeysradd)rZprotocol_basescr"rrrRrRrSr!is<     z!_ProtocolMeta._get_protocol_attrs)rZrVrWrrrr!rrRrR)rrSrLs rcs(eZdZdZdZdZfddZZS)rFzInternal base class for protocol classes. This implements a simple-minded structural issubclass check (similar but more general than the one-offs in collections.abc such as Hashable). rRTcs t|S)N)rr)rqrx)rrRrSrsz_Protocol.__class_getitem__)rZrVrWrrr rrrRrR)rrSrFsrF) metaclassTKTVTT_co)rV_coVT_coT_contra)rCT_co)rrcCst||d|dS)NT)rr)rJ)rrxrrRrRrS_aliassr0rR)raCallable 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. F)rra@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, ...]. )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@s&eZdZdZdZeedddZdS)r.z(An ABC with one abstract method __int__.rR)returncCsdS)NrR)rrRrRrS__int__ szSupportsInt.__int__N)rZrVrWrrrintr2rRrRrRrSr.sc@s&eZdZdZdZeedddZdS)r-z*An ABC with one abstract method __float__.rR)r1cCsdS)NrR)rrRrRrS __float__szSupportsFloat.__float__N)rZrVrWrrrfloatr4rRrRrRrSr-sc@s&eZdZdZdZeedddZdS)r,z,An ABC with one abstract method __complex__.rR)r1cCsdS)NrR)rrRrRrS __complex__szSupportsComplex.__complex__N)rZrVrWrrrcomplexr6rRrRrRrSr,sc@s&eZdZdZdZeedddZdS)r+z*An ABC with one abstract method __bytes__.rR)r1cCsdS)NrR)rrRrRrS __bytes__'szSupportsBytes.__bytes__N)rZrVrWrrrbytesr8rRrRrRrSr+#sc@s&eZdZdZdZeedddZdS)r*zMAn ABC with one abstract method __abs__ that is covariant in its return type.rR)r1cCsdS)NrR)rrRrRrS__abs__0szSupportsAbs.__abs__N)rZrVrWrrrr+r:rRrRrRrSr*,sc@s*eZdZdZdZedeedddZdS) r/zOAn ABC with one abstract method __round__ that is covariant in its return type.rRr)ndigitsr1cCsdS)NrR)rr;rRrRrS __round__9szSupportsRound.__round__N)r) rZrVrWrrrr3r+r<rRrRrRrSr/5sc svdfdd|D}t|dd|D}t||_|_ytdjdd|_ Wnt t fk rpYnX|S)NzDNamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a typecsg|]\}}|t|fqSrR)rT)r^nr_)rPrRrSra@sz!_make_nmtuple..cSsg|] \}}|qSrRrR)r^r=r_rRrRrSraAsrrZr) r namedtupler6r  _field_typesrrrrrVrr)rrXnm_tplrR)rPrS _make_nmtuple>srA) rrr__getnewargs___fields_field_defaultsr?_make_replace_asdictZ_source)rVrZr cseZdZfddZZS)NamedTupleMetac s|ddrt||||S|di}t||}g}i}xP|D]H}||krn||} || | ||<qF|rFtdj|d| dqFWt ||j_ t ||j_||_xD|D]<} | tkrtd| q| tkr| |jkrt|| || qW|S)NrFr zXNon-default namedtuple field {field_name} cannot follow default field(s) {default_names}z, ) field_nameZ default_namesz&Cannot overwrite NamedTuple attribute )rrrrArrbrLrrr$rr6r rfrrD _prohibitedrrcrCr) rqtypenamernsrXr@rZ defaults_dictrIZ default_valuekey)rrRrSrVs0       zNamedTupleMeta.__new__)rZrVrWrrrRrR)rrSrHTsrHc@s"eZdZdZdZddZde_dS)r9a4Typed 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 extra __annotations__ and _field_types attributes, giving an ordered dict mapping field names to types. __annotations__ should be preferred, while _field_types is kept to maintain pre PEP 526 compatibility. (The field names are 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)]) TcOs|s td|^}}|r"|^}}nd|kr6|d}ntd|r~y |\}Wqtk rztdt|dddYqXn$d|krt|dkr|d}nd}|dkr|}n |rtd t||S) Nz*NamedTuple.__new__(): not enough argumentsrKzGNamedTuple.__new__() missing 1 required positional argument: 'typename'z@NamedTuple.__new__() takes from 2 to 3 positional arguments but rz were givenfieldsrtzIEither list of fields or keywords can be provided to NamedTuple, not both)rLrrrprrA)r{rrqrKrNrRrRrSrs,      zNamedTuple.__new__z*($cls, typename, fields=None, /, **kwargs)N)rZrVrWrrr__text_signature__rRrRrRrSr9sscCsdd}||_||_|S)a%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 function 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 cSs|S)NrR)xrRrRrSnew_typeszNewType..new_type)rZZ __supertype__)rrmrQrRrRrSr>sc@seZdZdZdZeedddZeedddZe ddd d Z ee dd d Z e e dd dZe ddddZe e dddZe d7e edddZe e dddZe d8e edddZe d9e eedddZe d:e e e d d!d"Ze e dd#d$Ze e dd%d&Ze d;e e d'd(d)Ze e dd*d+Ze ee d,d-d.Ze eedd/d0d1Ze d2dd3d4Ze ddd5d6ZdS)<IOaGeneric base class for TextIO and BinaryIO. This is an abstract, generic version of the return of open(). NOTE: This does not distinguish between the different possible classes (text vs. binary, read vs. write vs. read/write, append-only, unbuffered). The TextIO and BinaryIO subclasses below capture the distinctions between text vs. binary, which is pervasive in the interface; however we currently do not offer a way to track the other distinctions in the type system. rR)r1cCsdS)NrR)rrRrRrSmodeszIO.modecCsdS)NrR)rrRrRrSrszIO.nameNcCsdS)NrR)rrRrRrScloseszIO.closecCsdS)NrR)rrRrRrSclosedsz IO.closedcCsdS)NrR)rrRrRrSfilenosz IO.filenocCsdS)NrR)rrRrRrSflushszIO.flushcCsdS)NrR)rrRrRrSisattysz IO.isattyr)r=r1cCsdS)NrR)rr=rRrRrSreadszIO.readcCsdS)NrR)rrRrRrSreadablesz IO.readable)limitr1cCsdS)NrR)rr[rRrRrSreadlinesz IO.readline)hintr1cCsdS)NrR)rr]rRrRrS readlines sz IO.readlinesr)offsetwhencer1cCsdS)NrR)rr_r`rRrRrSseek szIO.seekcCsdS)NrR)rrRrRrSseekablesz IO.seekablecCsdS)NrR)rrRrRrStellszIO.tell)sizer1cCsdS)NrR)rrdrRrRrStruncatesz IO.truncatecCsdS)NrR)rrRrRrSwritablesz IO.writable)sr1cCsdS)NrR)rrgrRrRrSwrite!szIO.write)linesr1cCsdS)NrR)rrirRrRrS writelines%sz IO.writelinesz IO[AnyStr]cCsdS)NrR)rrRrRrS __enter__)sz IO.__enter__cCsdS)NrR)rrGr tracebackrRrRrS__exit__-sz IO.__exit__)r)r)r)r)N) rZrVrWrrrrIrSrrrTrrUr3rVrWrXr;rYrZr\r5r^rarbrcrerfrhrjrkrmrRrRrRrSrRsT rRc@sBeZdZdZdZeeeefe dddZ eddddZ d S) BinaryIOz5Typed version of the return of open() in binary mode.rR)rgr1cCsdS)NrR)rrgrRrRrSrh7szBinaryIO.write)r1cCsdS)NrR)rrRrRrSrk;szBinaryIO.__enter__N) rZrVrWrrrrr9 bytearrayr3rhrkrRrRrRrSrn2s rnc@seZdZdZdZeedddZeedddZ ee eddd Z ee dd d Z eedd d ZeddddZdS)TextIOz3Typed version of the return of open() in text mode.rR)r1cCsdS)NrR)rrRrRrSbufferEsz TextIO.buffercCsdS)NrR)rrRrRrSencodingIszTextIO.encodingcCsdS)NrR)rrRrRrSerrorsMsz TextIO.errorscCsdS)NrR)rrRrRrSline_bufferingQszTextIO.line_bufferingcCsdS)NrR)rrRrRrSnewlinesUszTextIO.newlinescCsdS)NrR)rrRrRrSrkYszTextIO.__enter__N)rZrVrWrrrrnrqrIrrr rsrrtrrurrkrRrRrRrSrp@srpc@s&eZdZdZdddgZeZeZeZdS)ioz)Wrapper namespace for IO generic classes.rRrprnN)rZrVrWr__all__rRrprnrRrRrRrSrv^s  rvz.ioc@s eZdZdZddgZeZeZdS)rez&Wrapper namespace for re type aliases.PatternMatchN)rZrVrWrrwryrzrRrRrRrSrxmsrxz.re)T)NN)T)rrrrrZcollections.abc contextlibrrrxZ stdlib_rerrXrrrrwrTr]rgrkrsrzrrrrrrMrrAr rr r rrrrJrr rrr<r rYBuiltinFunctionType MethodTyperrr=r?r@rrBrGrrFr(r)r*r+r,r-r.r/r9rIr;r0rr"r%r$r#rrr)r rr&rr7rrrrrrrrfr rhr5rr2rurr8rrrr!AbstractContextManagerrAbstractAsyncContextManagerr(rr3rr4r6r1r0r:r'rr.r-r,r+r*r/rArJrcrHr9r>rCrDrRrnrprvrZrryrzrRrRrRrSs !   E  2a/_   V D                  <`