\dsNdZddlmZmZddlZddlmZddlZddlZddlZddl 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)a The typing module: Support for gradual typing as defined by PEP 484 and subsequent PEPs. Any name not present in __all__ is an implementation detail that may be changed without notice. Use at your own risk! Among other things, the module includes the following: * Generic, Protocol, and internal machinery to support generic aliases. All subscripted types like X[int], Union[int, str] are generic aliases. * Various "special forms" that have unique meanings in type annotations: NoReturn, Never, ClassVar, Self, Concatenate, Unpack, and others. * Classes whose instances can be type arguments to generic classes and functions: TypeVar, ParamSpec, TypeVarTuple. * Public helper functions: get_type_hints, overload, cast, final, and others. * Several protocols to support duck-typing: SupportsFloat, SupportsIndex, SupportsAbs, and others. * Special types: NewType, NamedTuple, TypedDict. * Deprecated wrapper submodules for re and io related types. * Deprecated aliases for builtin types and collections.abc ABCs. )abstractmethodABCMetaN) defaultdict)WrapperDescriptorTypeMethodWrapperTypeMethodDescriptorType GenericAlias)_idfuncc|SN)_xs ..\python\lib\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]}t|trt|tr2|D].}t|gD]}||vr||/_t |dr||vr||t |ddD]}||vr||t|S)zCollect all type variables and parameter specifications in args in order of first appearance (lexicographic order). For example:: assert _collect_parameters((T, Callable[P, T])) == (T, P) __typing_subst____parameters__r )ryrxr_collect_parametersappendhasattrgetattr)r parameterstr collecteds rrrsJ )) a   )  5 ! ! ) 5 5!4aS!9!955I 22")))4445 5Q* + + ) ""!!!$$$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_genericrs 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 _deduplicater)sVJ :V$$  % %AJ!!!$$$!!!$$$))z))) Mrcg}|D]S}t|ttjfr||j>||Ttt|S)zwInternal helper for Union creation and substitution. Flatten Unions among parameters, then remove duplicates. ) ry_UnionGenericAliasr UnionTyper__args__rrrrrps r_remove_dups_flattenr7st F  a,eo> ? ?  MM!* % % % % MM!     f%% & &&rcg}|D]G}t|tr||j2||Ht |S)zHInternal helper for Literal creation: flatten Literals among parameters.)ry_LiteralGenericAliasrrrrrs r_flatten_literal_paramsrGsa 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..inner]sR vt,t,,,    4&&& &s  ) functools lru_cache _cleanupsr cache_clearwraps)rrrrs` @r decoratorz_tp_cache..decoratorYss1$5111$77+,,,    ' ' ' ' '   '  rr )rrrs ` r _tp_cacherUs8      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..vsO$.c3#7#7@ 3SrNrc3<K|]}t|VdSr ) _eval_type)raglobalnslocalnsrecursive_guards rrz_eval_type..s1^^a 1hII^^^^^^r)ryr _evaluaterr rrrr __unpacked__rrrrrreduceoperatoror_ copy_with)rrrrr is_unpackedev_argss ``` rrrks!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 rr r)rgetitems r__init__z_SpecialForm.__init__s  %  rc6|dvr|jSt|)N>rr)r AttributeError)ritems r __getattr__z_SpecialForm.__getattr__s$ / / /: T"""rc&td|)NCannot subclass r)rbasess r__mro_entries__z_SpecialForm.__mro_entries__s3433444rcd|jzSNtyping.r rs 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 rrrrr r%r(r,r0rr3r rrrrs0I''' ### 555&&&888""""""DDDDDD//Y///rr)rceZdZdZdS)_LiteralSpecialFormcNt|ts|f}|j|g|RSr )ryrr r2s rr3z_LiteralSpecialForm.__getitem__s5*e,, '$Jt}T/J////rN)rrrr3r rrr5r5s#00000rr5c(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)rr:rrr;s rrz_AnyMeta.__repr__s' 3;;<ww!!!r)rrrr,r __classcell__r;s@rr8r8sQ..... """""""""rr8c"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)rrr:__new__)rrkwargsr;s rrBz Any.__new__sA #::899 9uwws4T444V444r)rrrrrBr>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 subscriptablerr2s rreres t222 3 33rc&t|d)adThe 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 rFrr2s rraras, t222 3 33rc&t|d)asUsed 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 rFrr2s rrmrm4s" t222 3 33rc&t|d)aRepresents 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. rFrr2s rr`r`Hs0 t222 3 33rcJt||d}t||fS)a9Special 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 rrrcs." 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. rKrLrMs rrrws.& zd#F#F#F G GD w ' ''rcx|dkrtdt|ts|f}dtfd|D}t|}t |dkr|dSt |dkr#t d|vrt ||d St ||S) aUnion type; Union[X, Y] means either X or Y. On Python 3.10 and higher, the | operator can also be used to denote unions; X | Y means the same thing to the type checker as Union[X, 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.:: assert Union[Union[int, str], float] == Union[int, str, float] - Unions of a single argument vanish, e.g.:: assert Union[int] == int # The constructor actually returns int - Redundant arguments are skipped, e.g.:: assert Union[int, str, int] == Union[int, str] - When comparing unions, the argument order is ignored, e.g.:: assert 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"s>R:;;; j% ( (# ] 5C????J?????J%j11J :!!} :!T j 8 8!$ DDDD dJ / //rc`t||d}t|tdfS)z,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_iterrrr2s rrrs2)44J ^^d;OPZ;[;[6\6\)])]^^^^^       j 1 11sAA AAc&t|d)a5Special form for marking type aliases. Use TypeAlias to indicate 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. rFrr2s rrprps t222 3 33rc0|dkrtdt|ts|f}|ddus*t|dtstddgfd|ddD|dR}t ||d S) abSpecial form for annotating higher-order functions. ``Concatenate`` can be sed in conjunction with ``ParamSpec`` and ``Callable`` to represent a higher order function which adds, removes or transforms the 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 rQrRs rrzConcatenate..s-AAAK3''AAAAAArNT_paramspec_tvars)rryrrrrVs @rrrsR@AAA j% ( (# ] rNc ! !Z 2 %J%J !:;; ; ;CRAAAACRCAAAR:b>RRJ #D*59 ; ; ;;rcJt||d}t||fS)aSpecial typing construct for marking user-defined type guard functions. ``TypeGuard`` can be 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). rKrLrMs rrqrq s/\ 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 SyntaxErrorrbrcrdrerfrgrh)rr{rrvrwarg_to_compilecodes rr zForwardRef.__init__Fs#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)rbrdrhrsysmodulesgetrrlrcrfrgrre)rrrrtype_s rrzForwardRef._evaluate^s  ? 2 2K) .WH-D-DGO%''77!""&2"KOOD$;TBBJPX T*Hg>>< 8$($= E &0x/T=Qs77'I )u)))))0&&&4EEEEEE""""""DDDDDrrrreturncPt|t ot|ddS)N#__typing_is_unpacked_typevartuple__F)ryrxrrs r_is_unpacked_typevartuplers.At$$ $ E A 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=...rSz"A single constraint is not allowedz:TypeVar(name, constraint, ...): constraints must be types.c38K|]}t|VdSr rQ)rrrs rrz#TypeVar.__init__..s-$N$NQ[C%8%8$N$N$N$N$N$Nrtyping) rr:r rrr__constraints___callerr) rrUrrr 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)rrUrs 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__2sLMMMrc "|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) NrSz(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__5sF%#\\$//.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__f  rc |jjdS)Nz.argsrrrs rrzParamSpecArgs.__repr__is/*1111rcZt|tstS|j|jkSr )ryrhrxrr#s rryzParamSpecArgs.__eq__ls*%// "! !%"222rNrrrrr rryr rrrhrhZsK  !!!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__~rrc |jjdS)Nz.kwargsrrs rrzParamSpecKwargs.__repr__s/*3333rcZt|tstS|j|jkSr )ryrirxrr#s rryzParamSpecKwargs.__eq__s*%11 "! !%"222rNrr rrririrsK  !!!44433333rricdeZdZdZedZedZddddfd ZdZd Z xZ S) raParameter 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 can be introspected. e.g.: P.__name__ == 'P' Note that only parameter specification variables defined in global scope can be pickled. c t|Sr )rhrs rrzParamSpec.argssT"""rc t|Sr )rirs rrCzParamSpec.kwargsst$$$rNFrc||_t|||t}|dkr ||_dSdSr)rr:r rr)rrUrrrrr;s rr zParamSpec.__init__sM   =999)) h  %DOOO  rct|ttfrtd|D}n!t|st d||S)Nc36K|]}t|dVdS)zExpected a type.NrQrrs 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)NrrSr)rrrrrryrr)rrrris rrz"ParamSpec.__typing_prepare_subst__s% LL   D >>r?s@rrrs##J##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 the 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. TNinstrUc>||_||_||_d|_dSr )_instr rr)rrrrUs rr z_BaseGenericAlias.__init__s"   rc|js%td|jd|jjd|j|i|} ||_n#t $rYnwxYw|S)NzType z cannot be instantiated; use z () instead)rrr rr__orig_class__r)rrrCresults rr z_BaseGenericAlias.__call__sz IHDJHH#'?#;HHHII I $1&11 $(F ! !    D  sA AAc@g}|j|vr||j||}||dzdD].}t|tst |t rn/|t t|SNrS)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)r rrrrrrr)rrs rrz_BaseGenericAlias.__getattr__s\ / / /:9!9 9 4= ( (D1A1A (4?D11 1T"""rct|s|dvr$t||dSt|j||dS)N>rr _nparamsr_)rr: __setattr__setattrr)rrvalr;s rrz_BaseGenericAlias.__setattr__ s^ d   0t(< < < GG  c * * * * * DOT3 / / / / /rcF|t|Sr r0rxr+s rr,z#_BaseGenericAlias.__instancecheck__%%d3ii000rc td)NzBSubscripted generics cannot be used with class and instance checksrr/s rr0z#_BaseGenericAlias.__subclasscheck__s566 6rc tttdt |jDzS)Nc0g|]}t||Sr )r)rrs r z-_BaseGenericAlias.__dir__..s%QQQD 4@P@PQ4QQQr)rrr:__dir__dirrr=s rrz_BaseGenericAlias.__dir__sWC))QQC$8$8QQQRSSTT Tr) rrrrr r rrrr,r0rr>r?s@rrrs(,$      ###00000111666TTTTTTTTTrrceZdZddddfd ZdZdZdZd Zed Z d Z d Z d Z dZ dZfdZdZxZS)rTNF)rrUr_ct|||t|ts|f}td|D|_t ||_||_|s|j|_dSdS)Nrc30K|]}|turdn|VdS).N)_TypingEllipsisrs rrz)_GenericAlias.__init__..GsE//$%&'/%9%9cc//////r) r:r ryrrrrr_r)rrrrrUr_r;s rr z_GenericAlias.__init__Bs d666$&& 7D//)-///// 1$77 0 0$/DOOO 0 0rczt|tstS|j|jko|j|jkSr )ryrrxrrr#s rryz_GenericAlias.__eq__Ns=%// "! !5#334MU^3 5rc8t|j|jfSr )r{rrrs rr|z_GenericAlias.__hash__TsT_dm4555rc t||fSr r"rs rr%z_GenericAlias.__or__Wr&rc t||fSr r"rs rr(z_GenericAlias.__ror__ZrrcZ|jttfvrtd||jst|dt |t s|f}t d|D}t|}||}| |}|S)Nz%Cannot subscript already-subscripted rc34K|]}t|VdSr r|rrs rrz,_GenericAlias.__getitem__..ws*44!]1%%444444r) rrrrrryrr_determine_new_argsr)rrnew_argsrs rr3z_GenericAlias.__getitem__]s" ?w1 1 1JDJJKK K" >t<<<== =$&& 7D44t44444D!!++D11 NN8 $ $rc p|j}|D]!}t|dd}| |||}"t|}t|}||kr#td||krdndd|d|d|t t ||}t ||j|S)Nrrrrrrr) rrrrdictzipr_make_substitutionr)rrrrpreparerrnew_arg_by_params rrz!_GenericAlias._determine_new_args}s$ + +Ee%?FFG"wtT**4yy6{{ 4<<?TD[[66e??TX??'+??8<??@@ @FD 1 122T,,T]>#G-=rBB  6%GG G&@@%a66@#NN+;A+>????#NN+;A+>????%eGnn5G+/":::z'SX?Y?Y:((((*733 )((((GU++ )$11';KLLMM((((rc^||j||j|j|jS)NrUrr_)r;rr rr_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()[])r rrrjoin)rrUrs rrz_GenericAlias.__repr__su : /tz)DDdo..D = 99CCT]CCCDDDDD      rc|jrt|j}n|j}t|j}t |dkrt |dts|\}tj||ffSNrSr) r globalsrrrrryrr )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 rS) ryrrrr r:rrrrr)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 ryr|r%r(rr3rrrrrrrr>r?s@rrr(s4.2"' 0 0 0 0 0 0 0555 666"""!!!Y>OOO:<<<|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)rr:r rrrr)rrnparamsrrUr;s rr z_SpecialGenericAlias.__init__ s <?D d666   * *I63FIIIDLLL]63D]]vGZ]]]DLLLrct|ts|f}dtfd|D}t|||j||S)Nrc38K|]}t|VdSr rQrRs rrz3_SpecialGenericAlias.__getitem__..-;;q{1c**;;;;;;r)ryrrrrrrrs @rr3z _SpecialGenericAlias.__getitem__si&%(( YF:;;;;F;;;;;tVT]333~~f%%%rcFt|j||j|jS)N)rUr)rrr rrrs rrz_SpecialGenericAlias.copy_withs(T_f"&*4:??? ?rcd|jzSrrrs rrz_SpecialGenericAlias.__repr__!rrct|trt|j|jSt|tst||jSt |Sr )ryr-rrrr:r0)rrr;s rr0z&_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__1rr) rrrr rr3rrr0rr%r(r>r?s@rr-r- s044^^^^^^^&&Y&???&&&....."""!!!!!!!rr-c$eZdZfdZdZxZS)_CallableGenericAliasc>|jdksJ|j}t|dkr5t|dr t Sddd|ddDdt|dd S) Nrrrztyping.Callable[[r!c,g|]}t|Sr r#rs rrz2_CallableGenericAlias.__repr__..;sAAA! 1 AAArrz], r%)r rrrr:rr&rrrr;s rrz_CallableGenericAlias.__repr__5szZ''''} 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@rr<r<4sG,,,,,2222222rr<c0eZdZdZdZedZdS) _CallableTypecHt|j||j|jdS)NTr)r<rr rr5s rrz_CallableType.copy_withFs+$T_f*.*4:6:<<< .bs*88C]3''888888r)rEllipsisrrryr)rrrrrs rrEz_CallableType.__getitem_inner__Ys f>VS)) 8  >>?F";<< <$&& 7D88488888 !~~f%%%rN)rrrrr3rrEr rrrBrBEsM<<< . . . & &Y & & &rrBc$eZdZedZdS) _TupleTypecZt|ts|f}t|dkrN|ddurDdtfd|ddD}|g|tRSdtfd|D}||S)Nrr.z Tuple[t, ...]: t must be a type.c38K|]}t|VdSr rQrRs rrz)_TupleType.__getitem__..ns-DD1;q#..DDDDDDrz*Tuple[t0, t1, ...]: each t must be a type.c38K|]}t|VdSr rQrRs rrz)_TupleType.__getitem__..qr2r)ryrrrrr3s @rr3z_TupleType.__getitem__hs&%(( YF v;;!  r c 1 14CDDDDss DDDDDF>>">Aw$t**$$@*T!W*=*=@@@@aDJJ&&@*T!W*=*=@@@@ww!!!rcF|t|Sr rr+s rr,z$_UnionGenericAlias.__instancecheck__rrc@|jD]}t||rdSdS)NT)rr)rrr{s rr0z$_UnionGenericAlias.__subclasscheck__s;=  C#s## tt   rcft\}\}}|t|ffSr )r:rr")rrrrr;s rrz_UnionGenericAlias.__reduce__s0$ww1133nvteT]""r) rrrrryr|rr,r0rr>r?s@rrrus999 ..."""""111 #########rrcd|DS)Nc38K|]}|t|fVdSr )rxrs rrz'_value_and_type_iter..s, - -QQQL - - - - - -rr )rs rrZrZs - -* - - --rceZdZdZdZdS)rct|tstStt |jtt |jkSr )ryrrxrrZrr#s rryz_LiteralGenericAlias.__eq__sN%!566 "! !' 66773?STYTb?c?c;d;dddrc^ttt|jSr )r{rRrZrrs rr|z_LiteralGenericAlias.__hash__s#I24=AABBCCCrN)rrrryr|r rrrrs:eee DDDDDrrceZdZfdZxZS)rct|dttfrg|dd|dRSt|dtrg|dd|djR}t |S)Nr)ryrrrrr:r)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. rK)rr)r_UnpackGenericAliasrMs rrrrrs1< zd#F#F#F G GD d$ 9 9 99rcPeZdZdZfdZedZedZxZS)r_c<dt|jdzS)Nrjr)rrrs rrz_UnpackGenericAlias.__repr__sT$-*++++rcX|jr|St|Sr )rr:r3r?s rr3z_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) rrrrr3rrrr>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 rs rrz,Generic.__class_getitem__..s*88A}Q''888888rzParameter list to z[...] cannot be emptyc34K|]}t|VdSr )rrs 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 times.r!c3>K|]}|vt|VdSr rz)rrgvarsets rrz,Generic.__init_subclass__..Qs3&Q&Q!@P@Ps1vv@P@P@P@P&Q&Qrc34K|]}t|VdSr rn)rgs rrz,Generic.__init_subclass__..Rs(&=&=!s1vv&=&=&=&=&=&=rzSome type variables (z) are not listed in Generic[r%)r:rrrrrl __bases__rrx_TypedDictMetarrryrrrrr&r) rrrCtvarserrorgvarsbasetvarsets_varss_argsror;s @rrzGeneric.__init_subclass__3s!!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_protocolrrjrr>r?s@rrrsh&IL,4,4Y,4\#*#*#*#*#*#*#*#*#*rrceZdZdZdS)rz(Internal placeholder for ... (ellipsis).N)rrrrr rrrrYs2222rr)rrlrr{_is_runtime_protocol) __abstractmethods____annotations__rrrr rrBr__subclasshook__rrj_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__rrrrrkeysrEXCLUDED_ATTRIBUTESadd)rattrsrw annotationsrs r_get_protocol_attrsrhs EEE CRC    =3 3 3 d$5r:: ++--..k6F6F6H6H1I1II  D??7++ .{s7WWdxT40011WWWWWWr)rirrs`r_is_callable_members_onlyrys0 WWWW>QRU>V>VWWW W WWrc,t|}|jrtd|jturdS|jD]4}|jdt}|tur ||_n5tj|_|j|g|Ri|dS)Nz Protocols cannot be instantiatedr ) rxr{rr _no_init_or_replace_initrrrruobject)rrrCrrwinits rrr~s t**C <:;;; |333 ''}  -EFF / / /CL E 0  CL'''''''''rrS__main__c tj|dzjd|S#tt f$rYdSwxYw)NrSr)rs _getframe f_globalsrurr)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) Nr{Fr}rrLInstance 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;r{rirr:r,)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)Nr{Fc3(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) Nr{Fr}rz._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))))4rrz7Protocols can only inherit from other protocols, got %r)r:rrrruanyrrr{rrrr_PROTO_ALLOWLISTrrrr rr)rrrCrrwr;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) rrrrrr{r}rr>r?s@rrrsT<IL >4>4>4>4>4>4>4>4>4rrcJeZdZdZfdZdZdZdZdZdZ fdZ xZ S) _AnnotatedAliasaRuntime 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. The metadata itself is stored in a '__metadata__' attribute as a tuple. ct|tr|j|z}|j}t ||||_dSr )ryr __metadata__rr:r )rrmetadatar;s rr z_AnnotatedAlias.__init__?sR fo . . '*X5H&F ((($rcft|dksJ|d}t||jSr()rrr)rrnew_types rrz_AnnotatedAlias.copy_withFs56{{a!9x):;;;rcdt|jdd|jDS)Nztyping.Annotated[{}, {}]r!c34K|]}t|VdSr )rrs rrz+_AnnotatedAlias.__repr__..Ns(99!d1gg999999r)formatrrr&rrs rrz_AnnotatedAlias.__repr__KsH)00 t ' ' II99t'8999 9 9   rcHtjt|jf|jzffSr )rr rrrrs rrz_AnnotatedAlias.__reduce__Qs) )D,=="   rczt|tstS|j|jko|j|jkSr )ryrrxrrr#s rryz_AnnotatedAlias.__eq__Vs?%11 "! !5#33<%);; =rc8t|j|jfSr )r{rrrs rr|z_AnnotatedAlias.__hash__\sT_d&78999rcR|dvrdSt|S)N>rrr)r:r)rrr;s rrz_AnnotatedAlias.__getattr___s, / / /;ww""4(((r) rrrrr rrrryr|rr>r?s@rrr4s%%%%%<<<       === :::)))))))))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. - Access the metadata via the ``__metadata__`` attribute:: assert Annotated[int, '$'].__metadata__ == ('$',) - Nested Annotated are flattened:: assert Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3] - Instantiating an annotated type is equivalent to instantiating the underlying type:: assert Annotated[C, Ann1](5) == C(5) - Annotated can be used as a generic type alias:: Optimized = Annotated[T, runtime.Optimize()] assert Optimized[int] == Annotated[int, runtime.Optimize()] OptimizedList = Annotated[List[T], runtime.Optimize()] assert 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.rrrrCs rrBzAnnotated.__new__s@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.TrsrS)ryrrrrrr)rrrrrs rrjzAnnotated.__class_getitem__s&%(( ,CKK!OO+,, , %VAY / / 5455 54VAYFFF$$vx000rcPtd|j)NzCannot subclass {}.Annotated)rrrrs rrzAnnotated.__init_subclass__s' * 1 1#. A A   rN) rrrrrrBrrjrr rrrresb++ZIBBB 1 1Y 1     rrcpt|tr|jstd|zd|_|S)a:Mark 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)rrr{rr}rs 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. At runtime this does nothing: it returns the first argument unchanged with no checks or side effects, no matter the actual type of the argument. When a static 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 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__NrrrFT)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..F s'(\(\(\da,>q,A,A(\(\(\r)rryrxreversedrrsrtrurrrrGetSetDescriptorTypervarsitemsrzrr ModuleTyperr_allowed_typesrr) rrrinclude_extrashintsrw base_globalsann base_localsrUvaluensobjs 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(Strip the annotations from a given type.rrc34K|]}t|VdSr rrs rrz%_strip_annotations..P +HH033HHHHHHrc34K|]}t|VdSr rrs rrz%_strip_annotations..U rrc34K|]}t|VdSr rrs rrz%_strip_annotations..Z rr)ryrrrrrjrfrrrrr rrrrrr)r stripped_argss rrrI sa!_%%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)aJGet the unsubscripted version of a type. This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar Annotated, and others. Return None for unsupported types. Examples:: assert get_origin(Literal[42]) is Literal assert get_origin(int) is None assert get_origin(ClassVar[int]) is ClassVar assert get_origin(Generic) is Generic assert get_origin(Generic[T]) is Generic assert get_origin(Union[T, int]) is Union assert get_origin(List[Tuple[T, T]][int]) is list assert get_origin(P.args) is P N) ryrrrr rhrirrrrtps rr\r\b 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:: assert get_args(Dict[str, int]) == (str, int) assert get_args(int) == () assert get_args(Union[int, Union[T, int], str][int]) == (int, str) assert get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int]) assert 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 )ryrsrs rr_r_ 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)aDecorator 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 rrrXrX4 srcF d|_n#ttf$rYnwxYw|S)aDecorator 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 attempts to set the ``__final__`` attribute to ``True`` on the decorated object to allow runtime introspection. T) __final__rr)rs rrZrZ9 s>4  I &      Hs  TKTVTT_co)rV_coVT_coT_contra)rCT_co)rrrTraDeprecated alias to collections.abc.Callable. Callable[[int], str] signifies 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, a ParamSpec 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#rTrrra]Deprecated alias to builtins.tuple. 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:rFrGraDeprecated alias to builtins.type. builtins.type or typing.Type can be used 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)rrrrrrintr r rrrArA sD22I    ^   rrAc2eZdZdZdZedefdZdS)r?z*An ABC with one abstract method __float__.r rcdSr r rs r __float__zSupportsFloat.__float__ r rN)rrrrrrfloatrr 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)rrrrrrrr r rrr<r< sDWWI    ^   rr<c8eZdZdZdZeddedefdZdS) rBzOAn ABC with one abstract method __round__ that is covariant in its return type.r rndigitsrcdSr r )rr"s 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 typerQr(s rrz!_make_nmtuple.. sD   A AEEEEFF   rdefaultsrv)r namedtuplerrB)rUrrvr,fieldsnm_tpls r _make_nmtupler0 sm " "E " " "F     E  #D&-5fFFFF>CCFV^; Mr> _makerB_asdict_fields_sourcer _replacer__getnewargs___field_defaults>rrrceZdZdZdS)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)rrws rrz)NamedTupleMeta.__new__..0 s0OOt{22eeOOOOOOrrzNon-default namedtuple field z cannot follow default fieldrSsr r!c g|] }| Sr r )rr)nss rrz*NamedTupleMeta.__new__..< s(F(F(F1A(F(F(Frrr+z&Cannot overwrite NamedTuple attribute )r<rrrrurrr&r0rrrrjr classmethod _prohibitedr_specialr3rr) rtypenamerr@rwr default_names field_namer/ class_getitemrs ` rrBzNamedTupleMeta.__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)rrrrBr rrr9r9) s#     rr9c ||}n|rtdt||tS)a?Typed version of namedtuple. Usage:: 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.) An alternative equivalent functional syntax is also accepted:: Employee = NamedTuple('Employee', [('name', str), ('id', int)]) NzIEither list of fields or keywords can be provided to NamedTuple, not bothrv)rrr0r)rDr.rCs rrLrLM sU(~ DCDD D 6')) < < <rc$eZdZddZeZdZeZdS)rsTc|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) a7Create a 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__.. s,55!z!W%%555555rr rz?TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a typecFi|]\}}|t|jS)rI)rr)rr)rrtp_dicts rrz*_TypedDictMeta.__new__.. sA   2 {2s7+=>>>   r__required_keys____optional_keys__r __total__)rxrsrrrrBrrurrupdaterrr\rr[rjrrfrrRrRrSrrT)rrUrr@totalrw generic_baserown_annotations required_keys optional_keysannotation_keyannotation_typeannotation_originannotation_argsrrQs @@rrBz_TypedDictMeta.__new__r 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 rr0z _TypedDictMeta.__subclasscheck__ sNOOOrN)T)rrrrBrr r0r,r rrrsrsq sF::::xHPPP*rrsrVc ||}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 such that a type checker will expect all 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. 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:: 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 Required and NotRequired special forms can also be used to mark individual keys as being required or not required:: class Point2D(TypedDict): x: int # the "x" key must always be present (Required is the default) y: NotRequired[int] # the "y" key can be omitted See PEP 655 for more details on Required and NotRequired. 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 stacklevelrrr r`)rwarningswarnDeprecationWarningrrrs)rDr.rVrCr@rvs rrMrM s^~ )()) )    7       T&\\ *B YYF !< (B% 8 8 88rrMctfSr ) _TypedDictrKs rri s:-rcTt||jd}t||fS)aSpecial typing construct to mark a TypedDict key as required. This is mainly useful for total=False TypedDicts. 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.rr rrMs rrjrj s0$ zdj#N#N#N O OD w ' ''rcTt||jd}t||fS)a7Special typing construct to mark a TypedDict key 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, ) rkrlrMs 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)rrUrrs 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(r!z)`)rr)r subclass_namesuperclass_names rrz8NewType.__mro_entries__..Dummy.__init_subclass__O sU # Y%YY2?YYETYYYrN)rrrr)rwsrDummyrtN s.       rrxr)rrrxrws @rrzNewType.__mro_entries__I sG-          xrc$|jd|jS)Nr)rrrs rrzNewType.__repr__X 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__a r)rN) rrrrr r r 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.mode|  rcdSr r rs rrUzIO.name rrNcdSr r rs rclosezIO.close r rcdSr r rs rclosedz IO.closed rrcdSr r rs rfilenoz IO.fileno r rcdSr r rs rflushzIO.flush r rcdSr r rs risattyz IO.isatty r rrr)cdSr r )rr)s rreadzIO.read r rcdSr r rs rreadablez IO.readable r rlimitcdSr r )rrs rreadlinez IO.readline r rhintcdSr r )rrs r readlinesz IO.readlines 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) rrrrrrrrzrrUrrrr rrrrTrrrrHrrrrrrrrrrr rrrPrPm 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 rrcdSr r rs rencodingzTextIO.encoding rrcdSr r rs rerrorsz TextIO.errors rrcdSr r rs rline_bufferingzTextIO.line_buffering rrcdSr r rs rnewlineszTextIO.newlines rrcdSr 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)rrrz5 is deprecated, import directly from typing instead. z will be removed in Python 3.12.rrb)rrrdrerrfr:__getattribute__)rrUr;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)printrxrrsstderrrs rrkrk) s0 3T#YY/ 3 3#*EEEE Jr) eq_default order_defaultkw_only_defaultfield_specifiersrrrr.rCc "fd}|S)aDecorator to mark an object as providing dataclass-like behaviour. The decorator can be applied to a function, class, or metaclass. 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)rrrrrC)__dataclass_transform__) cls_or_fnrrrrCrs rrz&dataclass_transform..decorator s)$*. 0 - - )rr )rrrrrCrs````` rrYrY< s=L rr r)rSr)r)NNF)r )rrrrrrcollections.abcrrrr stdlib_rersrrdrrrr _typingr ImportErrorrr|rrrrrrrrrrrrrRrrrrrr5rxr8rrerarmr`rrr"rrrprrqrrrrrrr r!rhrirrrrr-r<rBrJrrZrrrrr_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<rBr0rBrCr9rLrBr<rLrrsrMrhrjrfrbrnrorPrOrSrrrrtrRrQrkrYr rrrs4*('''''''###### ^^^^^^^^^^^^ m m m h5PUB@@@ $*< < < <    ' ' '   U,6?Y[[    DFFFFFFFF        ((/(/(/(/(/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/// 4     (        H        h        H        H        (4.        HTN   iDDDEE  9BBB C C!!!!!T!!!H====6ll><R@@ 5 C*C*C*C*C*TC*C*C*LC9C9C9C9C9C9J\\.+r2 > > 77 (((*((($9"9"9"9"9"9"9"9"z  ` ` ` ` ` ` ` ` F      r%y          RW    F . . . . .d . . .?  BK &"A & &y""?  BKQa*!CE OOOOO O DIc(::C?@ O  Oqc1fOOOOOOsA AA