NfbNdZddlmZmZddlZddlmZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddlZddl mZmZmZmZ ddlmZn#e$rdZYnwxYwgdZdd d d Zdd d d ZdZdZdZdZdZdZdZdZ dZ!gZ"dd ddZ#e$fdZ%GddZ&GddZ'GddZ(Gd d!e&e(d "Z)Gd#d$e)d "Z*Gd%d&e+Z,Gd'd(e,)Z-e)d*Z.e)d+Z/e)d,Z0e)d-Z1e)d.Z2e)d/Z3e)d0Z4e)d1Z5e*e#d d2Z6e)d3Z7e)d4Z8e)d5Z9Gd6d7e&d "Z:d8e-d9e;fd:ZGd>d?Z?Gd@dAe&e'e?e>d "Z@GdBdCe&e'e>d "ZAGdDdEe&e'd "ZBGdFdGe&e'd "ZCGdHdIe&e'e?e>d "ZDdJZEGdKdLe&d "ZFGdMdNeFd "ZGGdOdPe(eFd "ZHGdQdRe(eGd "ZIGdSdTeHd "ZJGdUdVeHd "ZKGdWdXe(eGd "ZLdYZMGdZd[eGd "ZNGd\d]eGd "ZOe)d^ZPGd_d`eGd "ZQGdadbZRGdcddZSgdeZTgdfZUeTeUzdggzZVdhZWdiZXdjZYddmZZddoZ[gdpdqdrgdsZ\GdtdueZ]GdvdweRe])Z^Gdxdye(eGd "Z_Gdzd{Z`d|Zad}Zbd~Zce jde jee jfe jgeeefZhddZidZjdZkdZldZmdZnde/d9e/fdZodZpdZqdZreejseetZudZvdZwdZxdZye@dZze@dZ{e@dZ|e@dd Z}e@dd Z~e@dd Ze@dd Ze@dd e+Ze@deeZeHZeejjdZeejjdkZeejjdnZeejjdkZeejjdkZeejjdkZeejjdkZeejjdkZeejjdZeejjdkZeejjdkZeJejjdZde_eejjdkdZeejjdkZeejjdZeejjdZeejjdkZeejjdkZeejjdZeKedd dZde_eedkd dZeejdkdZeedkd dZee$dkd dZeejjdkZeejjdkZeejjdZeejjdkZeejdkdZeejdkdZeetdd dZeejddZeejdZeejdkZeejdZeejjdnZeejjdZee+dkd dZde_eaGdde^ZeaGdde^ZeaGdde^ZeaGdde^ZeaGdde^ZeaGdde^e}ZeaGdde^e}ZddZe$hdZe$hdZGdde+ZddZe+eddiZd„Zee_GdÄde+Zdd dŜdƄZe+eddiZdȄe_e)dɄZe)dʄZGd˄d̦ZeZd ZGd̈́deReZGdτdeeZGdфdeeZGdӄde+ZGdՄdeͬ)Zedze_ee jej<ee jdkZee jdkZGd؄deͬ)Z edze _e e je j<dezd9ezfd܄Zd d d ddݜde;de;de;dee+e-ede-fzdfde-d9eezgezff dZdS)ad 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, Never, ClassVar, Union, Optional, Concatenate, Unpack * Classes whose instances can be type arguments in addition to types: ForwardRef, TypeVar and ParamSpec * The core of internal generics API: _GenericAlias and _VariadicGenericAlias, the latter is currently only used by Tuple and Callable. All subscripted types like X[int], Union[int, str], etc., are instances of either of these classes. * The public counterpart of the generics API consists of two classes: Generic and Protocol. * Public helper functions: get_type_hints, overload, cast, no_type_check, no_type_check_decorator. * Generic aliases for collections.abc ABCs and few additional protocols. * Special types: NewType, NamedTuple, TypedDict. * Wrapper submodules for re and io related types. )abstractmethodABCMetaN) defaultdict)WrapperDescriptorTypeMethodWrapperTypeMethodDescriptorType GenericAlias)_idfuncc|SN)_xs /usr/lib/python3.11/typing.pyr r 's)a AnnotatedAnyCallableClassVar ConcatenateFinal ForwardRefGenericLiteralOptional ParamSpecProtocolTupleTypeTypeVar TypeVarTupleUnion AbstractSet ByteString ContainerContextManagerHashable ItemsViewIterableIteratorKeysViewMapping MappingViewMutableMappingMutableSequence MutableSetSequenceSized ValuesView Awaitable AsyncIterator AsyncIterable Coroutine CollectionAsyncGeneratorAsyncContextManager Reversible SupportsAbs SupportsBytesSupportsComplex SupportsFloat SupportsIndex SupportsInt SupportsRoundChainMapCounterDequeDict DefaultDictList OrderedDictSet FrozenSet NamedTuple TypedDict GeneratorBinaryIOIOMatchPatternTextIOAnyStr assert_type assert_nevercastclear_overloadsdataclass_transformfinalget_args get_origin get_overloadsget_type_hints is_typeddict LiteralStringNeverNewType no_type_checkno_type_check_decoratorNoReturn NotRequiredoverload ParamSpecArgsParamSpecKwargsRequired reveal_typeruntime_checkableSelfText TYPE_CHECKING TypeAlias TypeGuardUnpackFallow_special_formscv|tdSt|trt|||S|S)z=For converting None to type(None), and strings to ForwardRef.N)moduleis_class)type isinstancestrr)argrvrts r _type_convertr|sA {Dzz#sL#f7JKKKK JrTcttf}|s|tfz }|r |tfz }t |||}t |t r|j|vrt|d|ttttttfvr|S|r|ttfvr|St |ts|ttfvrtd|dt!|t"urt|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). )rvrt is not valid as type argumentzPlain z Got z.100.)rrrrr|ry _GenericAlias __origin__ TypeErrorrr`rerarmrp _SpecialFormrxtuple)r{msg is_argumentrvrtinvalid_generic_formss r _type_checkrs3%h/ .(,  . !eX - ! F@S T T TC3 &&@ N3 3 33>>>??? sM8UD)DDD sx&777 #|$$F/B(B(BDDDDEEE CyyE322S2222333 JrcZ|dup't|ttttfS)N.)ryrlistr_ConcatenateGenericAlias)r{s r_is_param_exprrs2 #: @C D)%= >@@@rc|jtjjuo(t |dkot |d S)aInternal helper for munging collections.abc.Callable's __args__. The canonical representation for a Callable's __args__ flattens the argument types, see https://bugs.python.org/issue42195. For example: collections.abc.Callable[[int, int], str].__args__ == (int, int, str) collections.abc.Callable[ParamSpec, str].__args__ == (ParamSpec, str) As a result, if we need to reconstruct the Callable from its __args__, we need to unflatten it. r)r collectionsabcrlenr)typargss r_should_unflatten_callable_argsrs> +/22 =Ta;N47$;$; <rc0t|tjrt|St|tr#|jdkr|jS|jd|jS|durdSt|tjr|jSt|S)a;Return the repr() of an object, special-casing types (internal helper). If obj is a type, we return a shorter version than the default type.__repr__, based on the module and qualified name, which is typically enough to uniquely identify a type. For everything else, we fall back on repr(obj). builtinsr....) rytypesr reprrx __module__ __qualname__ FunctionType__name__objs r _type_reprrs#u)**Cyy#t6 >Z ' '# #.553#3555 czzu#u)**| 99rcg}|D]o}t|trt|dr||vr||Bt |ddD]}||vr||pt |S)zCollect all type variables and parameter specifications in args in order of first appearance (lexicographic order). For example:: _collect_parameters((T, Callable[P, T])) == (T, P) __typing_subst____parameters__r )ryrxhasattrappendgetattrr)r parameterstrs r_collect_parametersrs J  ) ) a     1( ) ) ) ""!!!$$$Q 0"55 ) )J&&%%a((( )   rc |st|dt|}||kr#td||krdndd|d|d|dS) zCheck correct count for parameters of a generic cls (internal helper). This gives a nice error message in case of count mismatch.  is not a generic classToo manyfew arguments for ; actual , expected N)rr)clsrelenalens r_check_genericr s 93777888 z??D t||;vv%;;PS;;#';;48;;<< <|rcg}|D]L}t|dd}|"|r |ddus||7||M|S)N__typing_unpacked_tuple_args__.)rextendr)rnewargsr{subargss r _unpack_argsrspG  #?FF   GBK34F4F NN7 # # # # NN3     Nrct|}t|t|krCg}|D]0}||vr*||||1|}|r J||Sr )setrrremove)params all_params new_paramsrs r _deduplicatersVJ :V$$  % %AJ!!!$$$!!!$$$))z))) Mrcg}|D]S}t|ttjfr||j>||Ttt|S)zyAn internal helper for Union creation and substitution: flatten Unions among parameters, then remove duplicates. ) ry_UnionGenericAliasr UnionTyper__args__rrrrrps r_remove_dups_flattenr-st F  a,eo> ? ?  MM!* % % % % MM!     f%% & &&rcg}|D]G}t|tr||j2||Ht |S)zJAn internal helper for Literal creation: flatten Literals among parameters)ry_LiteralGenericAliasrrrrrs r_flatten_literal_paramsr<sa F  a- . .  MM!* % % % % MM!     ==rtypedc,fd}| ||S|S)zInternal wrapper caching __getitem__ of generic types with a fallback to original function for non-hashable arguments. ctjtjtjfd}|S)NrcF |i|S#t$rYnwxYw|i|Sr r)rkwdscachedfuncs rinnerz+_tp_cache..decorator..innerRsR vt,t,,,    4&&& &s  ) functools lru_cache _cleanupsr cache_clearwraps)rrrrs` @r decoratorz_tp_cache..decoratorNss1$5111$77+,,,    ' ' ' ' '   '  rr )rrrs ` r _tp_cacherJs8      y rc t|tr|St|ttt jfr+t|trotd|jD}|j }t||r|j |dd|df}n |j |}|r t|}tfd|jD}||jkr|St|trt |j |St|t jrtjtj|S||S|S)zEvaluate all forward references in the given type t. For use of globalns and localns see the docstring for get_type_hints(). recursive_guard is used to prevent infinite recursion with a recursive ForwardRef. c3bK|]*}t|trt|n|V+dSr )ryrzr.0r{s r z_eval_type..jsO$.c3#7#7@ 3SrNrc3<K|]}t|VdSr ) _eval_type)raglobalnslocalnsrecursive_guards rrz_eval_type..us1^^a 1hII^^^^^^r)ryr _evaluaterr rrrr __unpacked__rrrrrreduceoperatoror_ copy_with)rrrrr is_unpackedev_argss ``` rrr`s !Z  ?{{8Wo>>>!m\5?CDD( a & & :D.K.q$77 'L$ss)T"X!67L& 1I^^^^^^STS]^^^^^ aj H a & & 7 g66 6 a ) ) (#HL':: :;;w'' ' HrceZdZdZdZdZdS)_FinalzMixin to prohibit subclassing) __weakref__c,d|vrtddS)N_rootz&Cannot subclass special typing classesr)rrrs r__init_subclass__z_Final.__init_subclass__s$ $  DEE E  rN)rrr__doc__ __slots__rr rrrrs3'' IFFFFFrrc"eZdZdZdZdZdZdS) _Immutablez3Mixin to indicate that object should not be copied.r c|Sr r selfs r__copy__z_Immutable.__copy__ rc|Sr r )rmemos r __deepcopy__z_Immutable.__deepcopy__rrN)rrrrrrrr rrrrs===IrrceZdZdZdZdZdS) _NotIterableaMixin to prevent iteration, without being compatible with Iterable. That is, we could do: def __iter__(self): raise TypeError() But this would make users of this mixin duck type-compatible with collections.abc.Iterable - isinstance(foo, Iterable) would be True. Luckily, we can instead prevent iteration by setting __iter__ to None, which is treated specially. r N)rrrrr__iter__r rrrrs$  IHHHrrcdeZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z ed Zd S)r)_namer_getitemcD||_|j|_|j|_dSr )r rrr)rgetitems r__init__z_SpecialForm.__init__s  %  rc6|dvr|jSt|)N>rr)rAttributeError)ritems r __getattr__z_SpecialForm.__getattr__s$ / / /: T"""rc&td|)NCannot subclass r)rbasess r__mro_entries__z_SpecialForm.__mro_entries__s3433444rcd|jzSNtyping.rrs r__repr__z_SpecialForm.__repr__4:%%rc|jSr rrs r __reduce__z_SpecialForm.__reduce__ zrc&td|)NzCannot instantiate r)rrrs r__call__z_SpecialForm.__call__s6d66777rc t||fSr r"rothers r__or__z_SpecialForm.__or__T5[!!rc t||fSr r!r"s r__ror__z_SpecialForm.__ror__UD[!!rc&t|d)Nz! cannot be used with isinstance()rrrs r__instancecheck__z_SpecialForm.__instancecheck__4BBBCCCrc&t|d)Nz! cannot be used with issubclass()rrrs r__subclasscheck__z_SpecialForm.__subclasscheck__r,rc.|||Sr )r rrs r __getitem__z_SpecialForm.__getitem__s}}T:...rN)rrrrr rrrrrr$r'r+r/rr2r rrrrs0I''' ### 555&&&888""""""DDDDDD//Y///rr)rceZdZdZdS)_LiteralSpecialFormcNt|ts|f}|j|g|RSr )ryrr r1s rr2z_LiteralSpecialForm.__getitem__s5*e,, '$Jt}T/J////rN)rrrr2r rrr4r4s#00000rr4c(eZdZfdZfdZxZS)_AnyMetacv|turtdt|S)Nz+typing.Any cannot be used with isinstance())rrsuperr+)rr __class__s rr+z_AnyMeta.__instancecheck__s3 3;;IJJ Jww((---rcZ|turdStS)Nz typing.Any)rr9rrr:s rrz_AnyMeta.__repr__s' 3;;<ww!!!r)rrrr+r __classcell__r:s@rr7r7sQ..... """""""""rr7c"eZdZdZfdZxZS)raWSpecial 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 checks. cn|turtdtj|g|Ri|S)NzAny cannot be instantiated)rrr9__new__)rrkwargsr:s rrAz Any.__new__sA #::899 9uwws4T444V444r)rrrrrAr=r>s@rrrsB  555555555rr) metaclassc&t|d)aSpecial type indicating functions that never return. Example:: from typing import NoReturn def stop() -> NoReturn: raise Exception('no way') NoReturn can also be used as a bottom type, a type that has no values. Starting in Python 3.11, the Never type should be used for this concept instead. Type checkers should treat the two equivalently.  is not subscriptablerr1s rreres t222 3 33rc&t|d)aeThe bottom type, a type that has no members. This can be used to define a function that should never be called, or a function that never returns:: from typing import Never def never_call_me(arg: Never) -> None: pass def int_or_str(arg: int | str) -> None: never_call_me(arg) # type checker error match arg: case int(): print("It's an int") case str(): print("It's a str") case _: never_call_me(arg) # ok, arg is of type Never rErr1s rrara s. t222 3 33rc&t|d)aiUsed to spell the type of "self" in classes. Example:: from typing import Self class Foo: def return_self(self) -> Self: ... return self This is especially useful for: - classmethods that are used as alternative constructors - annotating an `__enter__` method which returns self rErr1s rrmrm%s" t222 3 33rc&t|d)a Represents an arbitrary literal string. Example:: from typing import LiteralString def run_query(sql: LiteralString) -> ... ... def caller(arbitrary_string: str, literal_string: LiteralString) -> None: run_query("SELECT * FROM students") # ok run_query(literal_string) # ok run_query("SELECT * FROM " + literal_string) # ok run_query(arbitrary_string) # type checker error run_query( # type checker error f"SELECT * FROM students WHERE name = {arbitrary_string}" ) Only string literals and other LiteralStrings are compatible with LiteralString. This provides a tool to help prevent security issues such as SQL injection. rErr1s rr`r`9s2 t222 3 33rcJt||d}t||fS)a3Special type construct to mark class variables. An annotation wrapped in ClassVar indicates that a given attribute is intended to be used as a class variable and should not be set on instances of that class. Usage:: class Starship: stats: ClassVar[Dict[str, int]] = {} # class variable damage: int = 10 # instance variable ClassVar accepts only types and cannot be further subscribed. Note that ClassVar is not a class itself, and should not be used with isinstance() or issubclass().  accepts only single type.rrrrrs rrrUs." zd#F#F#F G GD w ' ''rcJt||d}t||fS)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. rJrKrLs rrris.$ zd#F#F#F G GD w ' ''rcx|dkrtdt|ts|f}dtfd|D}t|}t |dkr|dSt |dkr#t d|vrt ||d St ||S) a'Union type; Union[X, Y] means either X or Y. To define a union, use e.g. Union[int, str]. Details: - The arguments must be types and there must be at least one. - None as an argument is a special case and is replaced by type(None). - Unions of unions are flattened, e.g.:: Union[Union[int, str], float] == Union[int, str, float] - Unions of a single argument vanish, e.g.:: Union[int] == int # The constructor actually returns int - Redundant arguments are skipped, e.g.:: Union[int, str, int] == Union[int, str] - When comparing unions, the argument order is ignored, e.g.:: Union[int, str] == Union[str, int] - You cannot subclass or instantiate a union. - You can use Optional[X] as a shorthand for Union[X, None]. r z Cannot take a Union of no types.z)Union[arg, ...]: each arg must be a type.c38K|]}t|VdSr rrrrs rrzUnion..s-??q{1c**??????rrrNrname)rryrrrrxrrrrs @rr"r"~s6R:;;; j% ( (# ] 5C????J?????J%j11J :!!} :!T j 8 8!$ DDDD dJ / //rc`t||d}t|tdfS)zEOptional type. Optional[X] is equivalent to Union[X, None]. z requires a single type.N)rr"rx)rrr{s rrrs1 jT"C"C"C D DC d4jj !!rc t|} tdttt |D}n#t $rYnwxYwt ||S)aSpecial typing form to define literal types (a.k.a. value types). This form can be used to indicate to type checkers that the corresponding variable or function parameter has a value equivalent to the provided literal (or one of several literals): def validate_simple(data: Any) -> Literal[True]: # always returns True ... MODE = Literal['r', 'rb', 'w', 'wb'] def open_helper(file: str, mode: MODE) -> str: ... open_helper('/some/path', 'r') # Passes type check open_helper('/other/path', 'typo') # Error in type checker Literal[...] cannot be subclassed. At runtime, an arbitrary value is allowed as type argument to Literal[...], but type checkers may impose restrictions. c3 K|] \}}|V dSr r )rrrs rrzLiteral..s&^^A1^^^^^^r)rrrr_value_and_type_iterrrr1s rrrs2)44J ^^d;OPZ;[;[6\6\)])]^^^^^       j 1 11sAA AAc&t|d)aSpecial marker indicating that an assignment should be recognized as a proper type alias definition by type checkers. For example:: Predicate: TypeAlias = Callable[..., bool] It's invalid when used anywhere except as in the example above. rErr1s rrprps t222 3 33rc0|dkrtdt|ts|f}|ddus*t|dtstddgfd|ddD|dR}t ||d S) aUsed in conjunction with ``ParamSpec`` and ``Callable`` to represent a higher order function which adds, removes or transforms parameters of a callable. For example:: Callable[Concatenate[int, P], int] See PEP 612 for detailed information. r z&Cannot take a Concatenate of no types.r.zMThe last parameter to Concatenate should be a ParamSpec variable or ellipsis.z/Concatenate[arg, ...]: each arg must be a type.c38K|]}t|VdSr rPrQs rrzConcatenate..s-AAAK3''AAAAAArNT_paramspec_tvars)rryrrrrUs @rrrsR@AAA j% ( (# ] rNc ! !Z 2 %J%J !:;; ; ;CRAAAACRCAAAR:b>RRJ #D*59 ; ; ;;rcJt||d}t||fS)aSpecial typing form used to annotate the return type of a user-defined type guard function. ``TypeGuard`` only accepts a single type argument. At runtime, functions marked this way should return a boolean. ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static type checkers to determine a more precise type of an expression within a program's code flow. Usually type narrowing is done by analyzing conditional code flow and applying the narrowing to a block of code. The conditional expression here is sometimes referred to as a "type guard". Sometimes it would be convenient to use a user-defined boolean function as a type guard. Such a function should use ``TypeGuard[...]`` as its return type to alert static type checkers to this intention. Using ``-> TypeGuard`` tells the static type checker that for a given function: 1. The return value is a boolean. 2. If the return value is ``True``, the type of its argument is the type inside ``TypeGuard``. For example:: def is_str(val: Union[str, float]): # "isinstance" type guard if isinstance(val, str): # Type of ``val`` is narrowed to ``str`` ... else: # Else, type of ``val`` is narrowed to ``float``. ... Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower form of ``TypeA`` (it can even be a wider form) and this may lead to type-unsafe results. The main reason is to allow for things like narrowing ``List[object]`` to ``List[str]`` even though the latter is not a subtype of the former, since ``List`` is invariant. The responsibility of writing type-safe type guards is left to the user. ``TypeGuard`` also works with type variables. For more information, see PEP 647 (User-Defined Type Guards). rJrKrLs rrqrqs/X zd#F#F#F G GD w ' ''rcHeZdZdZdZddddZdZd Zd Zd Z d Z d Z dS)rz-Internal wrapper to hold a forward reference.)__forward_arg____forward_code____forward_evaluated____forward_value____forward_is_argument____forward_is_class____forward_module__TNF)rwcFt|tstd||ddkrd|d}n|} t|dd}n #t$rt d|wxYw||_||_d |_d|_||_ ||_ ||_ dS) Nz*Forward reference must be a string -- got r*(z,)[0]zevalz/Forward reference must be an expression -- got F) ryrzrcompile SyntaxErrorrarbrcrdrerfrg)rr{rrvrwarg_to_compilecodes rr zForwardRef.__init__2s#s## RPPPQQ Q q6S==+^^^NN N Y>:v>>DD Y Y YWPSWWXX X Y # $%*"!%'2$$,!"(s AA-c|j|vr|S|jr||ur||ix}}n ||}n||}|j4ttj|jdd|}tt|j ||d|j |j }t|||||jhz|_ d|_|j S)N__dict__z*Forward references must evaluate to types.)rrtT)rarcrgrsysmodulesgetrrkrbrerfrrd)rrrrtype_s rrzForwardRef._evaluateJs  ? 2 2K) .WH-D-DGO%''77!""&2"KOOD$;TBBJPX T*Hg>>< 8$($= E &0x/T=Q 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. NFrrrcJ||_t||||r|td|r"t |dkrtddt fd|D|_t}|dkr ||_dSdS)Nz-Constraints cannot be combined with bound=...rRz"A single constraint is not allowedz:TypeVar(name, constraint, ...): constraints must be types.c38K|]}t|VdSr rP)rrrs rrz#TypeVar.__init__..s-$N$NQ[C%8%8$N$N$N$N$N$Nrtyping) rr9r rrr__constraints___callerr) rrTrrr constraintsdef_modrr:s @rr zTypeVar.__init__s   =999  M5,KLL L  B3{++q00@AA AJ$$N$N$N$N+$N$N$NNN)) h  %DOOO  rcd}t||d}t|tr|jtus&t|t r#t |ddrt|d|S)N*Parameters to generic types must be types.T)rrFr~)rryrrrrr rr)rr{rs rrzTypeVar.__typing_subst__s~:#s555 ] + + D&0H0H \ * *1I/6sNE/R/R1IsBBBCC C r)rrrrr rr=r>s@rr r sf))V26  & & & & & & &rr c0eZdZdZdZdZdZdZdZdS)r!a~Type variable tuple. Usage: Ts = TypeVarTuple('Ts') # Can be given any name Just as a TypeVar (type variable) is a placeholder for a single type, a TypeVarTuple is a placeholder for an *arbitrary* number of types. For example, if we define a generic class using a TypeVarTuple: class C(Generic[*Ts]): ... Then we can parameterize that class with an arbitrary number of type arguments: C[int] # Fine C[int, str] # Also fine C[()] # Even this is fine For more details, see PEP 646. Note that only TypeVarTuples defined in global scope can be pickled. cN||_t}|dkr ||_dSdSNr)rrr)rrTrs rr zTypeVarTuple.__init__s2 )) h  %DOOO  rc#(Kt|VdSr rrrs rrzTypeVarTuple.__iter__Tlrc|jSr rrs rrzTypeVarTuple.__repr__rrc td)Nz2Substitution of bare TypeVarTuple is not supportedrrr{s rrzTypeVarTuple.__typing_subst__sLMMMrc "|j}||}||dzdD])}t|trt d|*t |}t |}|}||z dz } d} d} t |D]e\} } t| tsKt| dd}|r8t |dkr%|ddur| t d| } |d} f| 't|| }t| || z dz } n$|| z|krt d |d |d |dz g|d|| g||z zt|||| z | g|| z |z |z dz z||| z dRS) NrRz(More than one TypeVarTuple parameter in rrr.z6More than one unpacked arbitrary-length tuple argumentrToo few arguments for rz, expected at least ) rindexryr!rr enumeraterxrminr)raliasrrtypevartuple_indexparamrplenrrvar_tuple_indexfillargkr{rs r__typing_prepare_subst__z%TypeVarTuple.__typing_prepare_subst__!sF%#\\$//.2334 T TE%.. T R5 R RSSS T4yy6{{!))A-oo ) )FAsc4(( )!#'GNN)s7||q00WR[C5G5G&2'(`aaa&'O%ajG  &t_--Dto59::EE E\D JUJJ'+JJAEaJJKK K %4%[ i+d23  $tTE\)* + + i,/AAAEF  $,--    rN) rrrrr rrrrr rrr!r!sl0&&&NNN" " " " " rr!c$eZdZdZdZdZdZdS)rha<The args for a ParamSpec object. Given a ParamSpec object P, P.args is an instance of ParamSpecArgs. ParamSpecArgs objects have a reference back to their ParamSpec: P.args.__origin__ is P This type is meant for runtime introspection and has no special meaning to static type checkers. c||_dSr rrorigins rr zParamSpecArgs.__init__R  rc |jjdS)Nz.argsrrrs rrzParamSpecArgs.__repr__Us/*1111rcZt|tstS|j|jkSr )ryrhrwrr"s rrxzParamSpecArgs.__eq__Xs*%// "! !%"222rNrrrrr rrxr rrrhrhFsK  !!!22233333rrhc$eZdZdZdZdZdZdS)riaFThe kwargs for a ParamSpec object. Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs. ParamSpecKwargs objects have a reference back to their ParamSpec: P.kwargs.__origin__ is P This type is meant for runtime introspection and has no special meaning to static type checkers. c||_dSr rrs rr zParamSpecKwargs.__init__jrrc |jjdS)Nz.kwargsrrs rrzParamSpecKwargs.__repr__ms/*3333rcZt|tstS|j|jkSr )ryrirwrr"s rrxzParamSpecKwargs.__eq__ps*%11 "! !%"222rNrr rrriri^sK  !!!44433333rricdeZdZdZedZedZddddfd ZdZd Z xZ S) raqParameter specification variable. Usage:: P = ParamSpec('P') Parameter specification variables exist primarily for the benefit of static type checkers. They are used to forward the parameter types of one callable to another callable, a pattern commonly found in higher order functions and decorators. They are only valid when used in ``Concatenate``, or as the first argument to ``Callable``, or as parameters for user-defined Generics. See class Generic for more information on generic types. An example for annotating a decorator:: T = TypeVar('T') P = ParamSpec('P') def add_logging(f: Callable[P, T]) -> Callable[P, T]: '''A type-safe decorator to add logging to a function.''' def inner(*args: P.args, **kwargs: P.kwargs) -> T: logging.info(f'{f.__name__} was called') return f(*args, **kwargs) return inner @add_logging def add_two(x: float, y: float) -> float: '''Add two numbers together.''' return x + y Parameter specification variables defined with covariant=True or contravariant=True can be used to declare covariant or contravariant generic types. These keyword arguments are valid, but their actual semantics are yet to be decided. See PEP 612 for details. Parameter specification variables can be introspected. e.g.: P.__name__ == 'P' P.__bound__ == None P.__covariant__ == False P.__contravariant__ == False Note that only parameter specification variables defined in global scope can be pickled. c t|Sr )rhrs rrzParamSpec.argssT"""rc t|Sr )rirs rrBzParamSpec.kwargsst$$$rNFrc||_t|||t}|dkr ||_dSdSr)rr9r rr)rrTrrrrr:s rr zParamSpec.__init__sM   =999)) h  %DOOO  rct|ttfrtd|D}n!t|st d||S)Nc36K|]}t|dVdS)zExpected a type.NrPrrs rrz-ParamSpec.__typing_subst__..s-HHq A'9::HHHHHHrzFExpected a list of types, an ellipsis, ParamSpec, or Concatenate. Got )ryrrrrrs rrzParamSpec.__typing_subst__sw cD%= ) ) EHHCHHHHHCC$$ ED>ADDEE E rc|j}||}|t|krtd|t|dkr!t |ds |dksJ|f}nJt ||t r/g|d|t||||dzdR}|S)NrrRr)rrrrrryrr)rrrris rrz"ParamSpec.__typing_prepare_subst__s% LL   D >>s@rrrvs++Z##X#%%X%'+e5&&&&&&&       rrcV|do|dS)N__) startswithendswith)attrs r _is_dunderrs% ??4 8T]]4%8%88rcXeZdZdZddddZdZdZdZfd Zd Z d Z fd Z xZ S) _BaseGenericAliasaThe central part of internal API. This represents a generic version of type 'origin' with type arguments 'params'. There are two kind of these aliases: user defined and special. The special ones are wrappers around builtin collections and ABCs in collections.abc. These must have 'name' always set. If 'inst' is False, then the alias can't be instantiated, this is used by e.g. typing.List and typing.Dict. TNinstrTc>||_||_||_d|_dSr )_instrrr)rrrrTs rr z_BaseGenericAlias.__init__s"   rc|js%td|jd|jjd|j|i|} ||_n#t $rYnwxYw|S)NzType z cannot be instantiated; use z () instead)rrrrr__orig_class__r)rrrBresults rrz_BaseGenericAlias.__call__sz IHDJHH#'?#;HHHII I $1&11 $(F ! !    D  sA AAc@g}|j|vr||j||}||dzdD].}t|tst |t rn/|t t|SNrR)rrrryr issubclassrr)rrresrbs rrz!_BaseGenericAlias.__mro_entries__s ?% ' ' JJt ' ' ' KK  qstt  A!.// :a3I3I   JJw   Szzrc|dvr|jp |jjSd|jvr$t |st |j|St |)N>rrr)rrrrqrrr)rrs rrz_BaseGenericAlias.__getattr__s\ / / /:9!9 9 4= ( (D1A1A (4?D11 1T"""rct|s|dvr$t||dSt|j||dS)N>rr_nparamsr^)rr9 __setattr__setattrr)rrvalr:s rrz_BaseGenericAlias.__setattr__s^ d   0t(< < < GG  c * * * * * DOT3 / / / / /rcF|t|Sr r/rxr*s rr+z#_BaseGenericAlias.__instancecheck__%%d3ii000rc td)NzBSubscripted generics cannot be used with class and instance checksrr.s rr/z#_BaseGenericAlias.__subclasscheck__s566 6rc tttdt |jDzS)Nc0g|]}t||Sr )r)rrs r z-_BaseGenericAlias.__dir__.. s%QQQD 4@P@PQ4QQQr)rrr9__dir__dirrr<s rrz_BaseGenericAlias.__dir__ sWC))QQC$8$8QQQRSSTT Tr) rrrrr rrrrr+r/rr=r>s@rrrs(,$      ###00000111666TTTTTTTTTrrc~eZdZddddfd ZdZdZdZd Zed Z d Z d Z d Z dZ fdZdZxZS)rTNF)rrTr^ct|||t|ts|f}td|D|_t ||_||_|s|j|_dSdS)Nrc30K|]}|turdn|VdS).N)_TypingEllipsisrs rrz)_GenericAlias.__init__..:sE//$%&'/%9%9cc//////r) r9r ryrrrrr^r)rrrrrTr^r:s rr z_GenericAlias.__init__5s d666$&& 7D//)-///// 1$77 0 0$/DOOO 0 0rczt|tstS|j|jko|j|jkSr )ryrrwrrr"s rrxz_GenericAlias.__eq__As=%// "! !5#334MU^3 5rc8t|j|jfSr )rzrrrs rr{z_GenericAlias.__hash__GsT_dm4555rc t||fSr r!rs rr$z_GenericAlias.__or__Jr%rc t||fSr r!rs rr'z_GenericAlias.__ror__MrrcZ|jttfvrtd||jst|dt |t s|f}t d|D}t|}||}| |}|S)Nz%Cannot subscript already-subscripted rc34K|]}t|VdSr r|rrs rrz,_GenericAlias.__getitem__..js*44!]1%%444444r) rrrrrryrr_determine_new_argsr)rrnew_argsrs rr2z_GenericAlias.__getitem__Ps" ?w1 1 1JDJJKK K" >t<<<== =$&& 7D44t44444D!!++D11 NN8 $ $rc |j}|D]!}t|dd}| |||}"t|}t|}||kr#td||krdndd|d|d|t t ||}g}|jD]R} t| tr| | .t| dd} | r| || } n~t| d d } | s| } nhg} | D]N}t|tr| ||3| ||O| t| } |j tjjkr,t| tr| | t#| r| | =| | Tt|S) Nrrrrrrrrrr )rrrrdictziprryrxrr!rrrrrrr)rrrrpreparerrnew_arg_by_paramrold_arg substfuncnew_arg subparamsrrs rrz!_GenericAlias._determine_new_argspsT$ + +Ee%?FFG"wtT**4yy6{{ 4<<?TD[[66e??TX??'+??8<??@@ @FD 1 122}. ). )G'4(( ((();TBBI 6#)$4W$=>>#G-=rBB  6%GG G&@@%a66@#NN+;A+>????#NN+;A+>????%eGnn5G+/":::z'SX?Y?Y:((((*733 )((((((((Xrc^||j||j|j|jS)NrTrr^)r:rrrr^rrs rrz_GenericAlias.copy_withs4~~dot$*4:/3/DFF Frc|jr d|jz}nt|j}|jr%dd|jD}nd}|d|dS)Nr, c,g|]}t|Sr rrs rrz*_GenericAlias.__repr__..sCCCjmmCCCrz()[])rrrrjoin)rrTrs rrz_GenericAlias.__repr__su : /tz)DDdo..D = 99CCT]CCCDDDDD      rc|jrt|j}n|j}t|j}t |dkrt |dts|\}tj||ffSNrRr) rglobalsrrrrryrr )rrrs rrz_GenericAlias.__reduce__sn : %YYtz*FF_FT]## t99>>*T!We"<"<>ED&$//rcpt|jtrtd||jr!t |S|jturLt|vrdS| |}||dzdD]}t|tr||urdS|jfS)Nrr rR) ryrrrrr9rrrrr)rrrrr:s rrz_GenericAlias.__mro_entries__s do| 4 4 97t7788 8 : 277**511 1 ?g % %5  r D!!A1Q344[  a!233 22!!rc#(Kt|VdSr rrs rrz_GenericAlias.__iter__rr)rrrr rxr{r$r'rr2rrrrrrr=r>s@rrrs4.2"' 0 0 0 0 0 0 0555 666"""!!!Y>MMM^FFF ! ! !000 " " " " "rrcdeZdZdddfd ZedZdZdZfdZd Z d Z d Z xZ S) _SpecialGenericAliasTNrc||j}t|||||_|jdkrd|jd|_dSd|jd|jd|_dS)NrrzA generic version of r)rr9r rrrr)rrnparamsrrTr:s rr z_SpecialGenericAlias.__init__s <?D d666   * *I63FIIIDLLL]63D]]vGZ]]]DLLLrct|ts|f}dtfd|D}t|||j||S)Nrc38K|]}t|VdSr rPrQs rrz3_SpecialGenericAlias.__getitem__..-;;q{1c**;;;;;;r)ryrrrrrrrs @rr2z _SpecialGenericAlias.__getitem__si&%(( YF:;;;;F;;;;;tVT]333~~f%%%rcFt|j||j|jS)N)rTr)rrrrrrs rrz_SpecialGenericAlias.copy_withs(T_f"&*4:??? ?rcd|jzSrrrs rrz_SpecialGenericAlias.__repr__rrct|trt|j|jSt|tst||jSt |Sr )ryr*rrrr9r/)rrr:s rr/z&_SpecialGenericAlias.__subclasscheck__ sf c/ 0 0 ?cndo>> >#}-- 4c4?33 3ww((---rc|jSr rrs rrz_SpecialGenericAlias.__reduce__rrc t||fSr r!rs rr$z_SpecialGenericAlias.__or__r%rc t||fSr r!rs rr'z_SpecialGenericAlias.__ror__rr) rrrr rr2rrr/rr$r'r=r>s@rr*r*s044^^^^^^^&&Y&???&&&....."""!!!!!!!rr*c$eZdZfdZdZxZS)_CallableGenericAliasc>|jdksJ|j}t|dkr5t|dr t Sddd|ddDdt|dd S) Nrrrztyping.Callable[[rc,g|]}t|Sr r rs rrz2_CallableGenericAlias.__repr__.."sAAA! 1 AAArrz], r")rrrrr9rr#rrrr:s rrz_CallableGenericAlias.__repr__szZ''''} t99>>nT!W55>77##%% %+YYAAtCRCyAAABB++d2h''+++ ,rc|j}t|dkrt|dst|dd|df}tjt |ffS)Nrrr)rrrrrr rrs rrz _CallableGenericAlias.__reduce__%sW}D Q>$q'#:#:SbS ??DH,D(D!111r)rrrrrr=r>s@rr9r9sG,,,,,2222222rr9c0eZdZdZdZedZdS) _CallableTypecHt|j||j|jdS)NTr)r9rrrr2s rrz_CallableType.copy_with-s+$T_f*.*4:6:<<< .Is*88C]3''888888r)rEllipsisrrryr)rrrrrs rrBz_CallableType.__getitem_inner__@s f>VS)) 8  >>?F";<< <$&& 7D88488888 !~~f%%%rN)rrrrr2rrBr rrr?r?,sM<<< . . . & &Y & & &rr?c$eZdZedZdS) _TupleTypecZt|ts|f}t|dkrN|ddurDdtfd|ddD}|g|tRSdtfd|D}||S)Nrr.z Tuple[t, ...]: t must be a type.c38K|]}t|VdSr rPrQs rrz)_TupleType.__getitem__..Us-DD1;q#..DDDDDDrz*Tuple[t0, t1, ...]: each t must be a type.c38K|]}t|VdSr rPrQs rrz)_TupleType.__getitem__..Xr/r)ryrrrrr0s @rr2z_TupleType.__getitem__Os&%(( YF v;;!  r c 1 14CDDDDss DDDDDF>>">Aw$t**$$@*T!W*=*=@@@@aDJJ&&@*T!W*=*=@@@@ww!!!rcF|t|Sr rr*s rr+z$_UnionGenericAlias.__instancecheck__qrrc@|jD]}t||rdSdS)NT)rr)rrr{s rr/z$_UnionGenericAlias.__subclasscheck__ts;=  C#s## tt   rcft\}\}}|t|ffSr )r9rr")rrrrr:s rrz_UnionGenericAlias.__reduce__ys0$ww1133nvteT]""r) rrrrrxr{rr+r/rr=r>s@rrr\s999 ..."""""111 #########rrcd|DS)Nc38K|]}|t|fVdSr )rxr s rrz'_value_and_type_iter..s, - -QQQL - - - - - -rr )rs rrYrY~s - -* - - --rceZdZdZdZdS)rct|tstStt |jtt |jkSr )ryrrwrrYrr"s rrxz_LiteralGenericAlias.__eq__sN%!566 "! !' 66773?STYTb?c?c;d;dddrc^ttt|jSr )rzrOrYrrs rr{z_LiteralGenericAlias.__hash__s#I24=AABBCCCrN)rrrrxr{r rrrrs:eee DDDDDrrceZdZfdZxZS)rct|dttfrg|dd|dRSt|dtrg|dd|djR}t |S)Nr)ryrrrrr9r)rrr:s rrz"_ConcatenateGenericAlias.copy_withs fRj4- 0 0 /.VCRC[.6":.. . fRj": ; ; :9vcrc{9VBZ%899Fww  (((r)rrrrr=r>s@rrrs8)))))))))rrcLt||d}t||fS)aType unpack operator. The type unpack operator takes the child types from some container type, such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'. For example: # For some generic class `Foo`: Foo[Unpack[tuple[int, str]]] # Equivalent to Foo[int, str] Ts = TypeVarTuple('Ts') # Specifies that `Bar` is generic in an arbitrary number of types. # (Think of `Ts` as a tuple of an arbitrary number of individual # `TypeVar`s, which the `Unpack` is 'pulling out' directly into the # `Generic[]`.) class Bar(Generic[Unpack[Ts]]): ... Bar[int] # Valid Bar[int, str] # Also valid From Python 3.11, this can also be done using the `*` operator: Foo[*tuple[int, str]] class Bar(Generic[*Ts]): ... Note that there is only some runtime checking of this operator. Not everything the runtime allows may be accepted by static type checkers. For more information, see PEP 646. rJ)rr)r_UnpackGenericAliasrLs rrrrrs1< zd#F#F#F G GD d$ 9 9 99rcPeZdZdZfdZedZedZxZS)r\c<dt|jdzS)Nrir)rrrs rrz_UnpackGenericAlias.__repr__sT$-*++++rcX|jr|St|Sr )rr9r2r<s rr2z_UnpackGenericAlias.__getitem__s+  3 Kww""4(((rc|jtusJt|jdksJ|j\}t |t r|jt usJ|jSdSr)rrrrrryrrrs rrz2_UnpackGenericAlias.__typing_unpacked_tuple_args__sk&((((4=!!Q&&&&} c= ) ) >U****< trc|jtusJt|jdksJt |jdt Sr%)rrrrrryr!rs rrz7_UnpackGenericAlias.__typing_is_unpacked_typevartuple__sG&((((4=!!Q&&&&$-*L999r) rrrrr2rrrr=r>s@rr\r\s},,, ))))) X::X:::::rr\c@eZdZdZdZdZedZfdZxZ S)raCAbstract base class for generic types. A generic type is typically declared by inheriting from this class parameterized with one or more type variables. For example, a generic mapping type might be defined as:: class Mapping(Generic[KT, VT]): def __getitem__(self, key: KT) -> VT: ... # Etc. This class can then be used as follows:: def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT: try: return mapping[key] except KeyError: return default r Fc:t|ts|f}td|D}|ttfvr|st d|jdt d|Dst d|jdtt|t|krt d|jdn|j D]!}t|dd }| |||}"t||t|j g}t|j |D]E\}}t|tr||0||Ft|}t#||d S) aParameterizes a generic class. At least, parameterizing a generic class is the *main* thing this method does. For example, for some generic class `Foo`, this is called when we do `Foo[int]` - there, with `cls=Foo` and `params=int`. However, note that this method is also called when defining generic classes in the first place with `class Foo(Generic[T]): ...`. c34K|]}t|VdSr r r s rrz,Generic.__class_getitem__..s*88A}Q''888888rzParameter list to z[...] cannot be emptyc34K|]}t|VdSr )rr s rrz,Generic.__class_getitem__..s+;;q'**;;;;;;rzParameters to zF[...] must all be type variables or parameter specification variables.z[...] must all be uniquerNTr])ryrrrrrallrrrrrrrr!rrr)rrrrrrs r__class_getitem__zGeneric.__class_getitem__s&%(( YF8888888 7H% % % P)9PPP;;F;;;;; >=S\===>>>3v;;3v;;..KS\KKKMMM/ + 2 2!%)CTJJ&$WS&11F 3C,>(?(? @ @ @H"%c&8&"A"A - -we\22-OOG,,,,OOG,,,,8__FS&.2444 4rc tj|i|g}d|jvrt|jv}n1t|jvo"|jdkot|tk}|rtdd|jvrt|j}d}|jD]=}t|tr&|j tur|td|j}>||t|}t| | ksVd fd|D}dd|D} td|d | d |}t#||_dS) N__orig_bases__rz!Cannot inherit from plain Genericz0Cannot inherit from Generic[...] multiple types.rc3>K|]}|vt|VdSr rz)rrgvarsets rrz,Generic.__init_subclass__..:s3&Q&Q!@P@Ps1vv@P@P@P@P&Q&Qrc34K|]}t|VdSr rk)rgs rrz,Generic.__init_subclass__..;s(&=&=!s1vv&=&=&=&=&=&=rzSome type variables (z) are not listed in Generic[r")r9rrqrri __bases__rrx_TypedDictMetarrryrrrrr#r) rrrBtvarserrorgvarsbasetvarsets_varss_argsrlr:s @rrzGeneric.__init_subclass__s!!426222 s| + +s11EE -4 24S ^3   A?@@ @ s| + +'(:;;E E* 0 0t]330722('NPPP /E e**e**'))!YY&Q&Q&Q&Qu&Q&Q&QQQF!YY&=&=u&=&=&===F#%HF%H%H>D%H%H%HIII"5\\r) rrrrr _is_protocolrrgrr=r>s@rrrsh&IL,4,4Y,4\#*#*#*#*#*#*#*#*#*rrceZdZdZdS)rz(Internal placeholder for ... (ellipsis).N)rrrrr rrrrBs2222rr)rrirrx_is_runtime_protocol) __abstractmethods____annotations__rqrr rrAr__subclasshook__rrg_MutableMapping__markercxt}|jddD]}|jdvr t|di}t |jt |zD]5}|ds|tvr| |6|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)rrr|_abc_) r__mro__rrrrqkeysrEXCLUDED_ATTRIBUTESadd)rattrsrt annotationsrs r_get_protocol_attrsrQs EEE CRC    =3 3 3 d$5r:: ++--..k6F6F6H6H1I1II  D??7++ .ds7WWdxT40011WWWWWWr)rfrrs`r_is_callable_members_onlyrbs0 WWWW>QRU>V>VWWW W WWrc,t|}|jrtd|jturdS|jD]4}|jdt}|tur ||_n5tj|_|j|g|Ri|dS)Nz Protocols cannot be instantiatedr ) rxrxrr _no_init_or_replace_initrrqrtobject)rrrBrrtinits rrrgs t**C <:;;; |333 ''}  -EFF / / /CL E 0  CL'''''''''rrR__main__c tj|dzjd|S#tt f$rYdSwxYw)NrRr)rr _getframe f_globalsrtrr)depthdefaults rrrsU}UQY''155j'JJJ J 'tts/2AAc$t|dvS)zAllow instance and class checks for special stdlib modules. The abc and functools modules indiscriminately call isinstance() and issubclass() on the whole MRO of a user class, which may contain protocols. >Nrr)rrs r_allow_reckless_class_checksrs 5>>7 77r) rr4r)r*r6r'r2r%r8r;AbstractContextManagerAbstractAsyncContextManager)zcollections.abc contextlibceZdZfdZxZS) _ProtocolMetactddr0tddstdstdtddrtrt jrdSjr+tfdtDrdSt S) NrxFrzrrLInstance and class checks can only be used with @runtime_checkable protocolsTc3K|]E}t|o0tt|d pt|duVFdSr )rrr)rrrinstances rrz2_ProtocolMeta.__instancecheck__..sy:: 8T**:!'#tT":":;;;9Xt,,D8::::::r) rrrrrr:rxrfrr9r+)rrr:s``rr+z_ProtocolMeta.__instancecheck__s C / / =3U;; =-1555 = <== =ne44 )#.. 8-s33 4   :::::!4C 8 8 :::::  tww((222r)rrrr+r=r>s@rrrs8333333333rrc.eZdZdZdZdZdZfdZxZS)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: ... r TFctj|i|jdds#t djD_fd}djvr|_jsdSjD]g}|ttfvsU|j tvr|j t|j vs.t|tr|jstd|zhjt jurt"_dSdS)NrxFc3(K|] }|tuVdSr )rrrs rrz-Protocol.__init_subclass__..s&"H"HQ1="H"H"H"H"H"HrcjddstStdds$t rtSt dt s$t rtSt dt|tst dtD]}|j D]w}||jvr|j| tccSn\t|di}t|tj j r"||vrt|tr |jrn xtcSdS) NrxFrzrz._proto_hooks<##NE:: &%%3 6>> A/11*))!@AAA,S11 ?/11*))!>???eT** F DEEE,C00 * *!M**Dt},,=.6#111111#*$0A2"F"FK"; 0GHH K//&ug660;@;M0))))4rr}z7Protocols can only inherit from other protocols, got %r)r9rrqrtanyrorxr}rrr_PROTO_ALLOWLISTrrrr rr)rrrBrrtr:s` rrzProtocol.__init_subclass__sI!!426222|66 I""H"H#-"H"H"HHHC $ $ $ $ $ L S\ 1 1#.C   FM = =DVW---O'777M%5do%FFFtW--G262CG!57;!<=== <8, , ,3CLLL - ,r) rrrrrrxrzrr=r>s@rrrsT:IL >4>4>4>4>4>4>4>4>4rrcJeZdZdZfdZdZdZdZdZdZ fdZ xZ S) _AnnotatedAliasa7Runtime representation of an annotated type. At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't' with extra annotations. The alias behaves like a normal typing alias, instantiating is the same as instantiating the underlying type, binding it to types is also the same. ct|tr|j|z}|j}t ||||_dSr )ryr __metadata__rr9r )rrmetadatar:s rr z_AnnotatedAlias.__init__$sR fo . . '*X5H&F ((($rcft|dksJ|d}t||jSr%)rrr)rrnew_types rrz_AnnotatedAlias.copy_with+s56{{a!9x):;;;rcdt|jdd|jDS)Nztyping.Annotated[{}, {}]rc34K|]}t|VdSr )rrs rrz+_AnnotatedAlias.__repr__..3s(99!d1gg999999r)formatrrr#rrs rrz_AnnotatedAlias.__repr__0sH)00 t ' ' II99t'8999 9 9   rcHtjt|jf|jzffSr )rr rrrrs rrz_AnnotatedAlias.__reduce__6s) )D,=="   rczt|tstS|j|jko|j|jkSr )ryrrwrrr"s rrxz_AnnotatedAlias.__eq__;s?%11 "! !5#33<%);; =rc8t|j|jfSr )rzrrrs rr{z_AnnotatedAlias.__hash__AsT_d&78999rcR|dvrdSt|S)N>rrr)r9r)rrr:s rrz_AnnotatedAlias.__getattr__Ds, / / /;ww""4(((r) rrrrr rrrrxr{rr=r>s@rrrs%%%%%<<<       === :::)))))))))rrc8eZdZdZdZdZedZdZdS)raAdd context specific metadata to a type. Example: Annotated[int, runtime_check.Unsigned] indicates to the hypothetical runtime_check module that this type is an unsigned int. Every other consumer of this type can ignore this metadata and treat this type as int. The first argument to Annotated must be a valid type. Details: - It's an error to call `Annotated` with less than two arguments. - Nested Annotated are flattened:: Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3] - Instantiating an annotated type is equivalent to instantiating the underlying type:: Annotated[C, Ann1](5) == C(5) - Annotated can be used as a generic type alias:: Optimized = Annotated[T, runtime.Optimize()] Optimized[int] == Annotated[int, runtime.Optimize()] OptimizedList = Annotated[List[T], runtime.Optimize()] OptimizedList[int] == Annotated[List[int], runtime.Optimize()] - Annotated cannot be used with an unpacked TypeVarTuple:: Annotated[*Ts, Ann1] # NOT valid This would be equivalent to Annotated[T1, T2, T3, ..., Ann1] where T1, T2 etc. are TypeVars, which would be invalid, because only one type should be passed to Annotated. r c td)Nz&Type Annotated cannot be instantiated.rrrrBs rrAzAnnotated.__new__vs@AAArc:t|trt|dkrtdt |drtdd}t |d|d}t|dd}t ||S) NrzUAnnotated[...] should be used with at least two arguments (a type and an annotation).rz?Annotated[...] should not be used with an unpacked TypeVarTuplez$Annotated[t, ...]: t must be a type.TrsrR)ryrrrrrr)rrrrrs rrgzAnnotated.__class_getitem__ys&%(( ,CKK!OO+,, , %VAY / / 5455 54VAYFFF$$vx000rcPtd|j)NzCannot subclass {}.Annotated)rrrrs rrzAnnotated.__init_subclass__s' * 1 1#. A A   rN) rrrrrrArrgrr rrrrJsb''RIBBB 1 1Y 1     rrcpt|tr|jstd|zd|_|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)rrrxrrzrs rrlrlsL$ c7 # #)3+;)"$'()) )#C Jrc|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). r )rrs rrWrWs  Jrc|S)aAsk a static type checker to confirm that the value is of the given type. When the type checker encounters a call to assert_type(), it emits an error if the value is not of the specified type:: def greet(name: str) -> None: assert_type(name, str) # ok assert_type(name, int) # type checker error At runtime this returns the first argument unchanged and otherwise does nothing. r )rrs rrUrUs  Jrct|ddriSt|tr=i}t|jD]}|5tt j|jddi}n|}|j di}t|tj ri}|tt|n|}||||}}|D]S\} } | td} t| trt!| dd} t#| ||} | || <T|r|nd|DS|at|tjr|j }n:|} t'| d r| j} t'| d t| d i}||}n||}t|dd}|9t|t*riSt-d |t|}|D]j\} } | td} t| tr+t!| t|tj d} t#| |||| <k|r|nd |DS) a Return type hints for an object. This is often the same as obj.__annotations__, but it handles forward references encoded as string literals and recursively replaces all 'Annotated[T, ...]' with 'T' (unless 'include_extras=True'). The argument may be a module, class, method, or function. The annotations are returned as a dictionary. For classes, annotations include also inherited members. TypeError is raised if the argument is not of a type that can contain annotations, and an empty dictionary is returned if no annotations are present. BEWARE -- the behavior of globalns and localns is counterintuitive (unless you are familiar with how eval() and exec() work). The search order is locals first, then globals. - If no dict arguments are passed, an attempt is made to use the globals from obj (or the respective module's globals for classes), and these are also used as the locals. If the object does not appear to have globals, an empty dictionary is used. For classes, the search order is globals first then locals. - If one dict argument is passed, it is used for both globals and locals. - If two dict arguments are passed, they specify globals and locals, respectively. __no_type_check__Nrqr|FT)rrwc4i|]\}}|t|Sr _strip_annotationsrrrs r z"get_type_hints.. s',`,`,`$!QQ0B10E0E,`,`,`r __wrapped__ __globals__z1{!r} is not a module, class, method, or function.c4i|]\}}|t|Sr rrs rrz"get_type_hints..' s'(\(\(\da,>q,A,A(\(\(\r)rryrxreversedrrrrsrtrrqrGetSetDescriptorTypervarsitemsrzrr ModuleTyperr_allowed_typesrr) rrrinclude_extrashintsrt base_globalsann base_localsrTvaluensobjs rr^r^s@s'.. #taS[)) $ $D&s{t'M'Mz[]^^ ' -##$5r::C#u9:: .5o$tDzz***7K8#3-8k "yy{{ $ $ e= JJEeS))P&u%$OOOE"5, DD#d  $'`uu,`,`RWR]R]R_R_,`,`,`` c5+ , , 9|HHE%// *)%// *umR88H ?G  C*D 1 1E } c> * * 8I++16#;;88 8 KKE{{}} ; ; e =JJE eS ! !  *30@ A AAE !'::d " \55(\(\ekkmm(\(\(\\rct|trt|jSt |dr/|jt t fvrt|jdSt|tr@td|jD}||jkr|S| |St|tr@td|jD}||jkr|St|j|St|tj rJtd|jD}||jkr|Stjt j|S|S)z.Strips the annotations from a given type. rrc34K|]}t|VdSr rrs rrz%_strip_annotations..2 +HH033HHHHHHrc34K|]}t|VdSr rrs rrz%_strip_annotations..7 rrc34K|]}t|VdSr rrs rrz%_strip_annotations..< rr)ryrrrrrjrfrrrrr rrrrrr)r stripped_argss rrr* sc!_%%0!!,///q,1ALX{4K$K$K!!*Q-000!]##*HHQZHHHHH AJ & &H{{=)))!\""9HHQZHHHHH AJ & &HAL-888!U_%%=HHQZHHHHH AJ & &H m<<< Hrct|trtSt|ttt t fr|jS|turtSt|tj r tj SdS)a Get the unsubscripted version of a type. This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar and Annotated. Return None for unsupported types. Examples:: get_origin(Literal[42]) is Literal get_origin(int) is None get_origin(ClassVar[int]) is ClassVar get_origin(Generic) is Generic get_origin(Generic[T]) is Generic get_origin(Union[T, int]) is Union get_origin(List[Tuple[T, T]][int]) == list get_origin(P.args) is P N) ryrrrr rhrirrrrtps rr\r\D sv"o&&"(,$o788} W}}"eo&& 4rc:t|tr|jf|jzSt|tt fr8|j}t||rt|dd|df}|St|tj r|jSdS)aGet type arguments with all substitutions performed. For unions, basic simplifications used by Union constructor are performed. Examples:: get_args(Dict[str, int]) == (str, int) get_args(int) == () get_args(Union[int, Union[T, int], str][int]) == (int, str) get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int]) get_args(Callable[[], T][int]) == ([], int) Nrr ) ryrrrrr rrrrr)rrs rr[r[_ s"o&&2 "/11"}l344k *2s 3 3 ,CRC>>3r7+C "eo&&{ 2rc,t|tS)zCheck if an annotation is a TypedDict class For example:: class Film(TypedDict): title: str year: int is_typeddict(Film) # => True is_typeddict(Union[list, str]) # => False )ryrprs rr_r_v s b. ) ))rdr{ct|}t|tkr|dtdz}td|)aStatically assert that a line of code is unreachable. Example:: def int_or_str(arg: int | str) -> None: match arg: case int(): print("It's an int") case str(): print("It's a str") case _: assert_never(arg) If a type checker finds that a call to assert_never() is reachable, it will emit an error. At runtime, this throws an exception when called. Nrz*Expected code to be unreachable, but got: )rr_ASSERT_NEVER_REPR_MAX_LENGTHAssertionError)r{rs rrVrV sN( IIE 5zz1114445= MeMM N NNrct|trt|D]}t||}t |dr4|j|jd|jkst|dd|jkrWt|tj rd|_ t|tj r d|j _ t|trt| d|_ n#t$rYnwxYw|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. rrrNT)ryrxrrrrrrrrr MethodType__func__rcr)r{keyrs rrcrc s#t#s88 # #C#s##CC00 ##*:'K'KS\'K'KKK3 d33s~EE #u122 -(,%#u/00 615 .#t$$ #c""" $      Js)C11 C>=C>cFtjfd}|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. c6|i|}t|}|Sr )rc)rrrrs rwrapped_decoratorz2no_type_check_decorator..wrapped_decorator s)y$'$''T"" r)rr)rrs` rrdrd s;_Y  rc td)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.)NotImplementedError)rrs r_overload_dummyr s  9 : ::rct|d|} |t|j|j|jj<n#t $rYnwxYwtS)apDecorator 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 The overloads for a function can be retrieved at runtime using the get_overloads() function. r)r_overload_registryrr__code__co_firstlinenorr)rfs rrgrg sc< j$''A VZ1<(89RSS       s*> A  A ct|d|}|jtvrgSt|j}|j|vrgSt ||jS)z6Return all defined overloads for *func* as a sequence.r)rrrrrvalues)rrmod_dicts rr]r] sg j$''A|--- !!,/H~X%% (//11 2 22rc8tdS)z$Clear all overloads in the registry.N)rclearr rrrXrX srcF d|_n#ttf$rYnwxYw|S)aA 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. The decorator sets the ``__final__`` attribute to ``True`` on the decorated object to allow runtime introspection. T) __final__rr)rs rrZrZ s>2  I &      Hs  TKTVTT_co)rV_coVT_coT_contra)rCT_co)rrrTraCallable 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. r#rSrrra@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, ...]. rHrErJrKr&r:rFrGraA 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. c2eZdZdZdZedefdZdS)rAz(An ABC with one abstract method __int__.r rcdSr r rs r__int__zSupportsInt.__int__  rN)rrrrrrintrr rrrArA sD22I    ^   rrAc2eZdZdZdZedefdZdS)r?z*An ABC with one abstract method __float__.r rcdSr r rs r __float__zSupportsFloat.__float__ r rN)rrrrrrfloatr r rrr?r? D44I 5   ^   rr?c2eZdZdZdZedefdZdS)r>z,An ABC with one abstract method __complex__.r rcdSr r rs r __complex__zSupportsComplex.__complex__ r rN)rrrrrrcomplexrr rrr>r> sD66I W   ^   rr>c2eZdZdZdZedefdZdS)r=z*An ABC with one abstract method __bytes__.r rcdSr r rs r __bytes__zSupportsBytes.__bytes__ r rN)rrrrrrbytesrr rrr=r= rrr=c2eZdZdZdZedefdZdS)r@z*An ABC with one abstract method __index__.r rcdSr r rs r __index__zSupportsIndex.__index__ r rN)rrrrrrr rr rrr@r@ sD44I 3   ^   rr@c2eZdZdZdZedefdZdS)r<zMAn ABC with one abstract method __abs__ that is covariant in its return type.r rcdSr r rs r__abs__zSupportsAbs.__abs__ r rN)rrrrrrrrr rrr<r< sDWWI    ^   rr<c8eZdZdZdZeddedefdZdS) rBzOAn ABC with one abstract method __round__ that is covariant in its return type.r rndigitsrcdSr r )rrs r __round__zSupportsRound.__round__ r rNr) rrrrrrr rr!r rrrBrB sPYYI   T   ^   rrBr cd|D}d|D}tj||||}|x|_|j_|S)Ncg|]\}}|Sr r rnrs rrz!_make_nmtuple.. s " " "DAqa " " "rc >i|]\}}|t|d|dS)zfield z annotation must be a typerPr%s rrz!_make_nmtuple.. sD   A AEEEEFF   rdefaultsrv)r namedtupler|rA)rTrrvr)fieldsnm_tpls r _make_nmtupler- sm " "E " " "F     E  #D&-5fFFFF>CCFV^; Mr> _makerA_asdict_fields_sourcer _replacer__getnewargs___field_defaults>rrr|ceZdZdZdS)NamedTupleMetac (t|vsJ|D]#}|tur|turtd$td|D}di}g}|D]^}|vr|||r@td|dt |dkrdndd d |_t||j fd |Dd  }||_ t|vr%tj j } t| |_ D]F} | tvrtd| z| t vr | |jvrt%|| | Gt|vr||S)Nz3can only inherit from a NamedTuple type and Genericc3:K|]}|turtn|VdSr ) _NamedTupler)rrts rrz)NamedTupleMeta.__new__.. s0OOt{22eeOOOOOOrr|zNon-default namedtuple field z cannot follow default fieldrRsr rc g|] }| Sr r )rr&nss rrz*NamedTupleMeta.__new__.. s(F(F(F1A(F(F(Frrr(z&Cannot overwrite NamedTuple attribute )r9rrrrtrrr#r-rrorgr classmethod _prohibitedr_specialr0rr) rtypenamerr=rtr default_names field_namer, class_getitemrs ` rrAzNamedTupleMeta.__new__ se#### K KD;&&4w+>+>IKKKOOOOOOO("--  ? ?JR$$Z0000 ?!> !>!>*-m*<*!>$(99]#;#;!>!>??? ? x(F(F(F(F (F(F(F&(&6888! e  #5>M'2='A'AF $ . .Ck!!$%MPS%STTTH$$FN)B)BRW--- e    $ $ & & & rN)rrrrAr rrr6r6 s#     rr6c ||}n|rtdt||tS)aTyped version of namedtuple. Usage in Python versions >= 3.6:: class Employee(NamedTuple): name: str id: int This is equivalent to:: Employee = collections.namedtuple('Employee', ['name', 'id']) The resulting class has an extra __annotations__ attribute, giving a dict that maps field names to types. (The field names are also in the _fields attribute, which is part of the namedtuple API.) Alternative equivalent keyword syntax is also accepted:: Employee = NamedTuple('Employee', name=str, id=int) In Python versions <= 3.5 use:: Employee = NamedTuple('Employee', [('name', str), ('id', int)]) NzIEither list of fields or keywords can be provided to NamedTuple, not bothrv)rrr-r)rAr+rBs rrLrL" sU0~ DCDD D 6')) < < <rc$eZdZddZeZdZeZdS)rpTc|D]0}t|tur|turtd1t d|Dr tf}nd}tt|g|t R|i}|di}dfd|D}t} t} |D]}| |j di| |j dd| |j dd| ||D]\} } t| } | tur(t| }|r|d } t| } | tur| | d| t"ur| | |r| | | | |_t'| _t'| _t-d s|_S) a5Create new typed dict class object. This method is called when TypedDict is subclassed, or when TypedDict is instantiated. This way TypedDict supports all three syntax forms described in its docstring. Subclasses and instances of TypedDict return actual dictionaries. zHcannot inherit from both a TypedDict type and a non-TypedDict base classc3@K|]}t|tVdSr )rrrs rrz)_TypedDictMeta.__new__..X s,55!z!W%%555555rr r|z?TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a typecFi|]\}}|t|jS)rF)rr)rr&rrtp_dicts rrz*_TypedDictMeta.__new__..b sA   2 {2s7+=>>>   r__required_keys____optional_keys__r __total__)rxrprrrrArrtrrupdaterqr\rr[rjrrfr|rOrOrPrrQ)rrTrr=totalrt generic_baserown_annotations required_keys optional_keysannotation_keyannotation_typeannotation_originannotation_argsrrNs @@rrAz_TypedDictMeta.__new__K s B BDDzz//D4G4G!ABBB 55u555 5 5 #:LLL,,~t5J|5JT5J5JBOO &&!2B77O     (..00      M MD   t}001BBGG H H H  !2!23F!K!K L L L  !2!23F!K!K L L L L?+++/>/D/D/F/F 2 2 +NO *? ; ;  I--"*?";";"D&5a&8O(2?(C(C% H,,!!.1111"k11!!.1111 2!!.1111!!.1111"-$-m$<$<!$-m$<$<!w ,, & %G rc td)Nz4TypedDict does not support instance and class checksr)rr#s rr/z _TypedDictMeta.__subclasscheck__ sNOOOrN)T)rrrrArrr/r+r rrrprpJ sF::::xHPPP*rrprSc ||}n|rtd|rtjdtddt |i}t }|||d<t |d|| S) 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 the Point2D.__annotations__ dict, and the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets. TypedDict supports an additional equivalent form:: 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 the other syntax form works for Python 2.7 and 3.2+ Nz@TypedDict takes either a dict or keyword arguments, but not bothzThe kwargs-based syntax for TypedDict definitions is deprecated in Python 3.11, will be removed in Python 3.13, and may not be understood by third-party type checkers.r stacklevelr|rr r])rwarningswarnDeprecationWarningrrrp)rAr+rSrBr=rvs rrMrM sR~ )()) )    7       T&\\ *B YYF !< (B% 8 8 88rrMctfSr ) _TypedDictrHs rrf s:-rcTt||jd}t||fS)aA special typing construct to mark a key of a total=False TypedDict as required. For example: class Movie(TypedDict, total=False): title: Required[str] year: int m = Movie( title='The Matrix', # typechecker error if key is omitted year=1999, ) There is no runtime checking that a required key is actually provided when instantiating a related TypedDict.  accepts only a single type.rrrrLs rrjrj s0" zdj#N#N#N O OD w ' ''rcTt||jd}t||fS)a<A special typing construct to mark a key of a TypedDict as potentially missing. For example: class Movie(TypedDict): title: str year: NotRequired[int] m = Movie( title='The Matrix', # typechecker error if key is omitted year=1999, ) rhrirLs rrfrf s0 zdj#N#N#N O OD w ' ''rc:eZdZdZeZdZdZdZdZ dZ dZ dS) rba%NewType creates simple unique types with almost zero runtime overhead. NewType(name, tp) is considered a subtype of tp by static type checkers. At runtime, NewType(name, tp) returns a dummy callable that simply returns its argument. Usage:: UserId = NewType('UserId', int) def name_by_id(user_id: UserId) -> str: ... UserId('user') # Fails type check name_by_id(42) # Fails type check name_by_id(UserId(42)) # OK num = UserId(5) + 1 # type: int c||_d|vr|dd}||_||_t }|dkr ||_dSdS)Nrrr)r rpartitionr __supertype__rr)rrTrrs rr zNewType.__init__ s_  $;;??3''+D )) h  %DOOO  rc6|jGfdd}|fS)NceZdZfdZdS)&NewType.__mro_entries__..Dummyc D|j}td|d|dd)NzGCannot subclass an instance of NewType. Perhaps you were looking for: `z = NewType(rz)`)rr)r subclass_namesuperclass_names rrz8NewType.__mro_entries__..Dummy.__init_subclass__ sU # Y%YY2?YYETYYYrN)rrrr)rtsrDummyrq s.       rrur)rrrurts @rrzNewType.__mro_entries__ sG-          xrc$|jd|jS)Nr)rrrs rrzNewType.__repr__( s/77D$5777rc|jSr )rrs rrzNewType.__reduce__+ s   rc t||fSr r!r"s rr$zNewType.__or__. r%rc t||fSr r!r"s rr'zNewType.__ror__1 r(rN) rrrrr rr rrrr$r'r rrrbrb s$H&&&   888!!!""""""""rrbceZdZdZdZeedefdZeedefdZ ed$dZ eede fdZ ede fd Zed$d Zede fd Zed%d e defdZede fdZed%de defdZed%de deefdZed&de de de fdZede fdZede fdZed'de de fdZede fdZedede fdZedeeddfd Zed(d"Zed$d#ZdS))rPaGeneric 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 rcdSr r rs rmodezIO.modeL  rcdSr r rs rrTzIO.nameQ r}rNcdSr r rs rclosezIO.closeV r rcdSr r rs rclosedz IO.closedZ r}rcdSr r rs rfilenoz IO.fileno_ r rcdSr r rs rflushzIO.flushc r rcdSr r rs risattyz IO.isattyg r rrr&cdSr r )rr&s rreadzIO.readk r rcdSr r rs rreadablez IO.readableo r rlimitcdSr r )rrs rreadlinez IO.readlines r rhintcdSr r )rrs r readlinesz IO.readlinesw r rroffsetwhencecdSr r )rrrs rseekzIO.seek{ r rcdSr r rs rseekablez IO.seekable r rcdSr r rs rtellzIO.tell r rsizecdSr r )rrs rtruncatez IO.truncate r rcdSr r rs rwritablez IO.writable r rr:cdSr r rr:s rwritezIO.write r rlinescdSr r )rrs r writelinesz IO.writelines r r IO[AnyStr]cdSr r rs r __enter__z IO.__enter__ r rcdSr r )rrxr tracebacks r__exit__z IO.__exit__ r r)rN)rr"r )rr) rrrrrrrrzr|rTrrrr rrrrTrrrrHrrrrrrrrrrr rrrPrP= s  I  c   ^X  c   ^X    ^     ^X     ^    ^     ^   c 6   ^  $   ^   c 6   ^   c 4<   ^   3  C   ^  $   ^  c   ^   S C   ^  $   ^  v #   ^  V     ^    ^    ^   rrPc^eZdZdZdZedeeefde fdZ eddZ dS) rOz5Typed version of the return of open() in binary mode.r r:rcdSr r rs rrzBinaryIO.write r rcdSr r rs rrzBinaryIO.__enter__ r rN)rrO) rrrrrrr"r bytearrayr rrr rrrOrO su??I uUI-. 3   ^    ^   rrOceZdZdZdZeedefdZeede fdZ eede e fdZ eede fdZeedefdZed d Zd S) rSz3Typed version of the return of open() in text mode.r rcdSr r rs rbufferz TextIO.buffer r}rcdSr r rs rencodingzTextIO.encoding r}rcdSr r rs rerrorsz TextIO.errors r}rcdSr r rs rline_bufferingzTextIO.line_buffering r}rcdSr r rs rnewlineszTextIO.newlines r}rcdSr r rs rrzTextIO.__enter__ r rN)rrS)rrrrrrrrOrrzrrrrrrrrr rrrSrS s6==I     ^X  #   ^X      ^X     ^X  #   ^X    ^   rrSceZdZfdZxZS)_DeprecatedTypec|dvr5||jvr,tj|jd|jdtdt |S)N)rqrz5 is deprecated, import directly from typing instead. z will be removed in Python 3.12.rr_)rqrarbrrcr9__getattribute__)rrTr:s rrz _DeprecatedType.__getattribute__ sy 1 1 1dcl6J6J M<""(+ """#     ww''---r)rrrrr=r>s@rrr s8 . . . . . . . . .rrc&eZdZdZgdZeZeZeZdS)ioz)Wrapper namespace for IO generic classes.)rPrSrON)rrrr__all__rPrSrOr rrrr s.33***G B FHHHrrz.ioc"eZdZdZddgZeZeZdS)rez&Wrapper namespace for re type aliases.rRrQN)rrrrrrRrQr rrrr s(00'"GG EEErrz.rercftdt|jtj|S)aReveal the inferred type of a variable. When a static type checker encounters a call to ``reveal_type()``, it will emit the inferred type of the argument:: x: int = 1 reveal_type(x) Running a static type checker (e.g., ``mypy``) on this example will produce output similar to 'Revealed type is "builtins.int"'. At runtime, the function prints the runtime type of the argument and returns it unchanged. zRuntime type is )file)printrxrrrstderrrs rrkrk s0  3T#YY/ 3 3#*EEEE Jr) eq_default order_defaultkw_only_defaultfield_specifiersrrrr.rBc "fd}|S)aDecorator that marks a function, class, or metaclass as providing dataclass-like behavior. Example usage with a decorator function: T = TypeVar("T") @dataclass_transform() def create_model(cls: type[T]) -> type[T]: ... return cls @create_model class CustomerModel: id: int name: str On a base class: @dataclass_transform() class ModelBase: ... class CustomerModel(ModelBase): id: int name: str On a metaclass: @dataclass_transform() class ModelMeta(type): ... class ModelBase(metaclass=ModelMeta): ... class CustomerModel(ModelBase): id: int name: str The ``CustomerModel`` classes defined above will be treated by type checkers similarly to classes created with ``@dataclasses.dataclass``. For example, type checkers will assume these classes have ``__init__`` methods that accept ``id`` and ``name``. The arguments to this decorator can be used to customize this behavior: - ``eq_default`` indicates whether the ``eq`` parameter is assumed to be ``True`` or ``False`` if it is omitted by the caller. - ``order_default`` indicates whether the ``order`` parameter is assumed to be True or False if it is omitted by the caller. - ``kw_only_default`` indicates whether the ``kw_only`` parameter is assumed to be True or False if it is omitted by the caller. - ``field_specifiers`` specifies a static list of supported classes or functions that describe fields, similar to ``dataclasses.field()``. - Arbitrary other keyword arguments are accepted in order to allow for possible future extensions. At runtime, this decorator records its arguments in the ``__dataclass_transform__`` attribute on the decorated object. It has no other runtime effect. See PEP 681 for more details. c"d|_|S)N)rrrrrB)__dataclass_transform__) cls_or_fnrrrrBrs rrz&dataclass_transform..decoratorR s)$*. 0 - - )rr )rrrrrBrs````` rrYrY s=J rr r)rRr)r)NNF)r )rrrrrrcollections.abcrrrr stdlib_rerrrrarrrr _typingr ImportErrorrr|rrrrrrrrrrrrrOrrrrrr4rxr7rrerarmr`rrr"rrrprrqrrrrrrr r!rhrirrrrr*r9r?rGrrYrrrrr\rr_TYPING_INTERNALS_SPECIAL_NAMESrrrrrrrrrrrrlrWrUrBuiltinFunctionTyperrrr^rr\r[r_rrVrcrdrpartialrrrgr]rXrZrrrrrrrrrrzrT_aliasr'r4r7r6r5r)r*r;r2r%r8rrJr#r0r,r.r1r/r$rrrrHdequerErrKr-r+r(r3rr&rr:rFrGrIrDrCrNr9rrAr?r>r=r@r<rBr-r?r@r6rLrAr9rIrrprMrerjrfrbrnrorPrOrSrrrrsrRrQrkrYr rrrs.*('''''''###### ^^^^^^^^^^^^ m m m h5PUB@@@ $** < < <    ' ' '  U,6?Y[[    BFFFFFFFF        $(/(/(/(/(/6 > > f[_0!44 6+/*A . . F;?,a 0 0 VKO. 2 2  91CSTTTfZCQMbccc vdAE///f[,amDDD f[,a00 &$a ( ( 6+& * * F;?,a 0 0  6:: vdAE/// 2     (        H        h        H        H        (4.        HTN   iDDDEE  9BBB C C"""""T"""J====>ll><R@@ 5 C*C*C*C*C*TC*C*C*L=9=9=9=9=9=9~\\.+r2 > > 77 ((((((("8"8"8"8"8"8"8"8"x  ` ` ` ` ` ` ` ` F      r%y          RW    F . . . . .d . . .?  BK &"A & &y""?  BKQa,!CE NNNNN N DIc(::C?@ N  Nqc1fNNNNNNsA AA