Yf9D@sKddlZddlmZmZddlZddlZddlZddlZddlZddl Z yddl jZ Wne k rddlZ YnXej ddddfkrddlZy ddl mZmZmZWnBe k r-eejZeejZeejZYnXddd d d d d ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:g4Zd;d<Zd=d>ZGd?d@d@eZGdAdBdBdCedDdEZGdFdGdGedDdEZGdHdIdIedDdEZGdJdKdKedDdEZdLdMZ dNdOZ!dPdQZ"dRdSZ#dTdUZ$GdVdWdWedDdEZ%e%dDdEZ&GdXdYdYedDdEZ'e'dDdEZ(GdZddedDdEZ)e)d[Z*e)d\Z+e)d]Z,e)d^d_dEZ-e)d`d_dEZ.e)dad_dEZ/e)dbdcdEZ0e)d2e1eZ2dddeZ3dddfdgZ4dhdiZ5djdkZ6gZ7dldmZ8GdndodoedDdEZ9e9dDdEZ:GdpdqdqedDdEZ;e;dDdEZ<drdsZ=dtduZ>dvdwZ?dxdyZ@dzd{ZAGd|ddeejBZCdZDd}d~ZEGdd d dCeCZDGdddZFGdddZGGdddeCZHGdd d eIdeIdCeHZJGdddeCZKGdddde jLdCeKZLGdddedDdEZMeMdDdEZNdd3ZOddZPe jQe jRe jSe jTeeefZUdddd4ZVdd6ZWdd7ZXddZYdd8ZZGdddeCZ[GddddCe[Z\e j]Z]e^e drwGdddeDe-de j_Z_ej`de^e drGddde_e.eDe-e0e.fde jaZaej`de^e dr5GdddeDe-de jbZbGdddebe-de jcZcej`dej`dGdddeDe-de jdZdGdddede-de jeZeGdd'd'e\ZfGdd&d&e\ZgGdd%d%e\ZhGdd$d$e\ZiGdd#d#e\e-ZjGdd(d(e\e-Zke^e d"r<Gdd"d"ede-de jlZlnGdd"d"e\e-Zle jmZmGdddeDe-de jnZne^e drGdddemede-ene-de joZoej`de^e dr Gdddeoe-de jpZqn-Gdddemede-ene-de jpZqGdddeqe*de jrZre^e dr Gdddeoe+eDe+e/fde jsZsn:Gdddemede+ene+eDe+e/fde jsZsGdddese+e,fde jtZte^e d"rp e^e dr@ Gdddele-eoe-de juZun-Gdddemele-ene-de juZun-Gdddemede-ene-de juZuGdddeue*de jvZvGdddeuewde jxZxGdd-d-eyeve*deyZzGdd*d*ej{eve*dej{Z|Gdd.d.e}ere*de}ZpGdd/d/e~eqe-de~ZGdddemede-de jZGdddee+eqe+de jZGdddeeJe+e/feqeJe+e/feDe+e/fde jZGdd!d!ee/de jZe^edrh GdddeDe-dejZnGdddeDe-Ze^edr GdddeDe-dejZej`dn)ej ddddfkr edGdd+d+eete+e,fdeZGdd,d,ejete+e,fdejZGdd)d)ejee*ewfdejZe^edr ej`dGdddejete+e,fdejZe^e d1r e jZn e jZGdd1d1eee-eDe-e0e.fdeZe^e dr_Gdddece-eDe-e0fde jZej`de)dd_dEdeZGdd d eDedeZddZej ddddfkZdddddddddddf ZddddfZGdddeZGdd0d0dCeZdd5ZeZdZGdddeDe2ZGdddee1ZGdddeeZGdddZede_eejejevalz1Forward reference must be an expression -- got %rF) rTr^rkrlrPcompile SyntaxErrorrsrtrurv)r[argcode)rZrCrDr^s    z_ForwardRef.__init__cCs|j s||k r|dkr;|dkr;i}}n'|dkrP|}n|dkrb|}tt|j||d|_d|_|jS)Nz*Forward references must evaluate to types.T)ru _type_checkrwrtrv)r[r_r`rCrCrDras      z_ForwardRef._eval_typecCs5t|tstS|j|jko4|j|jkS)N)rkrGNotImplementedrsrv)r[otherrCrCrD__eq__sz_ForwardRef.__eq__cCst|j|jfS)N)hashrsrv)r[rCrCrD__hash__sz_ForwardRef.__hash__cCstddS)Nz4Forward references cannot be used with isinstance().)rP)r[objrCrCrD__instancecheck__sz_ForwardRef.__instancecheck__cCstddS)Nz4Forward references cannot be used with issubclass().)rP)r[rVrCrCrD__subclasscheck__sz_ForwardRef.__subclasscheck__cCsd|jfS)Nz_ForwardRef(%r))rs)r[rCrCrDrf sz_ForwardRef.__repr__)rsrtrurv) rArdr@rgrpr^rarrrrrfrCrC)rZrDrGs      rGc@speZdZdZdZddZdd Zd d Zd d ZddZ ddZ ddZ dS)rFa:Internal helper class for defining generic variants of concrete types. Note that this is not a type; let's call it a pseudo-type. It cannot be used in instance and subclass checks in parameterized form, i.e. ``isinstance(42, Match[str])`` raises ``TypeError`` instead of returning ``False``. rWtype_var impl_type type_checkercCst|ts!tt|t|tsBtt|t|t sdtt|t|ttfstt|||_||_||_ ||_ dS)atInitializer. Args: name: The name, e.g. 'Pattern'. type_var: The type parameter, e.g. AnyStr, or the specific type, e.g. str. impl_type: The implementation type. type_checker: Function that takes an impl_type instance. and returns a value that should be a type_var instance. N) rkrlAssertionErrorreprrnrNrHrWrrr)r[rWrrrrCrCrDr^s !!"'   z_TypeAlias.__init__cCsd|jt|jfS)Nz%s[%s])rWrSr)r[rCrCrDrf,sz_TypeAlias.__repr__cCst|jts"td||jjrkt|trkt||jjsktd||jft|tr||jk rtd||j|j||j |j S)Nz#%s cannot be further parameterized.z&%s is not a valid substitution for %s.z%s cannot be re-parameterized.) rkrrrP__constraints__rn issubclassrZrWrr)r[Z parameterrCrCrD __getitem__/sz_TypeAlias.__getitem__cCs5t|tstS|j|jko4|j|jkS)N)rkrFr}rWr)r[r~rCrCrDr;sz_TypeAlias.__eq__cCst|j|jfS)N)rrWr)r[rCrCrDr@sz_TypeAlias.__hash__cCs.t|jtstdt||jS)Nz NoReturn: raise Exception('no way') This type is invalid in other positions, e.g., ``List[NoReturn]`` will fail in static type checkers. cCstddS)Nz*NoReturn cannot be used with isinstance().)rP)r[rrCrCrDrsz_NoReturn.__instancecheck__cCstddS)Nz*NoReturn cannot be used with issubclass().)rP)r[rVrCrCrDrsz_NoReturn.__subclasscheck__N)rArdr@rgrprrrCrCrCrDrs  rc speZdZdZdZddd d d d fd d ZddZddZddZddZ S)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 do 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) rA __bound__r __covariant____contravariant__boundN covariantF contravariantc stj||d|d|d|||_|rF|rFtdt||_t||_|r|dk rtd|rt|dkrtddt fd d |D|_ |rt |d |_ n d|_ dS) Nrrrz"Bivariant types are not supported.z-Constraints cannot be combined with bound=...rKz"A single constraint is not allowedz:TypeVar(name, constraint, ...): constraints must be types.c3s|]}t|VqdS)N)r|).0r)rrCrD sz#TypeVar.__init__..zBound must be a type.) rTr^rA ValueErrorboolrrrPrjrmrr|r)r[rWrrrZ constraints)rZ)rrDr^s       "zTypeVar.__init__cCs||kr|j|dS)N)append)r[rbrCrCrDrcs zTypeVar._get_type_varscCs5|jrd}n|jr$d}nd}||jS)N+-~)rrrA)r[prefixrCrCrDrf s     zTypeVar.__repr__cCstddS)Nz0Type variables cannot be used with isinstance().)rP)r[instancerCrCrDrszTypeVar.__instancecheck__cCstddS)Nz0Type variables cannot be used with issubclass().)rP)r[rVrCrCrDrszTypeVar.__subclasscheck__)rArrrr) rArdr@rgrpr^rcrfrrrCrC)rZrDrs (   TKTVTT_corV_coVT_coT_contrarcCs|dkrg}t|drFt|ttfrF|j||St|trx.t|D] \}}||krb||SqbW|S)zAn internal helper function: replace arg if it is a type variable found in tvars with corresponding substitution from args or with corresponding substitution sub-tree if arg is a generic type. N _subs_tree)hasattrrkrrHrr enumerate)rzrbr\iZtvarrCrCrD _replace_arg)s $  rc Cs|jdkr|S|j}g}x)|jdk rM|j||j}q%Wg}x*|jD]}|jt|||q^WxJ|D]B}g}x-|jD]"}|jt||j|qW|}qW|S)aAn internal helper function: calculate substitution tree for generic cls after replacing its type parameters with substitutions in tvars -> args (if any). Repeat the same following __origin__'s. Return a list of arguments with all possible substitutions performed. Arguments that are generic classes themselves are represented as tuples (so that no new classes are created by this function). For example: _subs_tree(List[Tuple[int, T]][str]) == [(Tuple, int, str)] N)rr__args__r__parameters__) rVrbr\ZcurrentZ orig_chain tree_argsrzZoclsZ new_tree_argsrCrCrDrDs       rcsg}x|D]}t|trD|jtkrD|j|jq t|trt|dkr|dtkr|j|ddq |j|q Wt |tt|krg}x4|D],}|kr|j|j |qW|} st t |xS|D]Ktt sEq-t fddhDr-j q-Wtfdd|DS)zAn internal helper for Union creation and substitution: flatten Union's among parameters, then remove duplicates and strict subclasses. rrKNc3sK|]A}t|to$|jdk st|toBt|VqdS)N)rkrrrnr)rZt2)t1rCrDrsz'_remove_dups_flatten..c3s!|]}|kr|VqdS)NrC)rr) all_paramsrCrDrs)rkrrrextendrrmrjrsetremoverrnany) parametersparamspZ new_paramsrrC)rrrD_remove_dups_flattenes0 1      rcCs~|jstdt|t|}t|j}||krztd||kr^dndt|||fdS)Nz%s is not a generic classz0Too %s parameters for %s; actual %s, expected %sZmanyZfew)rrPrrj)rVrZalenZelenrCrCrD_check_generics   rcsJtjtjjtjfdd}|S)zInternal wrapper caching __getitem__ of generic types with a fallback to original function for non-hashable arguments. c s3y||SWntk r%YnX||S)N)rP)r\r])cachedfuncrCrDinners  z_tp_cache..inner) functools lru_cache _cleanupsr cache_clearwraps)rrrC)rrrD _tp_caches$rcseZdZdZdZddddfd d Zd d Zd dZfddZfddZ e ddZ ddddZ ddZ ddZddZddZS) raUnion 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] - When two arguments have a subclass relationship, the least derived argument is kept, e.g.:: class Employee: pass class Manager(Employee): pass Union[int, Employee, Manager] == Union[int, Employee] Union[Manager, int, Employee] == Union[int, Employee] Union[Employee, Manager] == Employee - Similar for object:: Union[int, object] == object - You cannot subclass or instantiate a union. - You can use Optional[X] as a shorthand for Union[X, None]. rrr __tree_hash__NrOFcstj||||d|}|dkrad|_d|_d|_ttd|_|St|t s|t d|t krt |}t |dkr|dSt||_||_||_|j}t|t rtt||_nt||_|S)NrOrzExpected parameters=rKr)r)rTrUrrrr frozensetrrkrmrPrrrjrr)rVroriginrOr\r[Z subs_tree)rZrCrDrUs*!          z_Union.__new__cs|jdkr|Stfdd|jD}t|j}||jkro||jkro|S|j||ddS)Nc3s!|]}t|VqdS)N)ra)rr)r_r`rCrDrsz$_Union._eval_type..rOT)rrmrarrZ)r[r_r`ev_args ev_originrC)r_r`rDras%z_Union._eval_typecCs&|jr"|jr"t|j|dS)N)rrrc)r[rbrCrCrDrcsz_Union._get_type_varscsR|jdkrtjS|j}t|tsAt|S|dj|S)Nr)rrTrfrrkrmr _tree_repr)r[tree)rZrCrDrfs    z_Union.__repr__cs~g}xW|ddD]E}t|tsB|jt|q|j|dj|qWtjddj|S)NrKrz[%s]z, )rkrmrrSrrTrfrQ)r[rarg_listrz)rZrCrDr s z_Union._tree_reprcs|fkrtdt|ts0|f}|jdkrHdndtfdd|D}|tk rt|||j|d|ddS) Nz Cannot take a Union of no types.z)Union[arg, ...]: each arg must be a type.z*Parameters to generic types must be types.c3s|]}t|VqdS)N)r|)rr)rrCrDr sz%_Union.__getitem__..rrOT)rPrkrmrrrrZ)r[rrC)rrDrs      z_Union.__getitem__cCsS|tkrtSt|||}t|}t|dkrH|dStf|S)NrKr)rrrrj)r[rbr\rrCrCrDr%s  z_Union._subs_treecCsIt|tr|j|jkS|tk r;|j|kS||kSdS)N)rkrrrr)r[r~rCrCrDr.s  z _Union.__eq__cCs|jS)N)r)r[rCrCrDr6sz_Union.__hash__cCstddS)Nz(Unions cannot be used with isinstance().)rP)r[rrCrCrDr9sz_Union.__instancecheck__cCstddS)Nz(Unions cannot be used with issubclass().)rP)r[rVrCrCrDr<sz_Union.__subclasscheck__)rrrr)rArdr@rgrprUrarcrfrrrrrrrrrCrC)rZrDrs *     rc@s.eZdZdZfZeddZdS)rzEOptional type. Optional[X] is equivalent to Union[X, None]. cCs#t|d}t|tdfS)Nz#Optional[t] requires a single type.)r|rrn)r[rzrCrCrDrKsz_Optional.__getitem__N)rArdr@rgrprrrCrCrCrDrCs rcCs8t|tstx|jdk r3|j}qW|S)z@Return the farthest origin of a generic class (internal helper).N)rkrrr)arCrCrDrTs rcCs:t|trt|ts$tt|t|kS)a6Return whether two generic classes are equivalent (internal helper). The intention is to consider generic class X and any of its parameterized forms (X[T], X[int], etc.) as equivalent. However, X is not equivalent to a subclass of X. The relation is reflexive, symmetric and transitive. )rkrrr)rbrCrCrD_geqv\s $rcCsft}xYt|jddD]>\}}t|tr t|tkr |j|d}q W|S)zHelper for Generic.__new__. Returns the class after the last occurrence of Generic or Generic[...] in cls.__mro__. NrK)objectr__mro__rkrrr )rVZ next_in_mrorcrCrCrD _next_in_mroks &!rcs@tjtjr*fdd}nfdd}|S)zConstruct a __subclasshook__ callable that incorporates the associated __extra__ class in subclass checks performed against cls. cs{jj|}|tk r"|Sj|jkr8dSx<jjD]+}t|tr`qHt||rHdSqHWtS)NT) __extra____subclasshook__r}r__subclasses__rkrr)subclassresscls)rVrCrD __extrahook__s z)_make_subclasshook..__extrahook__cs#jrt|jrdStS)NT)rrr})r)rVrCrDrs)rkrabcABCMeta)rVrrC)rVrD_make_subclasshookysrcCsAt|}d|kr=x"|dD]}|j|dq#W|S)zInternal helper: copy class __dict__ and clean slots class variables. (They will be re-created if necessary by normal class machinery.) rpN)dictpop)ZdctZ dict_copyZslotrCrCrD_no_slots_copys   rcs9eZdZdZdddddfddZeddZejddZedd Zejd d Zd d Z d dZ fddZ fddZ ddddZ ddZddZeddZfddZddZdd Zfd!d"ZS)#racMetaclass for generic types. This is a metaclass for typing.Generic and generic ABCs defined in typing module. User defined subclasses of GenericMeta can override __new__ and invoke super().__new__. Note that GenericMeta.__new__ has strict rules on what is allowed in its bases argument: * plain Generic is disallowed in bases; * Generic[...] should appear in bases at most once; * if Generic[...] is present, then it should list all type variables that appear in other bases. In addition, type of all generic bases is erased, e.g., C[int] is stripped to plain C. Nc s|dk rF|dk sttdd|Dst|nI|dks^t||dksvt||dkst|t|}d} xe|D]]} | tkrtdt| tr| jtkr| dk rtd| j} qW| dkr|} nrt |} t | | kstddj fdd|Ddj d d| Df| }|} |dk rt |t j kr||kr|f|}td d|D}td d|Drtd d|D}|jd |d|itj||||dd} || _|r|tdd|Dnd| _t| | _|dkr| | _d|kr|st| jdddkrt| | _t|t j r|j| _|j| _n$|dk r6|j| _|j| _|rWt|drW|j| _|rot| jntt| j | _!| S)zCreate a new generic class. GenericMeta.__new__ accepts keyword arguments that are used for internal bookkeeping, therefore an override should pass unused keyword arguments to super(). Ncss|]}t|tVqdS)N)rkr)rrrCrCrDrsz&GenericMeta.__new__..z!Cannot inherit from plain Genericz0Cannot inherit from Generic[...] multiple types.z6Some type variables (%s) are not listed in Generic[%s]z, c3s'|]}|krt|VqdS)N)rl)rr)gvarsetrCrDrscss|]}t|VqdS)N)rl)rgrCrCrDrscss0|]&}t|tr$t|n|VqdS)N)rkrr)rrrCrCrDrscss*|] }t|to!|tk VqdS)N)rkrr )rrrCrCrDrscss!|]}|tk r|VqdS)N)r )rrrCrCrDrsrrrOTcss9|]/}|tkrdn|tkr-fn|VqdS).N)_TypingEllipsis _TypingEmpty)rrrCrCrDrsrrArr@)"rallrr rPrkrrrrrQrnrrrmrupdaterTrUrr__next_in_mro____orig_bases__rrr _abc_registry _abc_cacherr@rrrr)rVrWrXrYrbr\rextra orig_basesZgvarsbaseZtvarsetZ initial_basesr[)rZ)rrDrUsl (            #- ! (       zGenericMeta.__new__cCs,t|jtjr|jjSt|jS)N)rkrrr_abc_negative_cacher_abc_generic_negative_cache)r[rCrCrDrs zGenericMeta._abc_negative_cachecCs@|jdkr<t|jtjr3||j_n ||_dS)N)rrkrrrrr)r[valuerCrCrDrscCs,t|jtjr|jjSt|jS)N)rkrrr_abc_negative_cache_versionr#_abc_generic_negative_cache_version)r[rCrCrDrs z'GenericMeta._abc_negative_cache_versioncCs@|jdkr<t|jtjr3||j_n ||_dS)N)rrkrrrrr)r[rrCrCrDr$scCs&|jr"|jr"t|j|dS)N)rrrc)r[rbrCrCrDrc,szGenericMeta._get_type_varscs|jr|jjnd}|jrRtfdd|jDnd}||jkrz||jkrz|S|j|j|jt|jd|rt |ndd|d|d|j d|j S)Nc3s!|]}t|VqdS)N)ra)rr)r_r`rCrDr3sz)GenericMeta._eval_type..rbr\rrr) rrarrmrZrA __bases__r__dict__rrr)r[r_r`rrrC)r_r`rDra0s$4  zGenericMeta._eval_typecs/|jdkrtjS|j|jS)N)rrTrfrr)r[)rZrCrDrf@s zGenericMeta.__repr__csg}xs|ddD]a}|fkr9|jdqt|ts^|jt|q|j|dj|qWtjddj|S)NrKz()rz[%s]z, )rrkrmrSrrTrfrQ)r[rrrz)rZrCrDrEs zGenericMeta._tree_reprcCs<|jdkr|St|||}t|ft|S)N)rrrrm)r[rbr\rrCrCrDrPszGenericMeta._subs_treecCsKt|tstS|jdks1|jdkr;||kS|j|jkS)N)rkrr}rr)r[r~rCrCrDrVs  zGenericMeta.__eq__cCs|jS)N)r)r[rCrCrDr]szGenericMeta.__hash__cst|ts|f}| rGt|tk rGtdt|dtfdd|D}|tkrtdd|Dstdtt |t|krtd|}|}n|tt fkrt |}|}nh|t kr|}|}nM|j tt fkrFtdt|nt||t |}|}|j dkr}|fnf}|j|j||jt|jd |d |d |d |jd |jS)Nz)Parameter list to %s[...] cannot be emptyz*Parameters to generic types must be types.c3s|]}t|VqdS)N)r|)rr)rrCrDrhsz*GenericMeta.__getitem__..css|]}t|tVqdS)N)rkr)rrrCrCrDrksz5Parameters to Generic[...] must all be type variablesz-Parameters to Generic[...] must all be uniquez'Cannot subscript already-subscripted %srbr\rrr)rkrmrrrPrEr rrjrr rrrrrrZrArrrrr)r[rrbr\ZprependrC)rrDr`sJ              zGenericMeta.__getitem__csg|jdk r;tjdjddkr7tddS|tkrWtd|tj|S) NrKrArrzCParameterized generics cannot be used with class or instance checksFz5Class %r cannot be used with class or instance checks)rr)rr> _getframe f_globalsrPr rTr)r[rV)rZrCrDrs   zGenericMeta.__subclasscheck__cCst|j|S)N)rrZ)r[rrCrCrDrszGenericMeta.__instancecheck__c Cs@|j|j|jt|j|j|j|j|j|j S)N) rZrArrrrrrrr)r[rCrCrD__copy__s zGenericMeta.__copy__csl|jdr|jds-|jdrItt|j||nttt|j||dS)N___abc_)rLendswithrTr __setattr__r)r[attrr)rZrCrDrszGenericMeta.__setattr__)rArdr@rgrUpropertyrsetterrrcrarfrrrrrrrrrrrCrC)rZrDrs$ !^     .  c Osq|jdkr|j|St|}|j|}y ||_Wntk rXYnX|j|||SdS)N)rrUrZ__orig_class__AttributeErrorr^)Zbase_clsrVr\r]rrrCrCrD _generic_news    r c@s(eZdZdZfZddZdS)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 cOs1t|trtdt|j|||S)NzHType Generic cannot be instantiated; it can be used only as a base class)rr rPr r)rVr\r]rCrCrDrUs zGeneric.__new__N)rArdr@rgrprUrCrCrCrDr 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)rArdr@rgrCrCrCrDrs rc@seZdZdZdS)rz(Internal placeholder for ... (ellipsis).N)rArdr@rgrCrCrCrDrs rcsFeZdZdZefddZddZddZS) TupleMetazMetaclass for Tuple (internal).cs|jdk st|t r/tj|S|fkrNtjtfSt|tsf|f}t|dkr|ddkrdt |d}tj|t fSdtfdd|D}tj|S) NrrK.z Tuple[t, ...]: t must be a type.rz*Tuple[t0, t1, ...]: each t must be a type.c3s|]}t|VqdS)N)r|)rr)rrCrDrsz(TupleMeta.__getitem__..) rrrrTrrrkrmrjr|r)r[rr)rZ)rrDrs  "zTupleMeta.__getitem__cCs,|jdkrt|tStddS)Nz5Parameterized Tuple cannot be used with isinstance().)rrkrmrP)r[rrCrCrDrs zTupleMeta.__instancecheck__cCs,|jdkrt|tStddS)Nz5Parameterized Tuple cannot be used with issubclass().)rrrmrP)r[rVrCrCrDr s zTupleMeta.__subclasscheck__)rArdr@rgrrrrrCrC)rZrDrs  rc@s(eZdZdZfZddZdS)ra@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, ...]. cOs.t|trtdtt|||S)Nz6Type Tuple cannot be instantiated; use tuple() instead)rrrPr rm)rVr\r]rCrCrDrUs z Tuple.__new__N)rArdr@rgrprUrCrCrCrDrs rcsdeZdZdZfddZfddZfddZefdd ZS) CallableMetaz"Metaclass for Callable (internal).cs/|jdkrtjS|j|jS)N)rrTrfrr)r[)rZrCrDrf's zCallableMeta.__repr__cst|tk r"tj|Sg}xW|ddD]E}t|tsd|jt|q9|j|dj|q9W|ddkrt|dd|dSt|dddj |dd|dfS) NrKrz...z [..., %s]z [[%s], %s]z, rr) rr rTrrkrmrrSrrQ)r[rrrz)rZrCrDr,s zCallableMeta._tree_reprcs|jdk st|t r/tj|St|t sQt|dkr]td|\}}|t krt |f}n4t|t std|ft||f}|j |S)zxA thin wrapper around __getitem_inner__ to provide the latter with hashable arguments to improve speed. Nrz6Callable must be used as Callable[[arg, ...], result].z8Callable[args, result]: args must be a list. Got %.100r.) rrr rTrrkrmrjrPEllipsislist__getitem_inner__)r[rr\result)rZrCrDr<s"    zCallableMeta.__getitem__cs|\}}dt|}|tkrCtjt|fSdtfdd|D}||f}tj|S)Nz.Callable[args, result]: result must be a type.z6Callable[[arg, ...], result]: each arg must be a type.c3s|]}t|VqdS)N)r|)rrz)rrCrDrXsz1CallableMeta.__getitem_inner__..)r|rrTrrrm)r[rr\r)rZ)rrDrPs   zCallableMeta.__getitem_inner__) rArdr@rgrfrrrrrCrC)rZrDr$s rc@s(eZdZdZfZddZdS)r aCallable 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. cOs1t|trtdt|j|||S)NzIType Callable cannot be instantiated; use a non-abstract subclass instead)rr rPr r)rVr\r]rCrCrDrUjs zCallable.__new__N)rArdr@rgrprUrCrCrCrDr ]s csmeZdZdZdZdddZddZdd Zfd d Zd d Z ddZ S)ra3Special 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(). __type__NcKs ||_dS)N)r)r[tpr]rCrCrDr^sz_ClassVar.__init__cCspt|}|jdkrJ|t|dj|jddddStdj|jdddS)Nz{} accepts only single type.rKrOTz {} cannot be further subscripted)rnrr|formatrArP)r[itemrVrCrCrDrs   z_ClassVar.__getitem__cCs>t|j||}||jkr(|St||ddS)NrOT)rarrn)r[r_r`Znew_tprCrCrDrasz_ClassVar._eval_typecs>tj}|jdk r:|djt|j7}|S)Nz[{}])rTrfrrrS)r[r)rZrCrDrfsz_ClassVar.__repr__cCstt|j|jfS)N)rrnrAr)r[rCrCrDrsz_ClassVar.__hash__cCs<t|tstS|jdk r2|j|jkS||kS)N)rkrr}r)r[r~rCrCrDrs z_ClassVar.__eq__)r) rArdr@rgrpr^rrarfrrrCrC)rZrDrqs   rcCs|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). rC)typvalrCrCrDr6sc Csy |j}Wntk r%iSYnX|j}|j}|d|}|jpTf}|j}|rrt|ni}|t|}xCt||d|D](\}} ||kst | ||.wrapped_decorator)rr)r,r-rC)r,rDr:1s!cOstddS)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]rCrCrD_overload_dummyAsr/cCstS)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/)rrCrCrDr;Jscs@eZdZdZfddZddZddZS) _ProtocolMetaz~Internal metaclass for _Protocol. This exists so _Protocol classes can be generic without deriving from Generic. cs/t|jkrtj|StddS)Nz+Protocols cannot be used with isinstance().)rrrTrrP)r[r)rZrCrDrnsz_ProtocolMeta.__instancecheck__csd|js tS|tkrdS|j}x4|D],tfdd|jDs0dSq0WdS)NTc3s|]}|jkVqdS)N)r)rd)r rCrDrsz2_ProtocolMeta.__subclasscheck__..F)rhr}r_get_protocol_attrsrr)r[rVattrsrC)r rDrss    "z_ProtocolMeta.__subclasscheck__cCsg}x?|jD]4}t|ddr|jdkr|j|qWt}x<|D]4}x+|jjD]}x|jD]5}||k r~||jkr~t|dd r~Pq~W|jd rn|dkrn|dkrn|dkrn|dkrn|dkrn|d krn|d krn|d krn|d krn|d krn|dkrn|dkrn|dkrn|dkrn|dkrn|j|qnWqXW|S)NrhFrr__abstractmethods__r%rirrrpr2rrrrrrrd) rrrArrrkeysrLadd)r[Zprotocol_basesrr3rr rCrCrDr2s:!                 z!_ProtocolMeta._get_protocol_attrs)rArdr@rgrrr2rCrC)rZrDr0gs  r0c@s"eZdZdZfZdZdS)rzInternal 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). TN)rArdr@rgrprhrCrCrCrDrs r Awaitablec@seZdZfZdS)r7N)rArdr@rprCrCrCrDr7s  Coroutinec@seZdZfZdS)r8N)rArdr@rprCrCrCrDr8s  AsyncIterablec@seZdZfZdS)r9N)rArdr@rprCrCrCrDr9s c@seZdZfZdS) AsyncIteratorN)rArdr@rprCrCrCrDr:s r:c@seZdZfZdS)rN)rArdr@rprCrCrCrDrs c@seZdZfZdS)rN)rArdr@rprCrCrCrDrs c@s1eZdZfZeedddZdS)r*)returncCsdS)NrC)r[rCrCrD__int__szSupportsInt.__int__N)rArdr@rprintr<rCrCrCrDr*s c@s1eZdZfZeedddZdS)r))r;cCsdS)NrC)r[rCrCrD __float__szSupportsFloat.__float__N)rArdr@rprfloatr>rCrCrCrDr)s c@s1eZdZfZeedddZdS)r()r;cCsdS)NrC)r[rCrCrD __complex__szSupportsComplex.__complex__N)rArdr@rprcomplexr@rCrCrCrDr(s c@s1eZdZfZeedddZdS)r')r;cCsdS)NrC)r[rCrCrD __bytes__szSupportsBytes.__bytes__N)rArdr@rprbytesrBrCrCrCrDr's c@s1eZdZfZeedddZdS)r&)r;cCsdS)NrC)r[rCrCrD__abs__szSupportsAbs.__abs__N)rArdr@rprrrDrCrCrCrDr&s c@s7eZdZfZedeedddZdS)r+r)ndigitsr;cCsdS)NrC)r[rErCrCrD __round__ szSupportsRound.__round__N)rArdr@rprr=rrFrCrCrCrDr+ s c@seZdZfZdS)r%N)rArdr@rprCrCrCrDr%s c@s1eZdZfZeddddZdS)r%zIterator[T_co])r;cCsdS)NrC)r[rCrCrD __reversed__szReversible.__reversed__N)rArdr@rprrGrCrCrCrDr%s c@seZdZfZdS)rN)rArdr@rprCrCrCrDr s  Collectionc@seZdZfZdS)rHN)rArdr@rprCrCrCrDrH%s c@seZdZfZdS)rN)rArdr@rprCrCrCrDr/s c@seZdZfZdS)rN)rArdr@rprCrCrCrDr3s c@seZdZfZdS)r!N)rArdr@rprCrCrCrDr!8s c@seZdZfZdS)rN)rArdr@rprCrCrCrDr>s c@seZdZfZdS)rN)rArdr@rprCrCrCrDrBs c@seZdZfZdS)rN)rArdr@rprCrCrCrDrGs c@seZdZfZdS)r"N)rArdr@rprCrCrCrDr"Ms c@seZdZfZdS)r"N)rArdr@rprCrCrCrDr"Qs c@seZdZfZdS)r"N)rArdr@rprCrCrCrDr"Us c@seZdZfZdS)r N)rArdr@rprCrCrCrDr Zs c@seZdZfZdS)rN)rArdr@rprCrCrCrDr^s c@s"eZdZfZddZdS)r0cOs.t|trtdtt|||S)Nz4Type List cannot be instantiated; use list() instead)rr0rPr r)rVr\r]rCrCrDrUfs z List.__new__N)rArdr@rprUrCrCrCrDr0bs c@s"eZdZfZddZdS)r-cOs5t|trtj||Sttj|||S)N)rr- collectionsdequer )rVr\r]rCrCrDrUqsz Deque.__new__N)rArdr@rprUrCrCrCrDr-ms c@s"eZdZfZddZdS)r1cOs.t|trtdtt|||S)Nz2Type Set cannot be instantiated; use set() instead)rr1rPr r)rVr\r]rCrCrDrU{s z Set.__new__N)rArdr@rprUrCrCrCrDr1ws c@s"eZdZfZddZdS)r2cOs.t|trtdtt|||S)Nz>Type FrozenSet cannot be instantiated; use frozenset() instead)rr2rPr r)rVr\r]rCrCrDrUs zFrozenSet.__new__N)rArdr@rprUrCrCrCrDr2s c@seZdZfZdS)rN)rArdr@rprCrCrCrDrs c@seZdZfZdS)rN)rArdr@rprCrCrCrDrs c@seZdZfZdS)rN)rArdr@rprCrCrCrDrs c@seZdZfZdS)r$N)rArdr@rprCrCrCrDr$s AbstractContextManagerc@seZdZfZdS)rN)rArdr@rprCrCrCrDrs c@sIeZdZfZddZejddZeddZ dS)rcCs|S)NrC)r[rCrCrD __enter__szContextManager.__enter__cCsdS)NrC)r[exc_type exc_value tracebackrCrCrD__exit__szContextManager.__exit__cCsL|tkrHtdd|jDrHtdd|jDrHdStS)Ncss|]}d|jkVqdS)rLN)r)rBrCrCrDrsz2ContextManager.__subclasshook__..css|]}d|jkVqdS)rPN)r)rrQrCrCrDrsT)rrrr})rVCrCrCrDrs  zContextManager.__subclasshook__N) rArdr@rprLrrrP classmethodrrCrCrCrDrs  AbstractAsyncContextManagerc@seZdZfZdS)AsyncContextManagerN)rArdr@rprCrCrCrDrUs rUa class AsyncContextManager(Generic[T_co]): __slots__ = () async def __aenter__(self): return self @abc.abstractmethod async def __aexit__(self, exc_type, exc_value, traceback): return None @classmethod def __subclasshook__(cls, C): if cls is AsyncContextManager: if sys.version_info[:2] >= (3, 6): return _collections_abc._check_methods(C, "__aenter__", "__aexit__") if (any("__aenter__" in B.__dict__ for B in C.__mro__) and any("__aexit__" in B.__dict__ for B in C.__mro__)): return True return NotImplemented __all__.append('AsyncContextManager') c@s"eZdZfZddZdS)r.cOs.t|trtdtt|||S)Nz4Type Dict cannot be instantiated; use dict() instead)rr.rPr r)rVr\r]rCrCrDrUs z Dict.__new__N)rArdr@rprUrCrCrCrDr.s c@s"eZdZfZddZdS)r/cOs5t|trtj||Sttj|||S)N)rr/rI defaultdictr )rVr\r]rCrCrDrUszDefaultDict.__new__N)rArdr@rprUrCrCrCrDr/s c@s"eZdZfZddZdS)r,cOs5t|trtj||Sttj|||S)N)rr,rIr )rVr\r]rCrCrDrUszCounter.__new__N)rArdr@rprUrCrCrCrDr,s ChainMapc@s"eZdZfZddZdS)rXcOs5t|trtj||Sttj|||S)N)rrXrIr )rVr\r]rCrCrDrUszChainMap.__new__N)rArdr@rprUrCrCrCrDrXs c@s"eZdZfZddZdS)r4cOs.t|trtdtt|||S)Nz@Type Generator cannot be instantiated; create a subclass instead)rr4rPr _G_base)rVr\r]rCrCrDrUs zGenerator.__new__N)rArdr@rprUrCrCrCrDr4s AsyncGeneratorc@seZdZfZdS)rZN)rArdr@rprCrCrCrDrZ s CT_corc@seZdZdZfZdS)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. N)rArdr@rgrprCrCrCrDr,s c sdfdd|D}tj|dd|D}tj||_|_y%tjdjjdd|_ Wnt t fk rYnX|S)NzDNamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a typecs+g|]!\}}|t|fqSrC)r|)rnr)rrCrD Is z!_make_nmtuple..cSsg|]\}}|qSrCrC)rr\rrCrCrDr]Js rrA__main__) rI namedtuple OrderedDictr% _field_typesr>rrr'rdr r)rWrnm_tplrC)rrD _make_nmtupleGs%rcrUr^rp__getnewargs___fields_field_defaultsra_make_replace_asdict_sourcerdrAr@r%cs"eZdZfddZS)NamedTupleMetac sb|jddr+tj||||Sts=td|jdi}t||j}g}i}xq|D]i}||kr||} |j| | ||= 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)]) TNcKsS|rt rtd|dkr4|j}n|rFtdt||S)Nz>Keyword syntax for NamedTuple is only supported in Python 3.6+zIEither list of fields or keywords can be provided to NamedTuple, not both)rmrPr(rc)r[rqZfieldskwargsrCrCrDrUs    zNamedTuple.__new__)rArdr@rgrOrUrCrCrCrDr3s cCs"dd}||_||_|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)NrC)rBrCrCrDnew_typeszNewType..new_type)rAZ __supertype__)rWrrurCrCrDr8s   Fc@sgeZdZdZfZeedddZeedddZe dddd Z e e dd d Z e e dd d Ze ddddZe e dddZe d6e edddZe e dddZe d7e edddZe d8e eedddZe de e e dd d!Ze e dd"d#Ze e dd$d%Ze de e d&d'd(Ze e dd)d*Ze ee d+d,d-Ze eedd.d/d0Ze d1dd2d3Ze ddd4d5ZdS)9IOaGeneric 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. )r;cCsdS)NrC)r[rCrCrDmodeszIO.modecCsdS)NrC)r[rCrCrDrWszIO.nameNcCsdS)NrC)r[rCrCrDcloseszIO.closecCsdS)NrC)r[rCrCrDclosedsz IO.closedcCsdS)NrC)r[rCrCrDfilenosz IO.filenocCsdS)NrC)r[rCrCrDflushszIO.flushcCsdS)NrC)r[rCrCrDisattysz IO.isattyrK)r\r;cCsdS)NrC)r[r\rCrCrDreadszIO.readcCsdS)NrC)r[rCrCrDreadablesz IO.readable)limitr;cCsdS)NrC)r[rrCrCrDreadlinesz IO.readline)hintr;cCsdS)NrC)r[rrCrCrD readlines sz IO.readlinesr)offsetwhencer;cCsdS)NrC)r[rrrCrCrDseek szIO.seekcCsdS)NrC)r[rCrCrDseekable sz IO.seekablecCsdS)NrC)r[rCrCrDtell szIO.tell)sizer;cCsdS)NrC)r[rrCrCrDtruncate sz IO.truncatecCsdS)NrC)r[rCrCrDwritable sz IO.writable)sr;cCsdS)NrC)r[rrCrCrDwrite szIO.write)linesr;cCsdS)NrC)r[rrCrCrD writelines sz IO.writelinesz IO[AnyStr]cCsdS)NrC)r[rCrCrDrL" sz IO.__enter__cCsdS)NrC)r[rnrrOrCrCrDrP& sz IO.__exit__rrr) rArdr@rgrprrlrwrWrrxrryr=rzr{r|r5r}r~rr0rrrrrrrrrLrPrCrCrCrDrvsT "!rvc@s_eZdZdZfZeeeefe dddZ eddddZ dS) BinaryIOz5Typed version of the return of open() in binary mode.)rr;cCsdS)NrC)r[rrCrCrDr0 szBinaryIO.write)r;cCsdS)NrC)r[rCrCrDrL4 szBinaryIO.__enter__N) rArdr@rgrprrrC bytearrayr=rrLrCrCrCrDr+ s %rc@seZdZdZfZeedddZeedddZ ee edddZ ee dd d Z eedd d Zeddd dZdS)TextIOz3Typed version of the return of open() in text mode.)r;cCsdS)NrC)r[rCrCrDbuffer> sz TextIO.buffercCsdS)NrC)r[rCrCrDencodingB szTextIO.encodingcCsdS)NrC)r[rCrCrDerrorsF sz TextIO.errorscCsdS)NrC)r[rCrCrDline_bufferingJ szTextIO.line_bufferingcCsdS)NrC)r[rCrCrDnewlinesN szTextIO.newlinescCsdS)NrC)r[rCrCrDrLR szTextIO.__enter__N)rArdr@rgrprrrrlrrrrrr rrrLrCrCrCrDr9 s rc@s7eZdZdZdddgZeZeZeZdS)ioz)Wrapper namespace for IO generic classes.rvrrN)rArdr@rg__all__rvrrrCrCrCrDrW s rz.ioPatternrcCs|jS)N)pattern)rrCrCrDe srMatchcCs |jjS)N)rer)mrCrCrDrg sc@s.eZdZdZddgZeZeZdS)rz&Wrapper namespace for re type aliases.rrN)rArdr@rgrrrrCrCrCrDrj s  rz.re)rrrrI contextlibrrZ stdlib_rer>rcollections.abcZcollections_abc ImportErrorr?_collections_abcrrr rnrr^__str__rlrQrrErMrNrHrIrGrFrcrrar|rSrr rZNoReturnrrrrrrrrrCr5rrrrrrrrrrrrrrrrrr r rrrrmrrr rr r6r"rBuiltinFunctionType MethodType ModuleTyper)r7r9r:r/r;r0rrrr7rr8r9r:rrr*r)r(r'r&r+r%r#rrHr1rr!rrr"r r=rrr0rJr-rrr2rrrr$rKrrTrUexecrr.rWr/r,rXr4rY GeneratorTyperZr[rrcrmrnrorkr3r8r<r=rvrrrrAmodulesrxrmatchrrCrCrCrDs               *%5C     W    ! )        ""9"6   I   C # '  #   ##& #!  ! #$. )!! ### ) # # &  #& ) # /  #   ' $      !( `