U e5db G@sdZddlmZmZddlZddlZddlZddlZddlZddl 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@dAdBdCdDdEdFdGdHdIdJdKgGZddMdNZdOdPZdQdRZdSdTZdUdVZdWdXZgZdYdZZd[d\ZGd]d^d^ZGd_d`d`ZGdadbdbeedLdcZeddddeZedGdfdeZeddgdeZeddhdeZ eddideZ!ed djdeZ"ed dkdeZ#Gdld d edLdcZ$GdmddeedLdcZ%d7dd5d9d:d4d6dddn Z&dodpZ'GdqdrdredLdcZ(Gdsdtdte(dLdcZ)Gdud d Z*GdvdwdwZ+GdxdydyZ,dzd{d|d}d~gZ-ddddddddddg Z.e-e.dgZ/ddZ0ddZ1ddZ2ddZ3dd#ddd%dd!dd'd*g ddgdZ4GdddeZ5Gdd d e*e5dZ6ddIZ7dd?Z8ddZ9e j:e j;e jdddCZ?ddBZ@ddAZAddEZBddFZCddZDddHZEdd@ZFe%dZGe%dZHe%dZIe%ddLdZJe%ddLdZKe%ddLdZLe%ddLdZMe%ddLeNdZOe%d>ePeQZRdddZSeSejjTdZTeSejjUeJZUeSejjVeJeMeKfZVeSejjWeJZWeSejjXeJZXeSejjYeJZYeSejjZeJZZeSejj[eJZ[eSejj\dZ\eSejj]eJZ]eSejj^eJZ^e)ejj_ddLdZ_de__eSejj`eJZaeSejjbeGZbeSejjceHeLfZceSejjdeHeIfZdeSejjeeJZeeSejjfeGZfeSejjgdZge)ehdddLdZidei_eSejeGddZkeSejleGZmeSeneGddZ`eSeoeJddZpeSejjqeJZqeSejjreHZreSejjseHeLfZseSejjteLZteSejueJZveSejweJZxeSeyeHeIfddZzeSej{eHeIfZ|eSej}eHeIfZ}eSej~eGZ~eSejeHeIfZeSejjeJeMeKfZeSejjeJeMfZeSeNeOddZde_e7Gdd0d0e6Ze7Gdd.d.e6Ze7Gdd-d-e6Ze7Gdd,d,e6Ze7Gdd/d/e6Ze7Gdd+d+e6eJZe7Gdd1d1e6eJZddÄZdZdZGddDŽdeNZGdd;d;edZddʄZddLd˜dd̈́ZddτZGddфdeNZGdd<dsz&_collect_type_vars..)rPrappendrR_specialextend__parameters__tuple)r`rhrZrir[_collect_type_varss rqcCst|ts|St|j}t|jD]J\}}t|tr\t|D]\}}||kr<||||<qdndd|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)rorTlen)cls parametersZalenZelenrZrZr[_check_generics  r}cCsg}|D]f}t|tr.|jtkr.||jqt|trdt|dkrd|dtkrd||ddq||qt |}t|t|krg}|D] }||kr||| |q|}|rt |t|S)zyAn internal helper for Union creation and substitution: flatten Unions among parameters, then remove duplicates. rN) rPrRrSrrnrsrprzrlsetremoveAssertionError)r|paramspZ all_paramsZ new_paramsrhrZrZr[_remove_dups_flattens""    rcs4ttjtfdd}|S)zInternal wrapper caching __getitem__ of generic types with a fallback to original function for non-hashable arguments. cs,z ||WStk r YnX||SNrTargskwdscachedfuncrZr[inners  z_tp_cache..inner) functools lru_cache _cleanupsrl cache_clearwraps)rrrZrr[ _tp_caches   rcsbt|tr|St|tr^tfdd|jD}||jkrH|S||}|j|_|S|S)zEvaluate all forward references in the given type t. For use of globalns and localns see the docstring for get_type_hints(). c3s|]}t|VqdSr) _eval_typergrxglobalnslocalnsrZr[ sz_eval_type..)rPr _evaluaterRrprsrvrm)rhrrZev_argsresrZrr[r s     rc@seZdZdZdZddZdS)_FinalzMixin to prohibit subclassing) __weakref__cOsd|krtddS)N_rootz&Cannot subclass special typing classesrselfrrrZrZr[__init_subclass__sz_Final.__init_subclass__N)rbr^r___doc__ __slots__rrZrZrZr[rsrc@s eZdZdZddZddZdS) _Immutablez3Mixin to indicate that object should not be copied.cCs|SrrZrrZrZr[__copy__%sz_Immutable.__copy__cCs|SrrZ)rZmemorZrZr[ __deepcopy__(sz_Immutable.__deepcopy__N)rbr^r_rrrrZrZrZr[r"srcspeZdZdZdZfddZddZddZd d Zd d Z d dZ ddZ ddZ ddZ eddZZS)rUzhInternal indicator of special typing constructs. See _doc instance attribute for specific docs. _nameZ_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). rr~zCannot subclass )rzrPrQrprTsuper__new__)r{rr __class__rZr[r3s   z_SpecialForm.__new__cCs||_||_dSrr)rnamedocrZrZr[__init__@sz_SpecialForm.__init__cCst|tstS|j|jkSr)rPrUNotImplementedrrotherrZrZr[__eq__Ds z_SpecialForm.__eq__cCs t|jfSr)hashrrrZrZr[__hash__Isz_SpecialForm.__hash__cCs d|jS)Ntyping.rrrZrZr[__repr__Lsz_SpecialForm.__repr__cCs|jSrrrrZrZr[ __reduce__Osz_SpecialForm.__reduce__cOstd|dS)NzCannot instantiate rrrZrZr[__call__Rsz_SpecialForm.__call__cCst|ddS)Nz! cannot be used with isinstance()rrrdrZrZr[__instancecheck__Usz_SpecialForm.__instancecheck__cCst|ddS)Nz! cannot be used with issubclass()rrr{rZrZr[__subclasscheck__Xsz_SpecialForm.__subclasscheck__cs|jdkr(t||jd}t||fS|jdkr|dkrBtdt|tsR|f}dtfdd|D}t|}t|d kr|d St||S|jd krt|d }t|t dfS|jd krt||St|ddS)N)r r z accepts only single type.rrZz Cannot take a Union of no types.z)Union[arg, ...]: each arg must be a type.c3s|]}t|VqdSrr\rgrrXrZr[rfsz+_SpecialForm.__getitem__..r~rrz#Optional[t] requires a single type.r z is not subscriptable) rr\rRrTrPrprrzrrO)rr|itemrWrZrr[ __getitem__[s(          z_SpecialForm.__getitem__)rbr^r_rrrrrrrrrrrrr __classcell__rZrZrr[rU,s rU)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(). 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. 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]. 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. 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|zt|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) rPrQrTcompile SyntaxErrorrrrrr)rrWrYcoderZrZr[rs 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.rYT)rr\rrrr)rrrrZrZr[rs  zForwardRef._evaluatecCs>t|tstS|jr2|jr2|j|jko0|j|jkS|j|jkSr)rPr rrrrrrZrZr[r s    zForwardRef.__eq__cCs t|jSr)rrrrZrZr[rszForwardRef.__hash__cCsd|jdS)Nz ForwardRef())rrrZrZr[rszForwardRef.__repr__N)T) rbr^r_rrrrrrrrZrZrZr[r 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. )rb __bound____constraints__ __covariant____contravariant__NF)bound covariant contravariantc s||_|r|rtdt||_t||_|r>|dk r>td|rVt|dkrVtddtfdd|D|_|rt |d|_ nd|_ zt dj d d }Wnttfk rd}YnX|d kr||_dS) Nz"Bivariant types are not supported.z-Constraints cannot be combined with bound=...r~z"A single constraint is not allowedz:TypeVar(name, constraint, ...): constraints must be types.c3s|]}t|VqdSrrrfrrZr[rVsz#TypeVar.__init__..zBound must be a type.rb__main__typing)rb ValueErrorboolrrrTrzrprr\rsys _getframe f_globalsgetAttributeErrorr^)rrrrrZ constraintsZdef_modrZrr[rJs(    zTypeVar.__init__cCs&|jr d}n|jrd}nd}||jS)N+-~)rrrb)rprefixrZrZr[rbs zTypeVar.__repr__cCs|jSr)rbrrZrZr[rkszTypeVar.__reduce__)rbr^r_rrrrrrZrZrZr[rs+  ) rrrpdictr frozensetdeque defaultdictrOr;cCs|do|dS)N__) startswithendswith)attrrZrZr[ _is_dundersrcseZdZdZddddddZedd Zd d Zd d ZddZ ddZ ddZ ddZ ddZ fddZddZddZddZZS) rRaThe 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).rZN)_TypingEllipsis _TypingEmptyrrZrZr[rs  z)_GenericAlias.__init__..)_instrmrb_normalize_aliasrrrPrprSrsrqrorr^)roriginrrrrZ orig_namerZrZr[rs      z_GenericAlias.__init__cs^|jttfkrtd|t|ts,|f}dtfdd|D}t||t||j|S)Nz%Cannot subscript already-subscripted *Parameters to generic types must be types.c3s|]}t|VqdSrrrrrZr[rsz,_GenericAlias.__getitem__..) rSr rrTrPrpr}rurorrrZrr[rs  z_GenericAlias.__getitem__cCst|j||j|jdS)N)rr)rRrSrrrrZrZr[rvsz_GenericAlias.copy_withcCs|jdks&t|jdkrx|jdtkrx|jr8d|j}n t|j}|jshdddd|jDd }nd }||S|jrd Sd dd d|jddDdt|jdd S)Nrrr[, cSsg|] }t|qSrZrerrZrZr[rksz*_GenericAlias.__repr__..]ztyping.Callableztyping.Callable[[cSsg|] }t|qSrZrrrZrZr[rksz], )rrzrsEllipsisrerSrmjoin)rrrrZrZr[rs       z_GenericAlias.__repr__cCsRt|tstS|j|jkrdS|jtkrF|jtkrFt|jt|jkS|j|jkS)NF)rPrRrrSrrrsrrZrZr[rs  z_GenericAlias.__eq__cCs,|jtkrttt|jfSt|j|jfSr)rSrrrrsrrZrZr[rs z_GenericAlias.__hash__cOsT|js$td|jd|jd|j||}z ||_Wntk rNYnX|S)NType z cannot be instantiated; use z () instead)rrTrlowerrS__orig_class__r)rrkwargsresultrZrZr[rs  z_GenericAlias.__call__cCs|jrZg}|j|kr ||j||}tdd||ddDsR|tt|S|jtkrt|krpdS||}||ddD]}t|t r||k rdSq|jfS)Ncss"|]}t|tpt|tVqdSr)rPrR issubclassr rgbrZrZr[rsz0_GenericAlias.__mro_entries__..r~rZ) rrSrlindexanyr rprrPrR)rbasesrryrrZrZr[__mro_entries__s$      z_GenericAlias.__mro_entries__cCs*d|jkrt|st|j|St|dS)NrS)__dict__rgetattrrSr)rrrZrZr[ __getattr__s z_GenericAlias.__getattr__cs2t|s|dkr t||nt|j||dS)N)rrrm)rr __setattr__setattrrS)rrvalrrZr[rsz_GenericAlias.__setattr__cCs|t|Sr)rrOrrZrZr[rsz_GenericAlias.__instancecheck__cCs<|jr0t|tst||jS|jr0t|j|jStddS)NzBSubscripted generics cannot be used with class and instance checks)rmrPrRrrSrTrrZrZr[rs   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)Nrrrr~) rmrglobalsrSrrzrsrrrrprPoperatorgetitem)rrrrZrZr[r s   z_GenericAlias.__reduce__)rbr^r_rrrrrvrrrrr rrrrrrrZrZrr[rRs     rRcs,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 ) rrm__getitem_inner__rPrprzrTrrr)rrrrrZrZr[r"s    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) NrZrr~.z Tuple[t, ...]: t must be a type.rz*Tuple[t0, t1, ...]: each t must be a type.c3s|]}t|VqdSrrrrrZr[r>sz:_VariadicGenericAlias.__getitem_inner__..z.Callable[args, result]: result must be a type.z6Callable[[arg, ...], result]: each arg must be a type.c3s|]}t|VqdSrr)rgrWrrZr[rGs)rSrprmrvrrPrzr\r collectionsabcrrrr)rrrrrrrr[r2s.      z'_VariadicGenericAlias.__getitem_inner__)rbr^r_rrrrrrZrZrr[rsrcs@eZdZdZdZdZfddZeddZfdd Z Z 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 rZFcs^|ttfkrtd|jdtjtjkrF|jtjk rFt|}ntj|f||}|S)Nrz< cannot be instantiated; it can be used only as a base class)r rrTrbrrobjectr)r{rrrdrrZr[rds  zGeneric.__new__cst|ts|f}|s.|tk r.td|jddtfdd|D}|ttfkrtdd|Dsxtd|jdt t |t |krtd|jd n t ||t ||S) NzParameter list to z[...] cannot be emptyrc3s|]}t|VqdSrrrrrZr[rvsz,Generic.__class_getitem__..css|]}t|tVqdSr)rPrrrZrZr[ryszParameters to z [...] must all be type variablesz[...] must all be unique) rPrprrTr_r rallrbrzrr}rR)r{rrZrr[__class_getitem__ns&       zGeneric.__class_getitem__c s tj||g}d|jkr(t|jk}nt|jko:|jdk}|rHtdd|jkrt|j}d}|jD].}t |t rf|j tkrf|dk rtd|j }qf|dk rt |}t ||ksdfdd|D}ddd|D} td |d | d |}t||_ dS) N__orig_bases__rz!Cannot inherit from plain Genericz0Cannot inherit from Generic[...] multiple types.rc3s|]}|krt|VqdSrrQrfZgvarsetrZr[rsz,Generic.__init_subclass__..css|]}t|VqdSrr)rggrZrZr[rszSome type variables (z) are not listed in Generic[r)rrr r r __bases__rbrTrqrPrRrSrorrrp) r{rrrjerrorZgvarsbaseZtvarsetZs_varsZs_argsrrr[rs8      zGeneric.__init_subclass__) rbr^r_rr _is_protocolrrrrrrZrZrr[r Ms  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. Nrbr^r_rrZrZrZr[rsrc@seZdZdZdS)rz(Internal placeholder for ... (ellipsis).Nr%rZrZrZr[rsrrorrr$_is_runtime_protocol__abstractmethods____annotations__r rrr^rr__subclasshook__r_MutableMapping__markercCsrt}|jddD]X}|jdkr$qt|di}t|jt|D] }|dsJ|tkrJ| |qJq|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)rr r(Z_abc_) r__mro__rbrrrr keysrEXCLUDED_ATTRIBUTESadd)r{attrsr# annotationsrrZrZr[_get_protocol_attrss  r1cstfddtDS)Nc3s|]}tt|dVqdSr)rVrrgrr{rZr[rsz,_is_callable_members_only..)rr1r3rZr3r[_is_callable_members_onlysr4cOst|jrtddS)Nz Protocols cannot be instantiated)rOr$rT)rrrrZrZr[_no_inits r5c Cs6ztdjddkWSttfk r0YdSXdS)zAllow instnance 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. rrb)rrTN)rrrrrrZrZrZr[_allow_reckless_class_chekssr6AbstractContextManagerAbstractAsyncContextManager)zcollections.abc contextlibcseZdZfddZZS) _ProtocolMetacsVtddrtr$tjr$dSjrJtfddtDrJdStS)Nr$FTc3s8|]0}t|o.tt|d p.t|dk VqdSr)hasattrrVrr2r{instancerZr[rs z2_ProtocolMeta.__instancecheck__..) rr4rrr$rr1rrr<rr<r[rs  z_ProtocolMeta.__instancecheck__)rbr^r_rrrZrZrr[r:sr:cs,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: ... rZTFcstj||jdds2tddjD_fdd}djkrN|_jsXdSjD]F}|tt fks^|j t kr|j t |j ks^t |t r|js^td|q^t_dS) Nr$Fcss|]}|tkVqdSr)rrrZrZr[r)sz-Protocol.__init_subclass__..csjddstStdds0tr(tStdtsJtrBtStdt|ts\tdt D]v}|j D]b}||jkr|j|dkrtSqdt|di}t|t j j rn||krnt|trn|jrnqdqntSqddS) Nr$Fr&zLInstance and class checks can only be used with @runtime_checkable protocolsz._proto_hookr)z7Protocols can only inherit from other protocols, got %r)rrr rr r!r$r)rr r^_PROTO_WHITELISTrbrrTr5r)r{rrr>r#rr3r[r$s, &   zProtocol.__init_subclass__) rbr^r_rrr$r&rrrZrZrr[rs ) metaclasscCs&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)rr r$rTr&r3rZrZr[rKds cCs|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). rZ)typrrZrZr[rA}sc Csz |j}Wntk r"iYSX|j}|j}|d|}|jpDd}|j}|rXt|ni}|t|}t||d|D]\}} ||kst | ||<qz|S)z:Internal helper to extract the default arguments, by name.NrZ) __code__r co_argcount co_varnames __defaults____kwdefaults__rrzzipr) rrZ pos_countZ arg_namesdefaultsZ kwdefaultsrZ pos_offsetrvaluerZrZr[ _get_defaultss       rJc Cst|ddriSt|tri}t|jD]z}|dkrDtj|jj}n|}|j di}| D]B\}}|dkrvtd}t|t rt |dd}t |||}|||<q^q(|S|dkrt|tjr|j}n"|} t| dr| j} qt| di}|dkr|}n|dkr|}t|dd}|dkr6t|tr(iStd|t|} t|}| D]d\}}|dkrhtd}t|t r|t |}t |||}|| kr| |dkrt|}|||<qN|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__Nr(Fr __wrapped__ __globals__z1{!r} is not a module, class, method, or function.)rrPrOreversedr+rmodulesr^r ritemsrQr rr` ModuleTyper;rL_allowed_typesrTformatrJrr) rdrrZhintsr#Z base_globalsannrrIZnsobjrHrZrZr[rEs^                 cCs t|tr|jS|tkrtSdS)aGet the unsubscripted version of a type. This supports generic types, Callable, Tuple, Union, Literal, Final and ClassVar. 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 N)rPrRrSr )rwrZrZr[rDs  cCsRt|trN|jsN|j}t|tjjkrJ|dtk rJt |dd|df}|SdS)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) rNrrZ) rPrRrmrsrDrrrrrr)rwrrZrZr[rC s cCst|trt|j}|jD]"\}}||j|fkr||q|D](}t|tj r`d|_ t|trJt |qJz 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) rPrOr copyrPr!popvaluesr`rarKrGrT)rWZ arg_attrsrrrdrZrZr[rGs        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|}|Sr)rG)rrr decoratorrZr[wrapped_decorator@s z2no_type_check_decorator..wrapped_decorator)rr)rYrZrZrXr[rH9scOs 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)NotImplementedErrorrrZrZr[_overload_dummyIsr\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\)rrZrZr[rJRscCs|S)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. rZ)frZrZr[rBosTKTVTT_co)rV_coVT_coT_contra)rCT_co)rrcCst||d|dS)NT)rr)rR)rrrrZrZr[_aliassrfrZ)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)r2z(An ABC with one abstract method __int__.rZreturncCsdSrrZrrZrZr[__int__szSupportsInt.__int__N)rbr^r_rrrintrirZrZrZr[r2sc@s&eZdZdZdZeedddZdS)r0z*An ABC with one abstract method __float__.rZrgcCsdSrrZrrZrZr[ __float__szSupportsFloat.__float__N)rbr^r_rrrfloatrkrZrZrZr[r0sc@s&eZdZdZdZeedddZdS)r/z,An ABC with one abstract method __complex__.rZrgcCsdSrrZrrZrZr[ __complex__ szSupportsComplex.__complex__N)rbr^r_rrrcomplexrmrZrZrZr[r/sc@s&eZdZdZdZeedddZdS)r.z*An ABC with one abstract method __bytes__.rZrgcCsdSrrZrrZrZr[ __bytes__szSupportsBytes.__bytes__N)rbr^r_rrrbytesrorZrZrZr[r.sc@s&eZdZdZdZeedddZdS)r1z*An ABC with one abstract method __index__.rZrgcCsdSrrZrrZrZr[ __index__szSupportsIndex.__index__N)rbr^r_rrrrjrqrZrZrZr[r1sc@s&eZdZdZdZeedddZdS)r-zMAn ABC with one abstract method __abs__ that is covariant in its return type.rZrgcCsdSrrZrrZrZr[__abs__(szSupportsAbs.__abs__N)rbr^r_rrrrarrrZrZrZr[r-#sc@s*eZdZdZdZedeedddZdS) r3zOAn ABC with one abstract method __round__ that is covariant in its return type.rZr)ndigitsrhcCsdSrrZ)rrsrZrZr[ __round__2szSupportsRound.__round__N)r) rbr^r_rrrrjrartrZrZrZr[r3-sc stdfdd|D}t|dd|D}t||_|_ztdjdd|_ Wnt t fk rnYnX|S)NzDNamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a typecsg|]\}}|t|fqSrZrrgnrhrrZr[rk9sz!_make_nmtuple..cSsg|] \}}|qSrZrZrurZrZr[rk:srrbr) r namedtuplerr( _field_typesrrrrr^rr)rr`nm_tplrZrr[ _make_nmtuple7srz) rrr__getnewargs___fields_field_defaultsrx_make_replace_asdictZ_source)r^rbr(cseZdZfddZZS)NamedTupleMetac s|ddrt||||S|di}t||}g}i}|D]H}||krl||} || | ||<qD|rDtdj|d| dqDt ||j_ t ||j_ ||_|D]<} | tkrtd| q| tkr| |jkrt|| || q|S)NrFr(zXNon-default namedtuple field {field_name} cannot follow default field(s) {default_names}r) field_nameZ default_namesz&Cannot overwrite NamedTuple attribute )rrrrzrPrlrTrSrr,rr(rprEr} _prohibitedrrmr|r) r{typenamer nsr`ryrHZ defaults_dictrZ default_valuekeyrrZr[rOs2       zNamedTupleMeta.__new__)rbr^r_rrrZrZrr[rMsrc@s"eZdZdZdZddZde_dS)r=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)]) TcOs|s td|^}}|r"|^}}n4d|krN|d}ddl}|jdtddntd|rz |\}Wqtk rtdt|dd dYqXnrr(z?TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a typecsi|]\}}|t|qSrZr)rgrvrwrrZr[ sz*_TypedDictMeta.__new__..r) rrrrrrrrPupdater r(r;r)r{rr rrZtp_dictZannsr#rrr[rs   z_TypedDictMeta.__new__)T)rbr^r_rrrrrrZrZrr[rsrc@seZdZdZdS)r>aA 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 Point2D.__annotations__. 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+ Nr%rZrZrZr[r>scCsdd}||_||_|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|SrrZ)xrZrZr[new_typeszNewType..new_type)rbZ __supertype__)rrwrrZrZr[rF sc@seZdZdZdZeeedddZeeedddZ eddd d Z eee dd d Z ee dd dZeddddZee dddZed7e edddZee dddZed8e edddZed9e eedddZed:e e e d d!d"Zee dd#d$Zee dd%d&Zed;e e d'd(d)Zee dd*d+Zeee d,d-d.Zeeedd/d0d1Zed2dd3d4Zeddd5d6ZdS)<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. rZrgcCsdSrrZrrZrZr[mode=szIO.modecCsdSrrZrrZrZr[rBszIO.nameNcCsdSrrZrrZrZr[closeGszIO.closecCsdSrrZrrZrZr[closedKsz IO.closedcCsdSrrZrrZrZr[filenoPsz IO.filenocCsdSrrZrrZrZr[flushTszIO.flushcCsdSrrZrrZrZr[isattyXsz IO.isattyr)rvrhcCsdSrrZ)rrvrZrZr[read\szIO.readcCsdSrrZrrZrZr[readable`sz IO.readable)limitrhcCsdSrrZ)rrrZrZr[readlinedsz IO.readline)hintrhcCsdSrrZ)rrrZrZr[ readlineshsz IO.readlinesr)offsetwhencerhcCsdSrrZ)rrrrZrZr[seeklszIO.seekcCsdSrrZrrZrZr[seekablepsz IO.seekablecCsdSrrZrrZrZr[telltszIO.tell)sizerhcCsdSrrZ)rrrZrZr[truncatexsz IO.truncatecCsdSrrZrrZrZr[writable|sz IO.writablesrhcCsdSrrZrrrZrZr[writeszIO.write)linesrhcCsdSrrZ)rrrZrZr[ writelinessz IO.writelinesz IO[AnyStr]cCsdSrrZrrZrZr[ __enter__sz IO.__enter__cCsdSrrZ)rrOrI tracebackrZrZr[__exit__sz IO.__exit__)r)r)r)r)N) rbr^r_rrpropertyrrQrrrrrrjrrrr@rrrr9rrrrrrrrrrrZrZrZr[r.sZ rc@sBeZdZdZdZeeeefe dddZ eddddZ d S) BinaryIOz5Typed version of the return of open() in binary mode.rZrcCsdSrrZrrZrZr[rszBinaryIO.writergcCsdSrrZrrZrZr[rszBinaryIO.__enter__N) rbr^r_rrrrrp bytearrayrjrrrZrZrZr[rs rc@seZdZdZdZeeedddZeee dddZ eee e ddd Z eee dd d Zeeedd d ZeddddZdS)TextIOz3Typed version of the return of open() in text mode.rZrgcCsdSrrZrrZrZr[buffersz TextIO.buffercCsdSrrZrrZrZr[encodingszTextIO.encodingcCsdSrrZrrZrZr[errorssz TextIO.errorscCsdSrrZrrZrZr[line_bufferingszTextIO.line_bufferingcCsdSrrZrrZrZr[newlinesszTextIO.newlinescCsdSrrZrrZrZr[rszTextIO.__enter__N)rbr^r_rrrrrrrQrrrrrrrrrZrZrZr[rs&rc@s&eZdZdZdddgZeZeZeZdS)ioz)Wrapper namespace for IO generic classes.rrrN)rbr^r_r__all__rrrrZrZrZr[rs  rz.ioc@s eZdZdZddgZeZeZdS)rez&Wrapper namespace for re type aliases.PatternMatchN)rbr^r_rrrrrZrZrZr[rsrz.re)T)NN)T)N)rrrrrZcollections.abcr9rrrZ stdlib_rerr`rrrrr\rerqrur}rrrrrrrUrrIr r rrr r rrrrRrr rrZ_TYPING_INTERNALSZ_SPECIAL_NAMESr-r1r4r5r6r?r:rrKrArJraBuiltinFunctionType MethodTyperQrRrErDrCrGrHr\rJrBr^r_r`rarbrcrdrOrerprQr@rfrr%r(r'r&rrr,r#rr)rr;rr!rrr"r rrprrrr9rr6rrr<rrrr$r7rr8r+rr7rr8r:r5r4r?r*rr2r0r/r.r1r-r3rzrrmrr=rrrrr>rFrLrMrrrrrbrOrrrZrZrZr[s(X !   I  2a /[ b  V                    @+c#