typing_extensions.py 157 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317
  1. import abc
  2. import builtins
  3. import collections
  4. import collections.abc
  5. import contextlib
  6. import enum
  7. import functools
  8. import inspect
  9. import io
  10. import keyword
  11. import operator
  12. import sys
  13. import types as _types
  14. import typing
  15. import warnings
  16. # Breakpoint: https://github.com/python/cpython/pull/119891
  17. if sys.version_info >= (3, 14):
  18. import annotationlib
  19. __all__ = [
  20. # Super-special typing primitives.
  21. 'Any',
  22. 'ClassVar',
  23. 'Concatenate',
  24. 'Final',
  25. 'LiteralString',
  26. 'ParamSpec',
  27. 'ParamSpecArgs',
  28. 'ParamSpecKwargs',
  29. 'Self',
  30. 'Type',
  31. 'TypeVar',
  32. 'TypeVarTuple',
  33. 'Unpack',
  34. # ABCs (from collections.abc).
  35. 'Awaitable',
  36. 'AsyncIterator',
  37. 'AsyncIterable',
  38. 'Coroutine',
  39. 'AsyncGenerator',
  40. 'AsyncContextManager',
  41. 'Buffer',
  42. 'ChainMap',
  43. # Concrete collection types.
  44. 'ContextManager',
  45. 'Counter',
  46. 'Deque',
  47. 'DefaultDict',
  48. 'NamedTuple',
  49. 'OrderedDict',
  50. 'TypedDict',
  51. # Structural checks, a.k.a. protocols.
  52. 'SupportsAbs',
  53. 'SupportsBytes',
  54. 'SupportsComplex',
  55. 'SupportsFloat',
  56. 'SupportsIndex',
  57. 'SupportsInt',
  58. 'SupportsRound',
  59. 'Reader',
  60. 'Writer',
  61. # One-off things.
  62. 'Annotated',
  63. 'assert_never',
  64. 'assert_type',
  65. 'clear_overloads',
  66. 'dataclass_transform',
  67. 'deprecated',
  68. 'disjoint_base',
  69. 'Doc',
  70. 'evaluate_forward_ref',
  71. 'get_overloads',
  72. 'final',
  73. 'Format',
  74. 'get_annotations',
  75. 'get_args',
  76. 'get_origin',
  77. 'get_original_bases',
  78. 'get_protocol_members',
  79. 'get_type_hints',
  80. 'IntVar',
  81. 'is_protocol',
  82. 'is_typeddict',
  83. 'Literal',
  84. 'NewType',
  85. 'overload',
  86. 'override',
  87. 'Protocol',
  88. 'Sentinel',
  89. 'reveal_type',
  90. 'runtime',
  91. 'runtime_checkable',
  92. 'Text',
  93. 'TypeAlias',
  94. 'TypeAliasType',
  95. 'TypeForm',
  96. 'TypeGuard',
  97. 'TypeIs',
  98. 'TYPE_CHECKING',
  99. 'type_repr',
  100. 'Never',
  101. 'NoReturn',
  102. 'ReadOnly',
  103. 'Required',
  104. 'NotRequired',
  105. 'NoDefault',
  106. 'NoExtraItems',
  107. # Pure aliases, have always been in typing
  108. 'AbstractSet',
  109. 'AnyStr',
  110. 'BinaryIO',
  111. 'Callable',
  112. 'Collection',
  113. 'Container',
  114. 'Dict',
  115. 'ForwardRef',
  116. 'FrozenSet',
  117. 'Generator',
  118. 'Generic',
  119. 'Hashable',
  120. 'IO',
  121. 'ItemsView',
  122. 'Iterable',
  123. 'Iterator',
  124. 'KeysView',
  125. 'List',
  126. 'Mapping',
  127. 'MappingView',
  128. 'Match',
  129. 'MutableMapping',
  130. 'MutableSequence',
  131. 'MutableSet',
  132. 'Optional',
  133. 'Pattern',
  134. 'Reversible',
  135. 'Sequence',
  136. 'Set',
  137. 'Sized',
  138. 'TextIO',
  139. 'Tuple',
  140. 'Union',
  141. 'ValuesView',
  142. 'cast',
  143. 'no_type_check',
  144. 'no_type_check_decorator',
  145. ]
  146. # for backward compatibility
  147. PEP_560 = True
  148. GenericMeta = type
  149. # Breakpoint: https://github.com/python/cpython/pull/116129
  150. _PEP_696_IMPLEMENTED = sys.version_info >= (3, 13, 0, "beta")
  151. # Added with bpo-45166 to 3.10.1+ and some 3.9 versions
  152. _FORWARD_REF_HAS_CLASS = "__forward_is_class__" in typing.ForwardRef.__slots__
  153. # The functions below are modified copies of typing internal helpers.
  154. # They are needed by _ProtocolMeta and they provide support for PEP 646.
  155. class _Sentinel:
  156. def __repr__(self):
  157. return "<sentinel>"
  158. _marker = _Sentinel()
  159. # Breakpoint: https://github.com/python/cpython/pull/27342
  160. if sys.version_info >= (3, 10):
  161. def _should_collect_from_parameters(t):
  162. return isinstance(
  163. t, (typing._GenericAlias, _types.GenericAlias, _types.UnionType)
  164. )
  165. else:
  166. def _should_collect_from_parameters(t):
  167. return isinstance(t, (typing._GenericAlias, _types.GenericAlias))
  168. NoReturn = typing.NoReturn
  169. # Some unconstrained type variables. These are used by the container types.
  170. # (These are not for export.)
  171. T = typing.TypeVar('T') # Any type.
  172. KT = typing.TypeVar('KT') # Key type.
  173. VT = typing.TypeVar('VT') # Value type.
  174. T_co = typing.TypeVar('T_co', covariant=True) # Any type covariant containers.
  175. T_contra = typing.TypeVar('T_contra', contravariant=True) # Ditto contravariant.
  176. # Breakpoint: https://github.com/python/cpython/pull/31841
  177. if sys.version_info >= (3, 11):
  178. from typing import Any
  179. else:
  180. class _AnyMeta(type):
  181. def __instancecheck__(self, obj):
  182. if self is Any:
  183. raise TypeError("typing_extensions.Any cannot be used with isinstance()")
  184. return super().__instancecheck__(obj)
  185. def __repr__(self):
  186. if self is Any:
  187. return "typing_extensions.Any"
  188. return super().__repr__()
  189. class Any(metaclass=_AnyMeta):
  190. """Special type indicating an unconstrained type.
  191. - Any is compatible with every type.
  192. - Any assumed to have all methods.
  193. - All values assumed to be instances of Any.
  194. Note that all the above statements are true from the point of view of
  195. static type checkers. At runtime, Any should not be used with instance
  196. checks.
  197. """
  198. def __new__(cls, *args, **kwargs):
  199. if cls is Any:
  200. raise TypeError("Any cannot be instantiated")
  201. return super().__new__(cls, *args, **kwargs)
  202. ClassVar = typing.ClassVar
  203. # Vendored from cpython typing._SpecialFrom
  204. # Having a separate class means that instances will not be rejected by
  205. # typing._type_check.
  206. class _SpecialForm(typing._Final, _root=True):
  207. __slots__ = ('_name', '__doc__', '_getitem')
  208. def __init__(self, getitem):
  209. self._getitem = getitem
  210. self._name = getitem.__name__
  211. self.__doc__ = getitem.__doc__
  212. def __getattr__(self, item):
  213. if item in {'__name__', '__qualname__'}:
  214. return self._name
  215. raise AttributeError(item)
  216. def __mro_entries__(self, bases):
  217. raise TypeError(f"Cannot subclass {self!r}")
  218. def __repr__(self):
  219. return f'typing_extensions.{self._name}'
  220. def __reduce__(self):
  221. return self._name
  222. def __call__(self, *args, **kwds):
  223. raise TypeError(f"Cannot instantiate {self!r}")
  224. def __or__(self, other):
  225. return typing.Union[self, other]
  226. def __ror__(self, other):
  227. return typing.Union[other, self]
  228. def __instancecheck__(self, obj):
  229. raise TypeError(f"{self} cannot be used with isinstance()")
  230. def __subclasscheck__(self, cls):
  231. raise TypeError(f"{self} cannot be used with issubclass()")
  232. @typing._tp_cache
  233. def __getitem__(self, parameters):
  234. return self._getitem(self, parameters)
  235. # Note that inheriting from this class means that the object will be
  236. # rejected by typing._type_check, so do not use it if the special form
  237. # is arguably valid as a type by itself.
  238. class _ExtensionsSpecialForm(typing._SpecialForm, _root=True):
  239. def __repr__(self):
  240. return 'typing_extensions.' + self._name
  241. Final = typing.Final
  242. # Breakpoint: https://github.com/python/cpython/pull/30530
  243. if sys.version_info >= (3, 11):
  244. final = typing.final
  245. else:
  246. # @final exists in 3.8+, but we backport it for all versions
  247. # before 3.11 to keep support for the __final__ attribute.
  248. # See https://bugs.python.org/issue46342
  249. def final(f):
  250. """This decorator can be used to indicate to type checkers that
  251. the decorated method cannot be overridden, and decorated class
  252. cannot be subclassed. For example:
  253. class Base:
  254. @final
  255. def done(self) -> None:
  256. ...
  257. class Sub(Base):
  258. def done(self) -> None: # Error reported by type checker
  259. ...
  260. @final
  261. class Leaf:
  262. ...
  263. class Other(Leaf): # Error reported by type checker
  264. ...
  265. There is no runtime checking of these properties. The decorator
  266. sets the ``__final__`` attribute to ``True`` on the decorated object
  267. to allow runtime introspection.
  268. """
  269. try:
  270. f.__final__ = True
  271. except (AttributeError, TypeError):
  272. # Skip the attribute silently if it is not writable.
  273. # AttributeError happens if the object has __slots__ or a
  274. # read-only property, TypeError if it's a builtin class.
  275. pass
  276. return f
  277. if hasattr(typing, "disjoint_base"): # 3.15
  278. disjoint_base = typing.disjoint_base
  279. else:
  280. def disjoint_base(cls):
  281. """This decorator marks a class as a disjoint base.
  282. Child classes of a disjoint base cannot inherit from other disjoint bases that are
  283. not parent classes of the disjoint base.
  284. For example:
  285. @disjoint_base
  286. class Disjoint1: pass
  287. @disjoint_base
  288. class Disjoint2: pass
  289. class Disjoint3(Disjoint1, Disjoint2): pass # Type checker error
  290. Type checkers can use knowledge of disjoint bases to detect unreachable code
  291. and determine when two types can overlap.
  292. See PEP 800."""
  293. cls.__disjoint_base__ = True
  294. return cls
  295. def IntVar(name):
  296. return typing.TypeVar(name)
  297. # A Literal bug was fixed in 3.11.0, 3.10.1 and 3.9.8
  298. # Breakpoint: https://github.com/python/cpython/pull/29334
  299. if sys.version_info >= (3, 10, 1):
  300. Literal = typing.Literal
  301. else:
  302. def _flatten_literal_params(parameters):
  303. """An internal helper for Literal creation: flatten Literals among parameters"""
  304. params = []
  305. for p in parameters:
  306. if isinstance(p, _LiteralGenericAlias):
  307. params.extend(p.__args__)
  308. else:
  309. params.append(p)
  310. return tuple(params)
  311. def _value_and_type_iter(params):
  312. for p in params:
  313. yield p, type(p)
  314. class _LiteralGenericAlias(typing._GenericAlias, _root=True):
  315. def __eq__(self, other):
  316. if not isinstance(other, _LiteralGenericAlias):
  317. return NotImplemented
  318. these_args_deduped = set(_value_and_type_iter(self.__args__))
  319. other_args_deduped = set(_value_and_type_iter(other.__args__))
  320. return these_args_deduped == other_args_deduped
  321. def __hash__(self):
  322. return hash(frozenset(_value_and_type_iter(self.__args__)))
  323. class _LiteralForm(_ExtensionsSpecialForm, _root=True):
  324. def __init__(self, doc: str):
  325. self._name = 'Literal'
  326. self._doc = self.__doc__ = doc
  327. def __getitem__(self, parameters):
  328. if not isinstance(parameters, tuple):
  329. parameters = (parameters,)
  330. parameters = _flatten_literal_params(parameters)
  331. val_type_pairs = list(_value_and_type_iter(parameters))
  332. try:
  333. deduped_pairs = set(val_type_pairs)
  334. except TypeError:
  335. # unhashable parameters
  336. pass
  337. else:
  338. # similar logic to typing._deduplicate on Python 3.9+
  339. if len(deduped_pairs) < len(val_type_pairs):
  340. new_parameters = []
  341. for pair in val_type_pairs:
  342. if pair in deduped_pairs:
  343. new_parameters.append(pair[0])
  344. deduped_pairs.remove(pair)
  345. assert not deduped_pairs, deduped_pairs
  346. parameters = tuple(new_parameters)
  347. return _LiteralGenericAlias(self, parameters)
  348. Literal = _LiteralForm(doc="""\
  349. A type that can be used to indicate to type checkers
  350. that the corresponding value has a value literally equivalent
  351. to the provided parameter. For example:
  352. var: Literal[4] = 4
  353. The type checker understands that 'var' is literally equal to
  354. the value 4 and no other value.
  355. Literal[...] cannot be subclassed. There is no runtime
  356. checking verifying that the parameter is actually a value
  357. instead of a type.""")
  358. _overload_dummy = typing._overload_dummy
  359. if hasattr(typing, "get_overloads"): # 3.11+
  360. overload = typing.overload
  361. get_overloads = typing.get_overloads
  362. clear_overloads = typing.clear_overloads
  363. else:
  364. # {module: {qualname: {firstlineno: func}}}
  365. _overload_registry = collections.defaultdict(
  366. functools.partial(collections.defaultdict, dict)
  367. )
  368. def overload(func):
  369. """Decorator for overloaded functions/methods.
  370. In a stub file, place two or more stub definitions for the same
  371. function in a row, each decorated with @overload. For example:
  372. @overload
  373. def utf8(value: None) -> None: ...
  374. @overload
  375. def utf8(value: bytes) -> bytes: ...
  376. @overload
  377. def utf8(value: str) -> bytes: ...
  378. In a non-stub file (i.e. a regular .py file), do the same but
  379. follow it with an implementation. The implementation should *not*
  380. be decorated with @overload. For example:
  381. @overload
  382. def utf8(value: None) -> None: ...
  383. @overload
  384. def utf8(value: bytes) -> bytes: ...
  385. @overload
  386. def utf8(value: str) -> bytes: ...
  387. def utf8(value):
  388. # implementation goes here
  389. The overloads for a function can be retrieved at runtime using the
  390. get_overloads() function.
  391. """
  392. # classmethod and staticmethod
  393. f = getattr(func, "__func__", func)
  394. try:
  395. _overload_registry[f.__module__][f.__qualname__][
  396. f.__code__.co_firstlineno
  397. ] = func
  398. except AttributeError:
  399. # Not a normal function; ignore.
  400. pass
  401. return _overload_dummy
  402. def get_overloads(func):
  403. """Return all defined overloads for *func* as a sequence."""
  404. # classmethod and staticmethod
  405. f = getattr(func, "__func__", func)
  406. if f.__module__ not in _overload_registry:
  407. return []
  408. mod_dict = _overload_registry[f.__module__]
  409. if f.__qualname__ not in mod_dict:
  410. return []
  411. return list(mod_dict[f.__qualname__].values())
  412. def clear_overloads():
  413. """Clear all overloads in the registry."""
  414. _overload_registry.clear()
  415. # This is not a real generic class. Don't use outside annotations.
  416. Type = typing.Type
  417. # Various ABCs mimicking those in collections.abc.
  418. # A few are simply re-exported for completeness.
  419. Awaitable = typing.Awaitable
  420. Coroutine = typing.Coroutine
  421. AsyncIterable = typing.AsyncIterable
  422. AsyncIterator = typing.AsyncIterator
  423. Deque = typing.Deque
  424. DefaultDict = typing.DefaultDict
  425. OrderedDict = typing.OrderedDict
  426. Counter = typing.Counter
  427. ChainMap = typing.ChainMap
  428. Text = typing.Text
  429. TYPE_CHECKING = typing.TYPE_CHECKING
  430. # Breakpoint: https://github.com/python/cpython/pull/118681
  431. if sys.version_info >= (3, 13, 0, "beta"):
  432. from typing import AsyncContextManager, AsyncGenerator, ContextManager, Generator
  433. else:
  434. def _is_dunder(attr):
  435. return attr.startswith('__') and attr.endswith('__')
  436. class _SpecialGenericAlias(typing._SpecialGenericAlias, _root=True):
  437. def __init__(self, origin, nparams, *, inst=True, name=None, defaults=()):
  438. super().__init__(origin, nparams, inst=inst, name=name)
  439. self._defaults = defaults
  440. def __setattr__(self, attr, val):
  441. allowed_attrs = {'_name', '_inst', '_nparams', '_defaults'}
  442. if _is_dunder(attr) or attr in allowed_attrs:
  443. object.__setattr__(self, attr, val)
  444. else:
  445. setattr(self.__origin__, attr, val)
  446. @typing._tp_cache
  447. def __getitem__(self, params):
  448. if not isinstance(params, tuple):
  449. params = (params,)
  450. msg = "Parameters to generic types must be types."
  451. params = tuple(typing._type_check(p, msg) for p in params)
  452. if (
  453. self._defaults
  454. and len(params) < self._nparams
  455. and len(params) + len(self._defaults) >= self._nparams
  456. ):
  457. params = (*params, *self._defaults[len(params) - self._nparams:])
  458. actual_len = len(params)
  459. if actual_len != self._nparams:
  460. if self._defaults:
  461. expected = f"at least {self._nparams - len(self._defaults)}"
  462. else:
  463. expected = str(self._nparams)
  464. if not self._nparams:
  465. raise TypeError(f"{self} is not a generic class")
  466. raise TypeError(
  467. f"Too {'many' if actual_len > self._nparams else 'few'}"
  468. f" arguments for {self};"
  469. f" actual {actual_len}, expected {expected}"
  470. )
  471. return self.copy_with(params)
  472. _NoneType = type(None)
  473. Generator = _SpecialGenericAlias(
  474. collections.abc.Generator, 3, defaults=(_NoneType, _NoneType)
  475. )
  476. AsyncGenerator = _SpecialGenericAlias(
  477. collections.abc.AsyncGenerator, 2, defaults=(_NoneType,)
  478. )
  479. ContextManager = _SpecialGenericAlias(
  480. contextlib.AbstractContextManager,
  481. 2,
  482. name="ContextManager",
  483. defaults=(typing.Optional[bool],)
  484. )
  485. AsyncContextManager = _SpecialGenericAlias(
  486. contextlib.AbstractAsyncContextManager,
  487. 2,
  488. name="AsyncContextManager",
  489. defaults=(typing.Optional[bool],)
  490. )
  491. _PROTO_ALLOWLIST = {
  492. 'collections.abc': [
  493. 'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable',
  494. 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible', 'Buffer',
  495. ],
  496. 'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'],
  497. 'typing_extensions': ['Buffer'],
  498. }
  499. _EXCLUDED_ATTRS = frozenset(typing.EXCLUDED_ATTRIBUTES) | {
  500. "__match_args__", "__protocol_attrs__", "__non_callable_proto_members__",
  501. "__final__",
  502. }
  503. def _get_protocol_attrs(cls):
  504. attrs = set()
  505. for base in cls.__mro__[:-1]: # without object
  506. if base.__name__ in {'Protocol', 'Generic'}:
  507. continue
  508. annotations = getattr(base, '__annotations__', {})
  509. for attr in (*base.__dict__, *annotations):
  510. if (not attr.startswith('_abc_') and attr not in _EXCLUDED_ATTRS):
  511. attrs.add(attr)
  512. return attrs
  513. def _caller(depth=1, default='__main__'):
  514. try:
  515. return sys._getframemodulename(depth + 1) or default
  516. except AttributeError: # For platforms without _getframemodulename()
  517. pass
  518. try:
  519. return sys._getframe(depth + 1).f_globals.get('__name__', default)
  520. except (AttributeError, ValueError): # For platforms without _getframe()
  521. pass
  522. return None
  523. # `__match_args__` attribute was removed from protocol members in 3.13,
  524. # we want to backport this change to older Python versions.
  525. # Breakpoint: https://github.com/python/cpython/pull/110683
  526. if sys.version_info >= (3, 13):
  527. Protocol = typing.Protocol
  528. else:
  529. def _allow_reckless_class_checks(depth=2):
  530. """Allow instance and class checks for special stdlib modules.
  531. The abc and functools modules indiscriminately call isinstance() and
  532. issubclass() on the whole MRO of a user class, which may contain protocols.
  533. """
  534. return _caller(depth) in {'abc', 'functools', None}
  535. def _no_init(self, *args, **kwargs):
  536. if type(self)._is_protocol:
  537. raise TypeError('Protocols cannot be instantiated')
  538. def _type_check_issubclass_arg_1(arg):
  539. """Raise TypeError if `arg` is not an instance of `type`
  540. in `issubclass(arg, <protocol>)`.
  541. In most cases, this is verified by type.__subclasscheck__.
  542. Checking it again unnecessarily would slow down issubclass() checks,
  543. so, we don't perform this check unless we absolutely have to.
  544. For various error paths, however,
  545. we want to ensure that *this* error message is shown to the user
  546. where relevant, rather than a typing.py-specific error message.
  547. """
  548. if not isinstance(arg, type):
  549. # Same error message as for issubclass(1, int).
  550. raise TypeError('issubclass() arg 1 must be a class')
  551. # Inheriting from typing._ProtocolMeta isn't actually desirable,
  552. # but is necessary to allow typing.Protocol and typing_extensions.Protocol
  553. # to mix without getting TypeErrors about "metaclass conflict"
  554. class _ProtocolMeta(type(typing.Protocol)):
  555. # This metaclass is somewhat unfortunate,
  556. # but is necessary for several reasons...
  557. #
  558. # NOTE: DO NOT call super() in any methods in this class
  559. # That would call the methods on typing._ProtocolMeta on Python <=3.11
  560. # and those are slow
  561. def __new__(mcls, name, bases, namespace, **kwargs):
  562. if name == "Protocol" and len(bases) < 2:
  563. pass
  564. elif {Protocol, typing.Protocol} & set(bases):
  565. for base in bases:
  566. if not (
  567. base in {object, typing.Generic, Protocol, typing.Protocol}
  568. or base.__name__ in _PROTO_ALLOWLIST.get(base.__module__, [])
  569. or is_protocol(base)
  570. ):
  571. raise TypeError(
  572. f"Protocols can only inherit from other protocols, "
  573. f"got {base!r}"
  574. )
  575. return abc.ABCMeta.__new__(mcls, name, bases, namespace, **kwargs)
  576. def __init__(cls, *args, **kwargs):
  577. abc.ABCMeta.__init__(cls, *args, **kwargs)
  578. if getattr(cls, "_is_protocol", False):
  579. cls.__protocol_attrs__ = _get_protocol_attrs(cls)
  580. def __subclasscheck__(cls, other):
  581. if cls is Protocol:
  582. return type.__subclasscheck__(cls, other)
  583. if (
  584. getattr(cls, '_is_protocol', False)
  585. and not _allow_reckless_class_checks()
  586. ):
  587. if not getattr(cls, '_is_runtime_protocol', False):
  588. _type_check_issubclass_arg_1(other)
  589. raise TypeError(
  590. "Instance and class checks can only be used with "
  591. "@runtime_checkable protocols"
  592. )
  593. if (
  594. # this attribute is set by @runtime_checkable:
  595. cls.__non_callable_proto_members__
  596. and cls.__dict__.get("__subclasshook__") is _proto_hook
  597. ):
  598. _type_check_issubclass_arg_1(other)
  599. non_method_attrs = sorted(cls.__non_callable_proto_members__)
  600. raise TypeError(
  601. "Protocols with non-method members don't support issubclass()."
  602. f" Non-method members: {str(non_method_attrs)[1:-1]}."
  603. )
  604. return abc.ABCMeta.__subclasscheck__(cls, other)
  605. def __instancecheck__(cls, instance):
  606. # We need this method for situations where attributes are
  607. # assigned in __init__.
  608. if cls is Protocol:
  609. return type.__instancecheck__(cls, instance)
  610. if not getattr(cls, "_is_protocol", False):
  611. # i.e., it's a concrete subclass of a protocol
  612. return abc.ABCMeta.__instancecheck__(cls, instance)
  613. if (
  614. not getattr(cls, '_is_runtime_protocol', False) and
  615. not _allow_reckless_class_checks()
  616. ):
  617. raise TypeError("Instance and class checks can only be used with"
  618. " @runtime_checkable protocols")
  619. if abc.ABCMeta.__instancecheck__(cls, instance):
  620. return True
  621. for attr in cls.__protocol_attrs__:
  622. try:
  623. val = inspect.getattr_static(instance, attr)
  624. except AttributeError:
  625. break
  626. # this attribute is set by @runtime_checkable:
  627. if val is None and attr not in cls.__non_callable_proto_members__:
  628. break
  629. else:
  630. return True
  631. return False
  632. def __eq__(cls, other):
  633. # Hack so that typing.Generic.__class_getitem__
  634. # treats typing_extensions.Protocol
  635. # as equivalent to typing.Protocol
  636. if abc.ABCMeta.__eq__(cls, other) is True:
  637. return True
  638. return cls is Protocol and other is typing.Protocol
  639. # This has to be defined, or the abc-module cache
  640. # complains about classes with this metaclass being unhashable,
  641. # if we define only __eq__!
  642. def __hash__(cls) -> int:
  643. return type.__hash__(cls)
  644. @classmethod
  645. def _proto_hook(cls, other):
  646. if not cls.__dict__.get('_is_protocol', False):
  647. return NotImplemented
  648. for attr in cls.__protocol_attrs__:
  649. for base in other.__mro__:
  650. # Check if the members appears in the class dictionary...
  651. if attr in base.__dict__:
  652. if base.__dict__[attr] is None:
  653. return NotImplemented
  654. break
  655. # ...or in annotations, if it is a sub-protocol.
  656. annotations = getattr(base, '__annotations__', {})
  657. if (
  658. isinstance(annotations, collections.abc.Mapping)
  659. and attr in annotations
  660. and is_protocol(other)
  661. ):
  662. break
  663. else:
  664. return NotImplemented
  665. return True
  666. class Protocol(typing.Generic, metaclass=_ProtocolMeta):
  667. __doc__ = typing.Protocol.__doc__
  668. __slots__ = ()
  669. _is_protocol = True
  670. _is_runtime_protocol = False
  671. def __init_subclass__(cls, *args, **kwargs):
  672. super().__init_subclass__(*args, **kwargs)
  673. # Determine if this is a protocol or a concrete subclass.
  674. if not cls.__dict__.get('_is_protocol', False):
  675. cls._is_protocol = any(b is Protocol for b in cls.__bases__)
  676. # Set (or override) the protocol subclass hook.
  677. if '__subclasshook__' not in cls.__dict__:
  678. cls.__subclasshook__ = _proto_hook
  679. # Prohibit instantiation for protocol classes
  680. if cls._is_protocol and cls.__init__ is Protocol.__init__:
  681. cls.__init__ = _no_init
  682. # Breakpoint: https://github.com/python/cpython/pull/113401
  683. if sys.version_info >= (3, 13):
  684. runtime_checkable = typing.runtime_checkable
  685. else:
  686. def runtime_checkable(cls):
  687. """Mark a protocol class as a runtime protocol.
  688. Such protocol can be used with isinstance() and issubclass().
  689. Raise TypeError if applied to a non-protocol class.
  690. This allows a simple-minded structural check very similar to
  691. one trick ponies in collections.abc such as Iterable.
  692. For example::
  693. @runtime_checkable
  694. class Closable(Protocol):
  695. def close(self): ...
  696. assert isinstance(open('/some/file'), Closable)
  697. Warning: this will check only the presence of the required methods,
  698. not their type signatures!
  699. """
  700. if not issubclass(cls, typing.Generic) or not getattr(cls, '_is_protocol', False):
  701. raise TypeError(f'@runtime_checkable can be only applied to protocol classes,'
  702. f' got {cls!r}')
  703. cls._is_runtime_protocol = True
  704. # typing.Protocol classes on <=3.11 break if we execute this block,
  705. # because typing.Protocol classes on <=3.11 don't have a
  706. # `__protocol_attrs__` attribute, and this block relies on the
  707. # `__protocol_attrs__` attribute. Meanwhile, typing.Protocol classes on 3.12.2+
  708. # break if we *don't* execute this block, because *they* assume that all
  709. # protocol classes have a `__non_callable_proto_members__` attribute
  710. # (which this block sets)
  711. if isinstance(cls, _ProtocolMeta) or sys.version_info >= (3, 12, 2):
  712. # PEP 544 prohibits using issubclass()
  713. # with protocols that have non-method members.
  714. # See gh-113320 for why we compute this attribute here,
  715. # rather than in `_ProtocolMeta.__init__`
  716. cls.__non_callable_proto_members__ = set()
  717. for attr in cls.__protocol_attrs__:
  718. try:
  719. is_callable = callable(getattr(cls, attr, None))
  720. except Exception as e:
  721. raise TypeError(
  722. f"Failed to determine whether protocol member {attr!r} "
  723. "is a method member"
  724. ) from e
  725. else:
  726. if not is_callable:
  727. cls.__non_callable_proto_members__.add(attr)
  728. return cls
  729. # The "runtime" alias exists for backwards compatibility.
  730. runtime = runtime_checkable
  731. # Our version of runtime-checkable protocols is faster on Python <=3.11
  732. # Breakpoint: https://github.com/python/cpython/pull/112717
  733. if sys.version_info >= (3, 12):
  734. SupportsInt = typing.SupportsInt
  735. SupportsFloat = typing.SupportsFloat
  736. SupportsComplex = typing.SupportsComplex
  737. SupportsBytes = typing.SupportsBytes
  738. SupportsIndex = typing.SupportsIndex
  739. SupportsAbs = typing.SupportsAbs
  740. SupportsRound = typing.SupportsRound
  741. else:
  742. @runtime_checkable
  743. class SupportsInt(Protocol):
  744. """An ABC with one abstract method __int__."""
  745. __slots__ = ()
  746. @abc.abstractmethod
  747. def __int__(self) -> int:
  748. pass
  749. @runtime_checkable
  750. class SupportsFloat(Protocol):
  751. """An ABC with one abstract method __float__."""
  752. __slots__ = ()
  753. @abc.abstractmethod
  754. def __float__(self) -> float:
  755. pass
  756. @runtime_checkable
  757. class SupportsComplex(Protocol):
  758. """An ABC with one abstract method __complex__."""
  759. __slots__ = ()
  760. @abc.abstractmethod
  761. def __complex__(self) -> complex:
  762. pass
  763. @runtime_checkable
  764. class SupportsBytes(Protocol):
  765. """An ABC with one abstract method __bytes__."""
  766. __slots__ = ()
  767. @abc.abstractmethod
  768. def __bytes__(self) -> bytes:
  769. pass
  770. @runtime_checkable
  771. class SupportsIndex(Protocol):
  772. __slots__ = ()
  773. @abc.abstractmethod
  774. def __index__(self) -> int:
  775. pass
  776. @runtime_checkable
  777. class SupportsAbs(Protocol[T_co]):
  778. """
  779. An ABC with one abstract method __abs__ that is covariant in its return type.
  780. """
  781. __slots__ = ()
  782. @abc.abstractmethod
  783. def __abs__(self) -> T_co:
  784. pass
  785. @runtime_checkable
  786. class SupportsRound(Protocol[T_co]):
  787. """
  788. An ABC with one abstract method __round__ that is covariant in its return type.
  789. """
  790. __slots__ = ()
  791. @abc.abstractmethod
  792. def __round__(self, ndigits: int = 0) -> T_co:
  793. pass
  794. if hasattr(io, "Reader") and hasattr(io, "Writer"):
  795. Reader = io.Reader
  796. Writer = io.Writer
  797. else:
  798. @runtime_checkable
  799. class Reader(Protocol[T_co]):
  800. """Protocol for simple I/O reader instances.
  801. This protocol only supports blocking I/O.
  802. """
  803. __slots__ = ()
  804. @abc.abstractmethod
  805. def read(self, size: int = ..., /) -> T_co:
  806. """Read data from the input stream and return it.
  807. If *size* is specified, at most *size* items (bytes/characters) will be
  808. read.
  809. """
  810. @runtime_checkable
  811. class Writer(Protocol[T_contra]):
  812. """Protocol for simple I/O writer instances.
  813. This protocol only supports blocking I/O.
  814. """
  815. __slots__ = ()
  816. @abc.abstractmethod
  817. def write(self, data: T_contra, /) -> int:
  818. """Write *data* to the output stream and return the number of items written.""" # noqa: E501
  819. _NEEDS_SINGLETONMETA = (
  820. not hasattr(typing, "NoDefault") or not hasattr(typing, "NoExtraItems")
  821. )
  822. if _NEEDS_SINGLETONMETA:
  823. class SingletonMeta(type):
  824. def __setattr__(cls, attr, value):
  825. # TypeError is consistent with the behavior of NoneType
  826. raise TypeError(
  827. f"cannot set {attr!r} attribute of immutable type {cls.__name__!r}"
  828. )
  829. if hasattr(typing, "NoDefault"):
  830. NoDefault = typing.NoDefault
  831. else:
  832. class NoDefaultType(metaclass=SingletonMeta):
  833. """The type of the NoDefault singleton."""
  834. __slots__ = ()
  835. def __new__(cls):
  836. return globals().get("NoDefault") or object.__new__(cls)
  837. def __repr__(self):
  838. return "typing_extensions.NoDefault"
  839. def __reduce__(self):
  840. return "NoDefault"
  841. NoDefault = NoDefaultType()
  842. del NoDefaultType
  843. if hasattr(typing, "NoExtraItems"):
  844. NoExtraItems = typing.NoExtraItems
  845. else:
  846. class NoExtraItemsType(metaclass=SingletonMeta):
  847. """The type of the NoExtraItems singleton."""
  848. __slots__ = ()
  849. def __new__(cls):
  850. return globals().get("NoExtraItems") or object.__new__(cls)
  851. def __repr__(self):
  852. return "typing_extensions.NoExtraItems"
  853. def __reduce__(self):
  854. return "NoExtraItems"
  855. NoExtraItems = NoExtraItemsType()
  856. del NoExtraItemsType
  857. if _NEEDS_SINGLETONMETA:
  858. del SingletonMeta
  859. # Update this to something like >=3.13.0b1 if and when
  860. # PEP 728 is implemented in CPython
  861. _PEP_728_IMPLEMENTED = False
  862. if _PEP_728_IMPLEMENTED:
  863. # The standard library TypedDict in Python 3.9.0/1 does not honour the "total"
  864. # keyword with old-style TypedDict(). See https://bugs.python.org/issue42059
  865. # The standard library TypedDict below Python 3.11 does not store runtime
  866. # information about optional and required keys when using Required or NotRequired.
  867. # Generic TypedDicts are also impossible using typing.TypedDict on Python <3.11.
  868. # Aaaand on 3.12 we add __orig_bases__ to TypedDict
  869. # to enable better runtime introspection.
  870. # On 3.13 we deprecate some odd ways of creating TypedDicts.
  871. # Also on 3.13, PEP 705 adds the ReadOnly[] qualifier.
  872. # PEP 728 (still pending) makes more changes.
  873. TypedDict = typing.TypedDict
  874. _TypedDictMeta = typing._TypedDictMeta
  875. is_typeddict = typing.is_typeddict
  876. else:
  877. # 3.10.0 and later
  878. _TAKES_MODULE = "module" in inspect.signature(typing._type_check).parameters
  879. def _get_typeddict_qualifiers(annotation_type):
  880. while True:
  881. annotation_origin = get_origin(annotation_type)
  882. if annotation_origin is Annotated:
  883. annotation_args = get_args(annotation_type)
  884. if annotation_args:
  885. annotation_type = annotation_args[0]
  886. else:
  887. break
  888. elif annotation_origin is Required:
  889. yield Required
  890. annotation_type, = get_args(annotation_type)
  891. elif annotation_origin is NotRequired:
  892. yield NotRequired
  893. annotation_type, = get_args(annotation_type)
  894. elif annotation_origin is ReadOnly:
  895. yield ReadOnly
  896. annotation_type, = get_args(annotation_type)
  897. else:
  898. break
  899. class _TypedDictMeta(type):
  900. def __new__(cls, name, bases, ns, *, total=True, closed=None,
  901. extra_items=NoExtraItems):
  902. """Create new typed dict class object.
  903. This method is called when TypedDict is subclassed,
  904. or when TypedDict is instantiated. This way
  905. TypedDict supports all three syntax forms described in its docstring.
  906. Subclasses and instances of TypedDict return actual dictionaries.
  907. """
  908. for base in bases:
  909. if type(base) is not _TypedDictMeta and base is not typing.Generic:
  910. raise TypeError('cannot inherit from both a TypedDict type '
  911. 'and a non-TypedDict base class')
  912. if closed is not None and extra_items is not NoExtraItems:
  913. raise TypeError(f"Cannot combine closed={closed!r} and extra_items")
  914. if any(issubclass(b, typing.Generic) for b in bases):
  915. generic_base = (typing.Generic,)
  916. else:
  917. generic_base = ()
  918. ns_annotations = ns.pop('__annotations__', None)
  919. # typing.py generally doesn't let you inherit from plain Generic, unless
  920. # the name of the class happens to be "Protocol"
  921. tp_dict = type.__new__(_TypedDictMeta, "Protocol", (*generic_base, dict), ns)
  922. tp_dict.__name__ = name
  923. if tp_dict.__qualname__ == "Protocol":
  924. tp_dict.__qualname__ = name
  925. if not hasattr(tp_dict, '__orig_bases__'):
  926. tp_dict.__orig_bases__ = bases
  927. annotations = {}
  928. own_annotate = None
  929. if ns_annotations is not None:
  930. own_annotations = ns_annotations
  931. elif sys.version_info >= (3, 14):
  932. if hasattr(annotationlib, "get_annotate_from_class_namespace"):
  933. own_annotate = annotationlib.get_annotate_from_class_namespace(ns)
  934. else:
  935. # 3.14.0a7 and earlier
  936. own_annotate = ns.get("__annotate__")
  937. if own_annotate is not None:
  938. own_annotations = annotationlib.call_annotate_function(
  939. own_annotate, Format.FORWARDREF, owner=tp_dict
  940. )
  941. else:
  942. own_annotations = {}
  943. else:
  944. own_annotations = {}
  945. msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
  946. if _TAKES_MODULE:
  947. own_checked_annotations = {
  948. n: typing._type_check(tp, msg, module=tp_dict.__module__)
  949. for n, tp in own_annotations.items()
  950. }
  951. else:
  952. own_checked_annotations = {
  953. n: typing._type_check(tp, msg)
  954. for n, tp in own_annotations.items()
  955. }
  956. required_keys = set()
  957. optional_keys = set()
  958. readonly_keys = set()
  959. mutable_keys = set()
  960. extra_items_type = extra_items
  961. for base in bases:
  962. base_dict = base.__dict__
  963. if sys.version_info <= (3, 14):
  964. annotations.update(base_dict.get('__annotations__', {}))
  965. required_keys.update(base_dict.get('__required_keys__', ()))
  966. optional_keys.update(base_dict.get('__optional_keys__', ()))
  967. readonly_keys.update(base_dict.get('__readonly_keys__', ()))
  968. mutable_keys.update(base_dict.get('__mutable_keys__', ()))
  969. # This was specified in an earlier version of PEP 728. Support
  970. # is retained for backwards compatibility, but only for Python
  971. # 3.13 and lower.
  972. if (closed and sys.version_info < (3, 14)
  973. and "__extra_items__" in own_checked_annotations):
  974. annotation_type = own_checked_annotations.pop("__extra_items__")
  975. qualifiers = set(_get_typeddict_qualifiers(annotation_type))
  976. if Required in qualifiers:
  977. raise TypeError(
  978. "Special key __extra_items__ does not support "
  979. "Required"
  980. )
  981. if NotRequired in qualifiers:
  982. raise TypeError(
  983. "Special key __extra_items__ does not support "
  984. "NotRequired"
  985. )
  986. extra_items_type = annotation_type
  987. annotations.update(own_checked_annotations)
  988. for annotation_key, annotation_type in own_checked_annotations.items():
  989. qualifiers = set(_get_typeddict_qualifiers(annotation_type))
  990. if Required in qualifiers:
  991. required_keys.add(annotation_key)
  992. elif NotRequired in qualifiers:
  993. optional_keys.add(annotation_key)
  994. elif total:
  995. required_keys.add(annotation_key)
  996. else:
  997. optional_keys.add(annotation_key)
  998. if ReadOnly in qualifiers:
  999. mutable_keys.discard(annotation_key)
  1000. readonly_keys.add(annotation_key)
  1001. else:
  1002. mutable_keys.add(annotation_key)
  1003. readonly_keys.discard(annotation_key)
  1004. # Breakpoint: https://github.com/python/cpython/pull/119891
  1005. if sys.version_info >= (3, 14):
  1006. def __annotate__(format):
  1007. annos = {}
  1008. for base in bases:
  1009. if base is Generic:
  1010. continue
  1011. base_annotate = base.__annotate__
  1012. if base_annotate is None:
  1013. continue
  1014. base_annos = annotationlib.call_annotate_function(
  1015. base_annotate, format, owner=base)
  1016. annos.update(base_annos)
  1017. if own_annotate is not None:
  1018. own = annotationlib.call_annotate_function(
  1019. own_annotate, format, owner=tp_dict)
  1020. if format != Format.STRING:
  1021. own = {
  1022. n: typing._type_check(tp, msg, module=tp_dict.__module__)
  1023. for n, tp in own.items()
  1024. }
  1025. elif format == Format.STRING:
  1026. own = annotationlib.annotations_to_string(own_annotations)
  1027. elif format in (Format.FORWARDREF, Format.VALUE):
  1028. own = own_checked_annotations
  1029. else:
  1030. raise NotImplementedError(format)
  1031. annos.update(own)
  1032. return annos
  1033. tp_dict.__annotate__ = __annotate__
  1034. else:
  1035. tp_dict.__annotations__ = annotations
  1036. tp_dict.__required_keys__ = frozenset(required_keys)
  1037. tp_dict.__optional_keys__ = frozenset(optional_keys)
  1038. tp_dict.__readonly_keys__ = frozenset(readonly_keys)
  1039. tp_dict.__mutable_keys__ = frozenset(mutable_keys)
  1040. tp_dict.__total__ = total
  1041. tp_dict.__closed__ = closed
  1042. tp_dict.__extra_items__ = extra_items_type
  1043. return tp_dict
  1044. __call__ = dict # static method
  1045. def __subclasscheck__(cls, other):
  1046. # Typed dicts are only for static structural subtyping.
  1047. raise TypeError('TypedDict does not support instance and class checks')
  1048. __instancecheck__ = __subclasscheck__
  1049. _TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {})
  1050. def _create_typeddict(
  1051. typename,
  1052. fields,
  1053. /,
  1054. *,
  1055. typing_is_inline,
  1056. total,
  1057. closed,
  1058. extra_items,
  1059. **kwargs,
  1060. ):
  1061. if fields is _marker or fields is None:
  1062. if fields is _marker:
  1063. deprecated_thing = (
  1064. "Failing to pass a value for the 'fields' parameter"
  1065. )
  1066. else:
  1067. deprecated_thing = "Passing `None` as the 'fields' parameter"
  1068. example = f"`{typename} = TypedDict({typename!r}, {{}})`"
  1069. deprecation_msg = (
  1070. f"{deprecated_thing} is deprecated and will be disallowed in "
  1071. "Python 3.15. To create a TypedDict class with 0 fields "
  1072. "using the functional syntax, pass an empty dictionary, e.g. "
  1073. ) + example + "."
  1074. warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2)
  1075. # Support a field called "closed"
  1076. if closed is not False and closed is not True and closed is not None:
  1077. kwargs["closed"] = closed
  1078. closed = None
  1079. # Or "extra_items"
  1080. if extra_items is not NoExtraItems:
  1081. kwargs["extra_items"] = extra_items
  1082. extra_items = NoExtraItems
  1083. fields = kwargs
  1084. elif kwargs:
  1085. raise TypeError("TypedDict takes either a dict or keyword arguments,"
  1086. " but not both")
  1087. if kwargs:
  1088. # Breakpoint: https://github.com/python/cpython/pull/104891
  1089. if sys.version_info >= (3, 13):
  1090. raise TypeError("TypedDict takes no keyword arguments")
  1091. warnings.warn(
  1092. "The kwargs-based syntax for TypedDict definitions is deprecated "
  1093. "in Python 3.11, will be removed in Python 3.13, and may not be "
  1094. "understood by third-party type checkers.",
  1095. DeprecationWarning,
  1096. stacklevel=2,
  1097. )
  1098. ns = {'__annotations__': dict(fields)}
  1099. module = _caller(depth=4 if typing_is_inline else 2)
  1100. if module is not None:
  1101. # Setting correct module is necessary to make typed dict classes
  1102. # pickleable.
  1103. ns['__module__'] = module
  1104. td = _TypedDictMeta(typename, (), ns, total=total, closed=closed,
  1105. extra_items=extra_items)
  1106. td.__orig_bases__ = (TypedDict,)
  1107. return td
  1108. class _TypedDictSpecialForm(_SpecialForm, _root=True):
  1109. def __call__(
  1110. self,
  1111. typename,
  1112. fields=_marker,
  1113. /,
  1114. *,
  1115. total=True,
  1116. closed=None,
  1117. extra_items=NoExtraItems,
  1118. **kwargs
  1119. ):
  1120. return _create_typeddict(
  1121. typename,
  1122. fields,
  1123. typing_is_inline=False,
  1124. total=total,
  1125. closed=closed,
  1126. extra_items=extra_items,
  1127. **kwargs,
  1128. )
  1129. def __mro_entries__(self, bases):
  1130. return (_TypedDict,)
  1131. @_TypedDictSpecialForm
  1132. def TypedDict(self, args):
  1133. """A simple typed namespace. At runtime it is equivalent to a plain dict.
  1134. TypedDict creates a dictionary type such that a type checker will expect all
  1135. instances to have a certain set of keys, where each key is
  1136. associated with a value of a consistent type. This expectation
  1137. is not checked at runtime.
  1138. Usage::
  1139. class Point2D(TypedDict):
  1140. x: int
  1141. y: int
  1142. label: str
  1143. a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
  1144. b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
  1145. assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
  1146. The type info can be accessed via the Point2D.__annotations__ dict, and
  1147. the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
  1148. TypedDict supports an additional equivalent form::
  1149. Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
  1150. By default, all keys must be present in a TypedDict. It is possible
  1151. to override this by specifying totality::
  1152. class Point2D(TypedDict, total=False):
  1153. x: int
  1154. y: int
  1155. This means that a Point2D TypedDict can have any of the keys omitted. A type
  1156. checker is only expected to support a literal False or True as the value of
  1157. the total argument. True is the default, and makes all items defined in the
  1158. class body be required.
  1159. The Required and NotRequired special forms can also be used to mark
  1160. individual keys as being required or not required::
  1161. class Point2D(TypedDict):
  1162. x: int # the "x" key must always be present (Required is the default)
  1163. y: NotRequired[int] # the "y" key can be omitted
  1164. See PEP 655 for more details on Required and NotRequired.
  1165. """
  1166. # This runs when creating inline TypedDicts:
  1167. if not isinstance(args, dict):
  1168. raise TypeError(
  1169. "TypedDict[...] should be used with a single dict argument"
  1170. )
  1171. return _create_typeddict(
  1172. "<inline TypedDict>",
  1173. args,
  1174. typing_is_inline=True,
  1175. total=True,
  1176. closed=True,
  1177. extra_items=NoExtraItems,
  1178. )
  1179. _TYPEDDICT_TYPES = (typing._TypedDictMeta, _TypedDictMeta)
  1180. def is_typeddict(tp):
  1181. """Check if an annotation is a TypedDict class
  1182. For example::
  1183. class Film(TypedDict):
  1184. title: str
  1185. year: int
  1186. is_typeddict(Film) # => True
  1187. is_typeddict(Union[list, str]) # => False
  1188. """
  1189. return isinstance(tp, _TYPEDDICT_TYPES)
  1190. if hasattr(typing, "assert_type"):
  1191. assert_type = typing.assert_type
  1192. else:
  1193. def assert_type(val, typ, /):
  1194. """Assert (to the type checker) that the value is of the given type.
  1195. When the type checker encounters a call to assert_type(), it
  1196. emits an error if the value is not of the specified type::
  1197. def greet(name: str) -> None:
  1198. assert_type(name, str) # ok
  1199. assert_type(name, int) # type checker error
  1200. At runtime this returns the first argument unchanged and otherwise
  1201. does nothing.
  1202. """
  1203. return val
  1204. if hasattr(typing, "ReadOnly"): # 3.13+
  1205. get_type_hints = typing.get_type_hints
  1206. else: # <=3.13
  1207. # replaces _strip_annotations()
  1208. def _strip_extras(t):
  1209. """Strips Annotated, Required and NotRequired from a given type."""
  1210. if isinstance(t, typing._AnnotatedAlias):
  1211. return _strip_extras(t.__origin__)
  1212. if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired, ReadOnly):
  1213. return _strip_extras(t.__args__[0])
  1214. if isinstance(t, typing._GenericAlias):
  1215. stripped_args = tuple(_strip_extras(a) for a in t.__args__)
  1216. if stripped_args == t.__args__:
  1217. return t
  1218. return t.copy_with(stripped_args)
  1219. if hasattr(_types, "GenericAlias") and isinstance(t, _types.GenericAlias):
  1220. stripped_args = tuple(_strip_extras(a) for a in t.__args__)
  1221. if stripped_args == t.__args__:
  1222. return t
  1223. return _types.GenericAlias(t.__origin__, stripped_args)
  1224. if hasattr(_types, "UnionType") and isinstance(t, _types.UnionType):
  1225. stripped_args = tuple(_strip_extras(a) for a in t.__args__)
  1226. if stripped_args == t.__args__:
  1227. return t
  1228. return functools.reduce(operator.or_, stripped_args)
  1229. return t
  1230. def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
  1231. """Return type hints for an object.
  1232. This is often the same as obj.__annotations__, but it handles
  1233. forward references encoded as string literals, adds Optional[t] if a
  1234. default value equal to None is set and recursively replaces all
  1235. 'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T'
  1236. (unless 'include_extras=True').
  1237. The argument may be a module, class, method, or function. The annotations
  1238. are returned as a dictionary. For classes, annotations include also
  1239. inherited members.
  1240. TypeError is raised if the argument is not of a type that can contain
  1241. annotations, and an empty dictionary is returned if no annotations are
  1242. present.
  1243. BEWARE -- the behavior of globalns and localns is counterintuitive
  1244. (unless you are familiar with how eval() and exec() work). The
  1245. search order is locals first, then globals.
  1246. - If no dict arguments are passed, an attempt is made to use the
  1247. globals from obj (or the respective module's globals for classes),
  1248. and these are also used as the locals. If the object does not appear
  1249. to have globals, an empty dictionary is used.
  1250. - If one dict argument is passed, it is used for both globals and
  1251. locals.
  1252. - If two dict arguments are passed, they specify globals and
  1253. locals, respectively.
  1254. """
  1255. hint = typing.get_type_hints(
  1256. obj, globalns=globalns, localns=localns, include_extras=True
  1257. )
  1258. # Breakpoint: https://github.com/python/cpython/pull/30304
  1259. if sys.version_info < (3, 11):
  1260. _clean_optional(obj, hint, globalns, localns)
  1261. if include_extras:
  1262. return hint
  1263. return {k: _strip_extras(t) for k, t in hint.items()}
  1264. _NoneType = type(None)
  1265. def _could_be_inserted_optional(t):
  1266. """detects Union[..., None] pattern"""
  1267. if not isinstance(t, typing._UnionGenericAlias):
  1268. return False
  1269. # Assume if last argument is not None they are user defined
  1270. if t.__args__[-1] is not _NoneType:
  1271. return False
  1272. return True
  1273. # < 3.11
  1274. def _clean_optional(obj, hints, globalns=None, localns=None):
  1275. # reverts injected Union[..., None] cases from typing.get_type_hints
  1276. # when a None default value is used.
  1277. # see https://github.com/python/typing_extensions/issues/310
  1278. if not hints or isinstance(obj, type):
  1279. return
  1280. defaults = typing._get_defaults(obj) # avoid accessing __annotations___
  1281. if not defaults:
  1282. return
  1283. original_hints = obj.__annotations__
  1284. for name, value in hints.items():
  1285. # Not a Union[..., None] or replacement conditions not fullfilled
  1286. if (not _could_be_inserted_optional(value)
  1287. or name not in defaults
  1288. or defaults[name] is not None
  1289. ):
  1290. continue
  1291. original_value = original_hints[name]
  1292. # value=NoneType should have caused a skip above but check for safety
  1293. if original_value is None:
  1294. original_value = _NoneType
  1295. # Forward reference
  1296. if isinstance(original_value, str):
  1297. if globalns is None:
  1298. if isinstance(obj, _types.ModuleType):
  1299. globalns = obj.__dict__
  1300. else:
  1301. nsobj = obj
  1302. # Find globalns for the unwrapped object.
  1303. while hasattr(nsobj, '__wrapped__'):
  1304. nsobj = nsobj.__wrapped__
  1305. globalns = getattr(nsobj, '__globals__', {})
  1306. if localns is None:
  1307. localns = globalns
  1308. elif localns is None:
  1309. localns = globalns
  1310. original_value = ForwardRef(
  1311. original_value,
  1312. is_argument=not isinstance(obj, _types.ModuleType)
  1313. )
  1314. original_evaluated = typing._eval_type(original_value, globalns, localns)
  1315. # Compare if values differ. Note that even if equal
  1316. # value might be cached by typing._tp_cache contrary to original_evaluated
  1317. if original_evaluated != value or (
  1318. # 3.10: ForwardRefs of UnionType might be turned into _UnionGenericAlias
  1319. hasattr(_types, "UnionType")
  1320. and isinstance(original_evaluated, _types.UnionType)
  1321. and not isinstance(value, _types.UnionType)
  1322. ):
  1323. hints[name] = original_evaluated
  1324. # Python 3.9 has get_origin() and get_args() but those implementations don't support
  1325. # ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do.
  1326. # Breakpoint: https://github.com/python/cpython/pull/25298
  1327. if sys.version_info >= (3, 10):
  1328. get_origin = typing.get_origin
  1329. get_args = typing.get_args
  1330. # 3.9
  1331. else:
  1332. def get_origin(tp):
  1333. """Get the unsubscripted version of a type.
  1334. This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
  1335. and Annotated. Return None for unsupported types. Examples::
  1336. get_origin(Literal[42]) is Literal
  1337. get_origin(int) is None
  1338. get_origin(ClassVar[int]) is ClassVar
  1339. get_origin(Generic) is Generic
  1340. get_origin(Generic[T]) is Generic
  1341. get_origin(Union[T, int]) is Union
  1342. get_origin(List[Tuple[T, T]][int]) == list
  1343. get_origin(P.args) is P
  1344. """
  1345. if isinstance(tp, typing._AnnotatedAlias):
  1346. return Annotated
  1347. if isinstance(tp, (typing._BaseGenericAlias, _types.GenericAlias,
  1348. ParamSpecArgs, ParamSpecKwargs)):
  1349. return tp.__origin__
  1350. if tp is typing.Generic:
  1351. return typing.Generic
  1352. return None
  1353. def get_args(tp):
  1354. """Get type arguments with all substitutions performed.
  1355. For unions, basic simplifications used by Union constructor are performed.
  1356. Examples::
  1357. get_args(Dict[str, int]) == (str, int)
  1358. get_args(int) == ()
  1359. get_args(Union[int, Union[T, int], str][int]) == (int, str)
  1360. get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
  1361. get_args(Callable[[], T][int]) == ([], int)
  1362. """
  1363. if isinstance(tp, typing._AnnotatedAlias):
  1364. return (tp.__origin__, *tp.__metadata__)
  1365. if isinstance(tp, (typing._GenericAlias, _types.GenericAlias)):
  1366. res = tp.__args__
  1367. if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis:
  1368. res = (list(res[:-1]), res[-1])
  1369. return res
  1370. return ()
  1371. # 3.10+
  1372. if hasattr(typing, 'TypeAlias'):
  1373. TypeAlias = typing.TypeAlias
  1374. # 3.9
  1375. else:
  1376. @_ExtensionsSpecialForm
  1377. def TypeAlias(self, parameters):
  1378. """Special marker indicating that an assignment should
  1379. be recognized as a proper type alias definition by type
  1380. checkers.
  1381. For example::
  1382. Predicate: TypeAlias = Callable[..., bool]
  1383. It's invalid when used anywhere except as in the example above.
  1384. """
  1385. raise TypeError(f"{self} is not subscriptable")
  1386. def _set_default(type_param, default):
  1387. type_param.has_default = lambda: default is not NoDefault
  1388. type_param.__default__ = default
  1389. def _set_module(typevarlike):
  1390. # for pickling:
  1391. def_mod = _caller(depth=2)
  1392. if def_mod != 'typing_extensions':
  1393. typevarlike.__module__ = def_mod
  1394. class _DefaultMixin:
  1395. """Mixin for TypeVarLike defaults."""
  1396. __slots__ = ()
  1397. __init__ = _set_default
  1398. # Classes using this metaclass must provide a _backported_typevarlike ClassVar
  1399. class _TypeVarLikeMeta(type):
  1400. def __instancecheck__(cls, __instance: Any) -> bool:
  1401. return isinstance(__instance, cls._backported_typevarlike)
  1402. if _PEP_696_IMPLEMENTED:
  1403. from typing import TypeVar
  1404. else:
  1405. # Add default and infer_variance parameters from PEP 696 and 695
  1406. class TypeVar(metaclass=_TypeVarLikeMeta):
  1407. """Type variable."""
  1408. _backported_typevarlike = typing.TypeVar
  1409. def __new__(cls, name, *constraints, bound=None,
  1410. covariant=False, contravariant=False,
  1411. default=NoDefault, infer_variance=False):
  1412. if hasattr(typing, "TypeAliasType"):
  1413. # PEP 695 implemented (3.12+), can pass infer_variance to typing.TypeVar
  1414. typevar = typing.TypeVar(name, *constraints, bound=bound,
  1415. covariant=covariant, contravariant=contravariant,
  1416. infer_variance=infer_variance)
  1417. else:
  1418. typevar = typing.TypeVar(name, *constraints, bound=bound,
  1419. covariant=covariant, contravariant=contravariant)
  1420. if infer_variance and (covariant or contravariant):
  1421. raise ValueError("Variance cannot be specified with infer_variance.")
  1422. typevar.__infer_variance__ = infer_variance
  1423. _set_default(typevar, default)
  1424. _set_module(typevar)
  1425. def _tvar_prepare_subst(alias, args):
  1426. if (
  1427. typevar.has_default()
  1428. and alias.__parameters__.index(typevar) == len(args)
  1429. ):
  1430. args += (typevar.__default__,)
  1431. return args
  1432. typevar.__typing_prepare_subst__ = _tvar_prepare_subst
  1433. return typevar
  1434. def __init_subclass__(cls) -> None:
  1435. raise TypeError(f"type '{__name__}.TypeVar' is not an acceptable base type")
  1436. # Python 3.10+ has PEP 612
  1437. if hasattr(typing, 'ParamSpecArgs'):
  1438. ParamSpecArgs = typing.ParamSpecArgs
  1439. ParamSpecKwargs = typing.ParamSpecKwargs
  1440. # 3.9
  1441. else:
  1442. class _Immutable:
  1443. """Mixin to indicate that object should not be copied."""
  1444. __slots__ = ()
  1445. def __copy__(self):
  1446. return self
  1447. def __deepcopy__(self, memo):
  1448. return self
  1449. class ParamSpecArgs(_Immutable):
  1450. """The args for a ParamSpec object.
  1451. Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.
  1452. ParamSpecArgs objects have a reference back to their ParamSpec:
  1453. P.args.__origin__ is P
  1454. This type is meant for runtime introspection and has no special meaning to
  1455. static type checkers.
  1456. """
  1457. def __init__(self, origin):
  1458. self.__origin__ = origin
  1459. def __repr__(self):
  1460. return f"{self.__origin__.__name__}.args"
  1461. def __eq__(self, other):
  1462. if not isinstance(other, ParamSpecArgs):
  1463. return NotImplemented
  1464. return self.__origin__ == other.__origin__
  1465. class ParamSpecKwargs(_Immutable):
  1466. """The kwargs for a ParamSpec object.
  1467. Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs.
  1468. ParamSpecKwargs objects have a reference back to their ParamSpec:
  1469. P.kwargs.__origin__ is P
  1470. This type is meant for runtime introspection and has no special meaning to
  1471. static type checkers.
  1472. """
  1473. def __init__(self, origin):
  1474. self.__origin__ = origin
  1475. def __repr__(self):
  1476. return f"{self.__origin__.__name__}.kwargs"
  1477. def __eq__(self, other):
  1478. if not isinstance(other, ParamSpecKwargs):
  1479. return NotImplemented
  1480. return self.__origin__ == other.__origin__
  1481. if _PEP_696_IMPLEMENTED:
  1482. from typing import ParamSpec
  1483. # 3.10+
  1484. elif hasattr(typing, 'ParamSpec'):
  1485. # Add default parameter - PEP 696
  1486. class ParamSpec(metaclass=_TypeVarLikeMeta):
  1487. """Parameter specification."""
  1488. _backported_typevarlike = typing.ParamSpec
  1489. def __new__(cls, name, *, bound=None,
  1490. covariant=False, contravariant=False,
  1491. infer_variance=False, default=NoDefault):
  1492. if hasattr(typing, "TypeAliasType"):
  1493. # PEP 695 implemented, can pass infer_variance to typing.TypeVar
  1494. paramspec = typing.ParamSpec(name, bound=bound,
  1495. covariant=covariant,
  1496. contravariant=contravariant,
  1497. infer_variance=infer_variance)
  1498. else:
  1499. paramspec = typing.ParamSpec(name, bound=bound,
  1500. covariant=covariant,
  1501. contravariant=contravariant)
  1502. paramspec.__infer_variance__ = infer_variance
  1503. _set_default(paramspec, default)
  1504. _set_module(paramspec)
  1505. def _paramspec_prepare_subst(alias, args):
  1506. params = alias.__parameters__
  1507. i = params.index(paramspec)
  1508. if i == len(args) and paramspec.has_default():
  1509. args = [*args, paramspec.__default__]
  1510. if i >= len(args):
  1511. raise TypeError(f"Too few arguments for {alias}")
  1512. # Special case where Z[[int, str, bool]] == Z[int, str, bool] in PEP 612.
  1513. if len(params) == 1 and not typing._is_param_expr(args[0]):
  1514. assert i == 0
  1515. args = (args,)
  1516. # Convert lists to tuples to help other libraries cache the results.
  1517. elif isinstance(args[i], list):
  1518. args = (*args[:i], tuple(args[i]), *args[i + 1:])
  1519. return args
  1520. paramspec.__typing_prepare_subst__ = _paramspec_prepare_subst
  1521. return paramspec
  1522. def __init_subclass__(cls) -> None:
  1523. raise TypeError(f"type '{__name__}.ParamSpec' is not an acceptable base type")
  1524. # 3.9
  1525. else:
  1526. # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
  1527. class ParamSpec(list, _DefaultMixin):
  1528. """Parameter specification variable.
  1529. Usage::
  1530. P = ParamSpec('P')
  1531. Parameter specification variables exist primarily for the benefit of static
  1532. type checkers. They are used to forward the parameter types of one
  1533. callable to another callable, a pattern commonly found in higher order
  1534. functions and decorators. They are only valid when used in ``Concatenate``,
  1535. or s the first argument to ``Callable``. In Python 3.10 and higher,
  1536. they are also supported in user-defined Generics at runtime.
  1537. See class Generic for more information on generic types. An
  1538. example for annotating a decorator::
  1539. T = TypeVar('T')
  1540. P = ParamSpec('P')
  1541. def add_logging(f: Callable[P, T]) -> Callable[P, T]:
  1542. '''A type-safe decorator to add logging to a function.'''
  1543. def inner(*args: P.args, **kwargs: P.kwargs) -> T:
  1544. logging.info(f'{f.__name__} was called')
  1545. return f(*args, **kwargs)
  1546. return inner
  1547. @add_logging
  1548. def add_two(x: float, y: float) -> float:
  1549. '''Add two numbers together.'''
  1550. return x + y
  1551. Parameter specification variables defined with covariant=True or
  1552. contravariant=True can be used to declare covariant or contravariant
  1553. generic types. These keyword arguments are valid, but their actual semantics
  1554. are yet to be decided. See PEP 612 for details.
  1555. Parameter specification variables can be introspected. e.g.:
  1556. P.__name__ == 'T'
  1557. P.__bound__ == None
  1558. P.__covariant__ == False
  1559. P.__contravariant__ == False
  1560. Note that only parameter specification variables defined in global scope can
  1561. be pickled.
  1562. """
  1563. # Trick Generic __parameters__.
  1564. __class__ = typing.TypeVar
  1565. @property
  1566. def args(self):
  1567. return ParamSpecArgs(self)
  1568. @property
  1569. def kwargs(self):
  1570. return ParamSpecKwargs(self)
  1571. def __init__(self, name, *, bound=None, covariant=False, contravariant=False,
  1572. infer_variance=False, default=NoDefault):
  1573. list.__init__(self, [self])
  1574. self.__name__ = name
  1575. self.__covariant__ = bool(covariant)
  1576. self.__contravariant__ = bool(contravariant)
  1577. self.__infer_variance__ = bool(infer_variance)
  1578. if bound:
  1579. self.__bound__ = typing._type_check(bound, 'Bound must be a type.')
  1580. else:
  1581. self.__bound__ = None
  1582. _DefaultMixin.__init__(self, default)
  1583. # for pickling:
  1584. def_mod = _caller()
  1585. if def_mod != 'typing_extensions':
  1586. self.__module__ = def_mod
  1587. def __repr__(self):
  1588. if self.__infer_variance__:
  1589. prefix = ''
  1590. elif self.__covariant__:
  1591. prefix = '+'
  1592. elif self.__contravariant__:
  1593. prefix = '-'
  1594. else:
  1595. prefix = '~'
  1596. return prefix + self.__name__
  1597. def __hash__(self):
  1598. return object.__hash__(self)
  1599. def __eq__(self, other):
  1600. return self is other
  1601. def __reduce__(self):
  1602. return self.__name__
  1603. # Hack to get typing._type_check to pass.
  1604. def __call__(self, *args, **kwargs):
  1605. pass
  1606. # 3.9
  1607. if not hasattr(typing, 'Concatenate'):
  1608. # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
  1609. # 3.9.0-1
  1610. if not hasattr(typing, '_type_convert'):
  1611. def _type_convert(arg, module=None, *, allow_special_forms=False):
  1612. """For converting None to type(None), and strings to ForwardRef."""
  1613. if arg is None:
  1614. return type(None)
  1615. if isinstance(arg, str):
  1616. if sys.version_info <= (3, 9, 6):
  1617. return ForwardRef(arg)
  1618. if sys.version_info <= (3, 9, 7):
  1619. return ForwardRef(arg, module=module)
  1620. return ForwardRef(arg, module=module, is_class=allow_special_forms)
  1621. return arg
  1622. else:
  1623. _type_convert = typing._type_convert
  1624. class _ConcatenateGenericAlias(list):
  1625. # Trick Generic into looking into this for __parameters__.
  1626. __class__ = typing._GenericAlias
  1627. def __init__(self, origin, args):
  1628. super().__init__(args)
  1629. self.__origin__ = origin
  1630. self.__args__ = args
  1631. def __repr__(self):
  1632. _type_repr = typing._type_repr
  1633. return (f'{_type_repr(self.__origin__)}'
  1634. f'[{", ".join(_type_repr(arg) for arg in self.__args__)}]')
  1635. def __hash__(self):
  1636. return hash((self.__origin__, self.__args__))
  1637. # Hack to get typing._type_check to pass in Generic.
  1638. def __call__(self, *args, **kwargs):
  1639. pass
  1640. @property
  1641. def __parameters__(self):
  1642. return tuple(
  1643. tp for tp in self.__args__ if isinstance(tp, (typing.TypeVar, ParamSpec))
  1644. )
  1645. # 3.9 used by __getitem__ below
  1646. def copy_with(self, params):
  1647. if isinstance(params[-1], _ConcatenateGenericAlias):
  1648. params = (*params[:-1], *params[-1].__args__)
  1649. elif isinstance(params[-1], (list, tuple)):
  1650. return (*params[:-1], *params[-1])
  1651. elif (not (params[-1] is ... or isinstance(params[-1], ParamSpec))):
  1652. raise TypeError("The last parameter to Concatenate should be a "
  1653. "ParamSpec variable or ellipsis.")
  1654. return self.__class__(self.__origin__, params)
  1655. # 3.9; accessed during GenericAlias.__getitem__ when substituting
  1656. def __getitem__(self, args):
  1657. if self.__origin__ in (Generic, Protocol):
  1658. # Can't subscript Generic[...] or Protocol[...].
  1659. raise TypeError(f"Cannot subscript already-subscripted {self}")
  1660. if not self.__parameters__:
  1661. raise TypeError(f"{self} is not a generic class")
  1662. if not isinstance(args, tuple):
  1663. args = (args,)
  1664. args = _unpack_args(*(_type_convert(p) for p in args))
  1665. params = self.__parameters__
  1666. for param in params:
  1667. prepare = getattr(param, "__typing_prepare_subst__", None)
  1668. if prepare is not None:
  1669. args = prepare(self, args)
  1670. # 3.9 & typing.ParamSpec
  1671. elif isinstance(param, ParamSpec):
  1672. i = params.index(param)
  1673. if (
  1674. i == len(args)
  1675. and getattr(param, '__default__', NoDefault) is not NoDefault
  1676. ):
  1677. args = [*args, param.__default__]
  1678. if i >= len(args):
  1679. raise TypeError(f"Too few arguments for {self}")
  1680. # Special case for Z[[int, str, bool]] == Z[int, str, bool]
  1681. if len(params) == 1 and not _is_param_expr(args[0]):
  1682. assert i == 0
  1683. args = (args,)
  1684. elif (
  1685. isinstance(args[i], list)
  1686. # 3.9
  1687. # This class inherits from list do not convert
  1688. and not isinstance(args[i], _ConcatenateGenericAlias)
  1689. ):
  1690. args = (*args[:i], tuple(args[i]), *args[i + 1:])
  1691. alen = len(args)
  1692. plen = len(params)
  1693. if alen != plen:
  1694. raise TypeError(
  1695. f"Too {'many' if alen > plen else 'few'} arguments for {self};"
  1696. f" actual {alen}, expected {plen}"
  1697. )
  1698. subst = dict(zip(self.__parameters__, args))
  1699. # determine new args
  1700. new_args = []
  1701. for arg in self.__args__:
  1702. if isinstance(arg, type):
  1703. new_args.append(arg)
  1704. continue
  1705. if isinstance(arg, TypeVar):
  1706. arg = subst[arg]
  1707. if (
  1708. (isinstance(arg, typing._GenericAlias) and _is_unpack(arg))
  1709. or (
  1710. hasattr(_types, "GenericAlias")
  1711. and isinstance(arg, _types.GenericAlias)
  1712. and getattr(arg, "__unpacked__", False)
  1713. )
  1714. ):
  1715. raise TypeError(f"{arg} is not valid as type argument")
  1716. elif isinstance(arg,
  1717. typing._GenericAlias
  1718. if not hasattr(_types, "GenericAlias") else
  1719. (typing._GenericAlias, _types.GenericAlias)
  1720. ):
  1721. subparams = arg.__parameters__
  1722. if subparams:
  1723. subargs = tuple(subst[x] for x in subparams)
  1724. arg = arg[subargs]
  1725. new_args.append(arg)
  1726. return self.copy_with(tuple(new_args))
  1727. # 3.10+
  1728. else:
  1729. _ConcatenateGenericAlias = typing._ConcatenateGenericAlias
  1730. # 3.10
  1731. if sys.version_info < (3, 11):
  1732. class _ConcatenateGenericAlias(typing._ConcatenateGenericAlias, _root=True):
  1733. # needed for checks in collections.abc.Callable to accept this class
  1734. __module__ = "typing"
  1735. def copy_with(self, params):
  1736. if isinstance(params[-1], (list, tuple)):
  1737. return (*params[:-1], *params[-1])
  1738. if isinstance(params[-1], typing._ConcatenateGenericAlias):
  1739. params = (*params[:-1], *params[-1].__args__)
  1740. elif not (params[-1] is ... or isinstance(params[-1], ParamSpec)):
  1741. raise TypeError("The last parameter to Concatenate should be a "
  1742. "ParamSpec variable or ellipsis.")
  1743. return super(typing._ConcatenateGenericAlias, self).copy_with(params)
  1744. def __getitem__(self, args):
  1745. value = super().__getitem__(args)
  1746. if isinstance(value, tuple) and any(_is_unpack(t) for t in value):
  1747. return tuple(_unpack_args(*(n for n in value)))
  1748. return value
  1749. # 3.9.2
  1750. class _EllipsisDummy: ...
  1751. # <=3.10
  1752. def _create_concatenate_alias(origin, parameters):
  1753. if parameters[-1] is ... and sys.version_info < (3, 9, 2):
  1754. # Hack: Arguments must be types, replace it with one.
  1755. parameters = (*parameters[:-1], _EllipsisDummy)
  1756. if sys.version_info >= (3, 10, 3):
  1757. concatenate = _ConcatenateGenericAlias(origin, parameters,
  1758. _typevar_types=(TypeVar, ParamSpec),
  1759. _paramspec_tvars=True)
  1760. else:
  1761. concatenate = _ConcatenateGenericAlias(origin, parameters)
  1762. if parameters[-1] is not _EllipsisDummy:
  1763. return concatenate
  1764. # Remove dummy again
  1765. concatenate.__args__ = tuple(p if p is not _EllipsisDummy else ...
  1766. for p in concatenate.__args__)
  1767. if sys.version_info < (3, 10):
  1768. # backport needs __args__ adjustment only
  1769. return concatenate
  1770. concatenate.__parameters__ = tuple(p for p in concatenate.__parameters__
  1771. if p is not _EllipsisDummy)
  1772. return concatenate
  1773. # <=3.10
  1774. @typing._tp_cache
  1775. def _concatenate_getitem(self, parameters):
  1776. if parameters == ():
  1777. raise TypeError("Cannot take a Concatenate of no types.")
  1778. if not isinstance(parameters, tuple):
  1779. parameters = (parameters,)
  1780. if not (parameters[-1] is ... or isinstance(parameters[-1], ParamSpec)):
  1781. raise TypeError("The last parameter to Concatenate should be a "
  1782. "ParamSpec variable or ellipsis.")
  1783. msg = "Concatenate[arg, ...]: each arg must be a type."
  1784. parameters = (*(typing._type_check(p, msg) for p in parameters[:-1]),
  1785. parameters[-1])
  1786. return _create_concatenate_alias(self, parameters)
  1787. # 3.11+; Concatenate does not accept ellipsis in 3.10
  1788. # Breakpoint: https://github.com/python/cpython/pull/30969
  1789. if sys.version_info >= (3, 11):
  1790. Concatenate = typing.Concatenate
  1791. # <=3.10
  1792. else:
  1793. @_ExtensionsSpecialForm
  1794. def Concatenate(self, parameters):
  1795. """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
  1796. higher order function which adds, removes or transforms parameters of a
  1797. callable.
  1798. For example::
  1799. Callable[Concatenate[int, P], int]
  1800. See PEP 612 for detailed information.
  1801. """
  1802. return _concatenate_getitem(self, parameters)
  1803. # 3.10+
  1804. if hasattr(typing, 'TypeGuard'):
  1805. TypeGuard = typing.TypeGuard
  1806. # 3.9
  1807. else:
  1808. @_ExtensionsSpecialForm
  1809. def TypeGuard(self, parameters):
  1810. """Special typing form used to annotate the return type of a user-defined
  1811. type guard function. ``TypeGuard`` only accepts a single type argument.
  1812. At runtime, functions marked this way should return a boolean.
  1813. ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
  1814. type checkers to determine a more precise type of an expression within a
  1815. program's code flow. Usually type narrowing is done by analyzing
  1816. conditional code flow and applying the narrowing to a block of code. The
  1817. conditional expression here is sometimes referred to as a "type guard".
  1818. Sometimes it would be convenient to use a user-defined boolean function
  1819. as a type guard. Such a function should use ``TypeGuard[...]`` as its
  1820. return type to alert static type checkers to this intention.
  1821. Using ``-> TypeGuard`` tells the static type checker that for a given
  1822. function:
  1823. 1. The return value is a boolean.
  1824. 2. If the return value is ``True``, the type of its argument
  1825. is the type inside ``TypeGuard``.
  1826. For example::
  1827. def is_str(val: Union[str, float]):
  1828. # "isinstance" type guard
  1829. if isinstance(val, str):
  1830. # Type of ``val`` is narrowed to ``str``
  1831. ...
  1832. else:
  1833. # Else, type of ``val`` is narrowed to ``float``.
  1834. ...
  1835. Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
  1836. form of ``TypeA`` (it can even be a wider form) and this may lead to
  1837. type-unsafe results. The main reason is to allow for things like
  1838. narrowing ``List[object]`` to ``List[str]`` even though the latter is not
  1839. a subtype of the former, since ``List`` is invariant. The responsibility of
  1840. writing type-safe type guards is left to the user.
  1841. ``TypeGuard`` also works with type variables. For more information, see
  1842. PEP 647 (User-Defined Type Guards).
  1843. """
  1844. item = typing._type_check(parameters, f'{self} accepts only a single type.')
  1845. return typing._GenericAlias(self, (item,))
  1846. # 3.13+
  1847. if hasattr(typing, 'TypeIs'):
  1848. TypeIs = typing.TypeIs
  1849. # <=3.12
  1850. else:
  1851. @_ExtensionsSpecialForm
  1852. def TypeIs(self, parameters):
  1853. """Special typing form used to annotate the return type of a user-defined
  1854. type narrower function. ``TypeIs`` only accepts a single type argument.
  1855. At runtime, functions marked this way should return a boolean.
  1856. ``TypeIs`` aims to benefit *type narrowing* -- a technique used by static
  1857. type checkers to determine a more precise type of an expression within a
  1858. program's code flow. Usually type narrowing is done by analyzing
  1859. conditional code flow and applying the narrowing to a block of code. The
  1860. conditional expression here is sometimes referred to as a "type guard".
  1861. Sometimes it would be convenient to use a user-defined boolean function
  1862. as a type guard. Such a function should use ``TypeIs[...]`` as its
  1863. return type to alert static type checkers to this intention.
  1864. Using ``-> TypeIs`` tells the static type checker that for a given
  1865. function:
  1866. 1. The return value is a boolean.
  1867. 2. If the return value is ``True``, the type of its argument
  1868. is the intersection of the type inside ``TypeIs`` and the argument's
  1869. previously known type.
  1870. For example::
  1871. def is_awaitable(val: object) -> TypeIs[Awaitable[Any]]:
  1872. return hasattr(val, '__await__')
  1873. def f(val: Union[int, Awaitable[int]]) -> int:
  1874. if is_awaitable(val):
  1875. assert_type(val, Awaitable[int])
  1876. else:
  1877. assert_type(val, int)
  1878. ``TypeIs`` also works with type variables. For more information, see
  1879. PEP 742 (Narrowing types with TypeIs).
  1880. """
  1881. item = typing._type_check(parameters, f'{self} accepts only a single type.')
  1882. return typing._GenericAlias(self, (item,))
  1883. # 3.14+?
  1884. if hasattr(typing, 'TypeForm'):
  1885. TypeForm = typing.TypeForm
  1886. # <=3.13
  1887. else:
  1888. class _TypeFormForm(_ExtensionsSpecialForm, _root=True):
  1889. # TypeForm(X) is equivalent to X but indicates to the type checker
  1890. # that the object is a TypeForm.
  1891. def __call__(self, obj, /):
  1892. return obj
  1893. @_TypeFormForm
  1894. def TypeForm(self, parameters):
  1895. """A special form representing the value that results from the evaluation
  1896. of a type expression. This value encodes the information supplied in the
  1897. type expression, and it represents the type described by that type expression.
  1898. When used in a type expression, TypeForm describes a set of type form objects.
  1899. It accepts a single type argument, which must be a valid type expression.
  1900. ``TypeForm[T]`` describes the set of all type form objects that represent
  1901. the type T or types that are assignable to T.
  1902. Usage:
  1903. def cast[T](typ: TypeForm[T], value: Any) -> T: ...
  1904. reveal_type(cast(int, "x")) # int
  1905. See PEP 747 for more information.
  1906. """
  1907. item = typing._type_check(parameters, f'{self} accepts only a single type.')
  1908. return typing._GenericAlias(self, (item,))
  1909. if hasattr(typing, "LiteralString"): # 3.11+
  1910. LiteralString = typing.LiteralString
  1911. else:
  1912. @_SpecialForm
  1913. def LiteralString(self, params):
  1914. """Represents an arbitrary literal string.
  1915. Example::
  1916. from typing_extensions import LiteralString
  1917. def query(sql: LiteralString) -> ...:
  1918. ...
  1919. query("SELECT * FROM table") # ok
  1920. query(f"SELECT * FROM {input()}") # not ok
  1921. See PEP 675 for details.
  1922. """
  1923. raise TypeError(f"{self} is not subscriptable")
  1924. if hasattr(typing, "Self"): # 3.11+
  1925. Self = typing.Self
  1926. else:
  1927. @_SpecialForm
  1928. def Self(self, params):
  1929. """Used to spell the type of "self" in classes.
  1930. Example::
  1931. from typing import Self
  1932. class ReturnsSelf:
  1933. def parse(self, data: bytes) -> Self:
  1934. ...
  1935. return self
  1936. """
  1937. raise TypeError(f"{self} is not subscriptable")
  1938. if hasattr(typing, "Never"): # 3.11+
  1939. Never = typing.Never
  1940. else:
  1941. @_SpecialForm
  1942. def Never(self, params):
  1943. """The bottom type, a type that has no members.
  1944. This can be used to define a function that should never be
  1945. called, or a function that never returns::
  1946. from typing_extensions import Never
  1947. def never_call_me(arg: Never) -> None:
  1948. pass
  1949. def int_or_str(arg: int | str) -> None:
  1950. never_call_me(arg) # type checker error
  1951. match arg:
  1952. case int():
  1953. print("It's an int")
  1954. case str():
  1955. print("It's a str")
  1956. case _:
  1957. never_call_me(arg) # ok, arg is of type Never
  1958. """
  1959. raise TypeError(f"{self} is not subscriptable")
  1960. if hasattr(typing, 'Required'): # 3.11+
  1961. Required = typing.Required
  1962. NotRequired = typing.NotRequired
  1963. else: # <=3.10
  1964. @_ExtensionsSpecialForm
  1965. def Required(self, parameters):
  1966. """A special typing construct to mark a key of a total=False TypedDict
  1967. as required. For example:
  1968. class Movie(TypedDict, total=False):
  1969. title: Required[str]
  1970. year: int
  1971. m = Movie(
  1972. title='The Matrix', # typechecker error if key is omitted
  1973. year=1999,
  1974. )
  1975. There is no runtime checking that a required key is actually provided
  1976. when instantiating a related TypedDict.
  1977. """
  1978. item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
  1979. return typing._GenericAlias(self, (item,))
  1980. @_ExtensionsSpecialForm
  1981. def NotRequired(self, parameters):
  1982. """A special typing construct to mark a key of a TypedDict as
  1983. potentially missing. For example:
  1984. class Movie(TypedDict):
  1985. title: str
  1986. year: NotRequired[int]
  1987. m = Movie(
  1988. title='The Matrix', # typechecker error if key is omitted
  1989. year=1999,
  1990. )
  1991. """
  1992. item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
  1993. return typing._GenericAlias(self, (item,))
  1994. if hasattr(typing, 'ReadOnly'):
  1995. ReadOnly = typing.ReadOnly
  1996. else: # <=3.12
  1997. @_ExtensionsSpecialForm
  1998. def ReadOnly(self, parameters):
  1999. """A special typing construct to mark an item of a TypedDict as read-only.
  2000. For example:
  2001. class Movie(TypedDict):
  2002. title: ReadOnly[str]
  2003. year: int
  2004. def mutate_movie(m: Movie) -> None:
  2005. m["year"] = 1992 # allowed
  2006. m["title"] = "The Matrix" # typechecker error
  2007. There is no runtime checking for this property.
  2008. """
  2009. item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
  2010. return typing._GenericAlias(self, (item,))
  2011. _UNPACK_DOC = """\
  2012. Type unpack operator.
  2013. The type unpack operator takes the child types from some container type,
  2014. such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'. For
  2015. example:
  2016. # For some generic class `Foo`:
  2017. Foo[Unpack[tuple[int, str]]] # Equivalent to Foo[int, str]
  2018. Ts = TypeVarTuple('Ts')
  2019. # Specifies that `Bar` is generic in an arbitrary number of types.
  2020. # (Think of `Ts` as a tuple of an arbitrary number of individual
  2021. # `TypeVar`s, which the `Unpack` is 'pulling out' directly into the
  2022. # `Generic[]`.)
  2023. class Bar(Generic[Unpack[Ts]]): ...
  2024. Bar[int] # Valid
  2025. Bar[int, str] # Also valid
  2026. From Python 3.11, this can also be done using the `*` operator:
  2027. Foo[*tuple[int, str]]
  2028. class Bar(Generic[*Ts]): ...
  2029. The operator can also be used along with a `TypedDict` to annotate
  2030. `**kwargs` in a function signature. For instance:
  2031. class Movie(TypedDict):
  2032. name: str
  2033. year: int
  2034. # This function expects two keyword arguments - *name* of type `str` and
  2035. # *year* of type `int`.
  2036. def foo(**kwargs: Unpack[Movie]): ...
  2037. Note that there is only some runtime checking of this operator. Not
  2038. everything the runtime allows may be accepted by static type checkers.
  2039. For more information, see PEP 646 and PEP 692.
  2040. """
  2041. # PEP 692 changed the repr of Unpack[]
  2042. # Breakpoint: https://github.com/python/cpython/pull/104048
  2043. if sys.version_info >= (3, 12):
  2044. Unpack = typing.Unpack
  2045. def _is_unpack(obj):
  2046. return get_origin(obj) is Unpack
  2047. else: # <=3.11
  2048. class _UnpackSpecialForm(_ExtensionsSpecialForm, _root=True):
  2049. def __init__(self, getitem):
  2050. super().__init__(getitem)
  2051. self.__doc__ = _UNPACK_DOC
  2052. class _UnpackAlias(typing._GenericAlias, _root=True):
  2053. if sys.version_info < (3, 11):
  2054. # needed for compatibility with Generic[Unpack[Ts]]
  2055. __class__ = typing.TypeVar
  2056. @property
  2057. def __typing_unpacked_tuple_args__(self):
  2058. assert self.__origin__ is Unpack
  2059. assert len(self.__args__) == 1
  2060. arg, = self.__args__
  2061. if isinstance(arg, (typing._GenericAlias, _types.GenericAlias)):
  2062. if arg.__origin__ is not tuple:
  2063. raise TypeError("Unpack[...] must be used with a tuple type")
  2064. return arg.__args__
  2065. return None
  2066. @property
  2067. def __typing_is_unpacked_typevartuple__(self):
  2068. assert self.__origin__ is Unpack
  2069. assert len(self.__args__) == 1
  2070. return isinstance(self.__args__[0], TypeVarTuple)
  2071. def __getitem__(self, args):
  2072. if self.__typing_is_unpacked_typevartuple__:
  2073. return args
  2074. return super().__getitem__(args)
  2075. @_UnpackSpecialForm
  2076. def Unpack(self, parameters):
  2077. item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
  2078. return _UnpackAlias(self, (item,))
  2079. def _is_unpack(obj):
  2080. return isinstance(obj, _UnpackAlias)
  2081. def _unpack_args(*args):
  2082. newargs = []
  2083. for arg in args:
  2084. subargs = getattr(arg, '__typing_unpacked_tuple_args__', None)
  2085. if subargs is not None and (not (subargs and subargs[-1] is ...)):
  2086. newargs.extend(subargs)
  2087. else:
  2088. newargs.append(arg)
  2089. return newargs
  2090. if _PEP_696_IMPLEMENTED:
  2091. from typing import TypeVarTuple
  2092. elif hasattr(typing, "TypeVarTuple"): # 3.11+
  2093. # Add default parameter - PEP 696
  2094. class TypeVarTuple(metaclass=_TypeVarLikeMeta):
  2095. """Type variable tuple."""
  2096. _backported_typevarlike = typing.TypeVarTuple
  2097. def __new__(cls, name, *, default=NoDefault):
  2098. tvt = typing.TypeVarTuple(name)
  2099. _set_default(tvt, default)
  2100. _set_module(tvt)
  2101. def _typevartuple_prepare_subst(alias, args):
  2102. params = alias.__parameters__
  2103. typevartuple_index = params.index(tvt)
  2104. for param in params[typevartuple_index + 1:]:
  2105. if isinstance(param, TypeVarTuple):
  2106. raise TypeError(
  2107. f"More than one TypeVarTuple parameter in {alias}"
  2108. )
  2109. alen = len(args)
  2110. plen = len(params)
  2111. left = typevartuple_index
  2112. right = plen - typevartuple_index - 1
  2113. var_tuple_index = None
  2114. fillarg = None
  2115. for k, arg in enumerate(args):
  2116. if not isinstance(arg, type):
  2117. subargs = getattr(arg, '__typing_unpacked_tuple_args__', None)
  2118. if subargs and len(subargs) == 2 and subargs[-1] is ...:
  2119. if var_tuple_index is not None:
  2120. raise TypeError(
  2121. "More than one unpacked "
  2122. "arbitrary-length tuple argument"
  2123. )
  2124. var_tuple_index = k
  2125. fillarg = subargs[0]
  2126. if var_tuple_index is not None:
  2127. left = min(left, var_tuple_index)
  2128. right = min(right, alen - var_tuple_index - 1)
  2129. elif left + right > alen:
  2130. raise TypeError(f"Too few arguments for {alias};"
  2131. f" actual {alen}, expected at least {plen - 1}")
  2132. if left == alen - right and tvt.has_default():
  2133. replacement = _unpack_args(tvt.__default__)
  2134. else:
  2135. replacement = args[left: alen - right]
  2136. return (
  2137. *args[:left],
  2138. *([fillarg] * (typevartuple_index - left)),
  2139. replacement,
  2140. *([fillarg] * (plen - right - left - typevartuple_index - 1)),
  2141. *args[alen - right:],
  2142. )
  2143. tvt.__typing_prepare_subst__ = _typevartuple_prepare_subst
  2144. return tvt
  2145. def __init_subclass__(self, *args, **kwds):
  2146. raise TypeError("Cannot subclass special typing classes")
  2147. else: # <=3.10
  2148. class TypeVarTuple(_DefaultMixin):
  2149. """Type variable tuple.
  2150. Usage::
  2151. Ts = TypeVarTuple('Ts')
  2152. In the same way that a normal type variable is a stand-in for a single
  2153. type such as ``int``, a type variable *tuple* is a stand-in for a *tuple*
  2154. type such as ``Tuple[int, str]``.
  2155. Type variable tuples can be used in ``Generic`` declarations.
  2156. Consider the following example::
  2157. class Array(Generic[*Ts]): ...
  2158. The ``Ts`` type variable tuple here behaves like ``tuple[T1, T2]``,
  2159. where ``T1`` and ``T2`` are type variables. To use these type variables
  2160. as type parameters of ``Array``, we must *unpack* the type variable tuple using
  2161. the star operator: ``*Ts``. The signature of ``Array`` then behaves
  2162. as if we had simply written ``class Array(Generic[T1, T2]): ...``.
  2163. In contrast to ``Generic[T1, T2]``, however, ``Generic[*Shape]`` allows
  2164. us to parameterise the class with an *arbitrary* number of type parameters.
  2165. Type variable tuples can be used anywhere a normal ``TypeVar`` can.
  2166. This includes class definitions, as shown above, as well as function
  2167. signatures and variable annotations::
  2168. class Array(Generic[*Ts]):
  2169. def __init__(self, shape: Tuple[*Ts]):
  2170. self._shape: Tuple[*Ts] = shape
  2171. def get_shape(self) -> Tuple[*Ts]:
  2172. return self._shape
  2173. shape = (Height(480), Width(640))
  2174. x: Array[Height, Width] = Array(shape)
  2175. y = abs(x) # Inferred type is Array[Height, Width]
  2176. z = x + x # ... is Array[Height, Width]
  2177. x.get_shape() # ... is tuple[Height, Width]
  2178. """
  2179. # Trick Generic __parameters__.
  2180. __class__ = typing.TypeVar
  2181. def __iter__(self):
  2182. yield self.__unpacked__
  2183. def __init__(self, name, *, default=NoDefault):
  2184. self.__name__ = name
  2185. _DefaultMixin.__init__(self, default)
  2186. # for pickling:
  2187. def_mod = _caller()
  2188. if def_mod != 'typing_extensions':
  2189. self.__module__ = def_mod
  2190. self.__unpacked__ = Unpack[self]
  2191. def __repr__(self):
  2192. return self.__name__
  2193. def __hash__(self):
  2194. return object.__hash__(self)
  2195. def __eq__(self, other):
  2196. return self is other
  2197. def __reduce__(self):
  2198. return self.__name__
  2199. def __init_subclass__(self, *args, **kwds):
  2200. if '_root' not in kwds:
  2201. raise TypeError("Cannot subclass special typing classes")
  2202. if hasattr(typing, "reveal_type"): # 3.11+
  2203. reveal_type = typing.reveal_type
  2204. else: # <=3.10
  2205. def reveal_type(obj: T, /) -> T:
  2206. """Reveal the inferred type of a variable.
  2207. When a static type checker encounters a call to ``reveal_type()``,
  2208. it will emit the inferred type of the argument::
  2209. x: int = 1
  2210. reveal_type(x)
  2211. Running a static type checker (e.g., ``mypy``) on this example
  2212. will produce output similar to 'Revealed type is "builtins.int"'.
  2213. At runtime, the function prints the runtime type of the
  2214. argument and returns it unchanged.
  2215. """
  2216. print(f"Runtime type is {type(obj).__name__!r}", file=sys.stderr)
  2217. return obj
  2218. if hasattr(typing, "_ASSERT_NEVER_REPR_MAX_LENGTH"): # 3.11+
  2219. _ASSERT_NEVER_REPR_MAX_LENGTH = typing._ASSERT_NEVER_REPR_MAX_LENGTH
  2220. else: # <=3.10
  2221. _ASSERT_NEVER_REPR_MAX_LENGTH = 100
  2222. if hasattr(typing, "assert_never"): # 3.11+
  2223. assert_never = typing.assert_never
  2224. else: # <=3.10
  2225. def assert_never(arg: Never, /) -> Never:
  2226. """Assert to the type checker that a line of code is unreachable.
  2227. Example::
  2228. def int_or_str(arg: int | str) -> None:
  2229. match arg:
  2230. case int():
  2231. print("It's an int")
  2232. case str():
  2233. print("It's a str")
  2234. case _:
  2235. assert_never(arg)
  2236. If a type checker finds that a call to assert_never() is
  2237. reachable, it will emit an error.
  2238. At runtime, this throws an exception when called.
  2239. """
  2240. value = repr(arg)
  2241. if len(value) > _ASSERT_NEVER_REPR_MAX_LENGTH:
  2242. value = value[:_ASSERT_NEVER_REPR_MAX_LENGTH] + '...'
  2243. raise AssertionError(f"Expected code to be unreachable, but got: {value}")
  2244. # dataclass_transform exists in 3.11 but lacks the frozen_default parameter
  2245. # Breakpoint: https://github.com/python/cpython/pull/99958
  2246. if sys.version_info >= (3, 12): # 3.12+
  2247. dataclass_transform = typing.dataclass_transform
  2248. else: # <=3.11
  2249. def dataclass_transform(
  2250. *,
  2251. eq_default: bool = True,
  2252. order_default: bool = False,
  2253. kw_only_default: bool = False,
  2254. frozen_default: bool = False,
  2255. field_specifiers: typing.Tuple[
  2256. typing.Union[typing.Type[typing.Any], typing.Callable[..., typing.Any]],
  2257. ...
  2258. ] = (),
  2259. **kwargs: typing.Any,
  2260. ) -> typing.Callable[[T], T]:
  2261. """Decorator that marks a function, class, or metaclass as providing
  2262. dataclass-like behavior.
  2263. Example:
  2264. from typing_extensions import dataclass_transform
  2265. _T = TypeVar("_T")
  2266. # Used on a decorator function
  2267. @dataclass_transform()
  2268. def create_model(cls: type[_T]) -> type[_T]:
  2269. ...
  2270. return cls
  2271. @create_model
  2272. class CustomerModel:
  2273. id: int
  2274. name: str
  2275. # Used on a base class
  2276. @dataclass_transform()
  2277. class ModelBase: ...
  2278. class CustomerModel(ModelBase):
  2279. id: int
  2280. name: str
  2281. # Used on a metaclass
  2282. @dataclass_transform()
  2283. class ModelMeta(type): ...
  2284. class ModelBase(metaclass=ModelMeta): ...
  2285. class CustomerModel(ModelBase):
  2286. id: int
  2287. name: str
  2288. Each of the ``CustomerModel`` classes defined in this example will now
  2289. behave similarly to a dataclass created with the ``@dataclasses.dataclass``
  2290. decorator. For example, the type checker will synthesize an ``__init__``
  2291. method.
  2292. The arguments to this decorator can be used to customize this behavior:
  2293. - ``eq_default`` indicates whether the ``eq`` parameter is assumed to be
  2294. True or False if it is omitted by the caller.
  2295. - ``order_default`` indicates whether the ``order`` parameter is
  2296. assumed to be True or False if it is omitted by the caller.
  2297. - ``kw_only_default`` indicates whether the ``kw_only`` parameter is
  2298. assumed to be True or False if it is omitted by the caller.
  2299. - ``frozen_default`` indicates whether the ``frozen`` parameter is
  2300. assumed to be True or False if it is omitted by the caller.
  2301. - ``field_specifiers`` specifies a static list of supported classes
  2302. or functions that describe fields, similar to ``dataclasses.field()``.
  2303. At runtime, this decorator records its arguments in the
  2304. ``__dataclass_transform__`` attribute on the decorated object.
  2305. See PEP 681 for details.
  2306. """
  2307. def decorator(cls_or_fn):
  2308. cls_or_fn.__dataclass_transform__ = {
  2309. "eq_default": eq_default,
  2310. "order_default": order_default,
  2311. "kw_only_default": kw_only_default,
  2312. "frozen_default": frozen_default,
  2313. "field_specifiers": field_specifiers,
  2314. "kwargs": kwargs,
  2315. }
  2316. return cls_or_fn
  2317. return decorator
  2318. if hasattr(typing, "override"): # 3.12+
  2319. override = typing.override
  2320. else: # <=3.11
  2321. _F = typing.TypeVar("_F", bound=typing.Callable[..., typing.Any])
  2322. def override(arg: _F, /) -> _F:
  2323. """Indicate that a method is intended to override a method in a base class.
  2324. Usage:
  2325. class Base:
  2326. def method(self) -> None:
  2327. pass
  2328. class Child(Base):
  2329. @override
  2330. def method(self) -> None:
  2331. super().method()
  2332. When this decorator is applied to a method, the type checker will
  2333. validate that it overrides a method with the same name on a base class.
  2334. This helps prevent bugs that may occur when a base class is changed
  2335. without an equivalent change to a child class.
  2336. There is no runtime checking of these properties. The decorator
  2337. sets the ``__override__`` attribute to ``True`` on the decorated object
  2338. to allow runtime introspection.
  2339. See PEP 698 for details.
  2340. """
  2341. try:
  2342. arg.__override__ = True
  2343. except (AttributeError, TypeError):
  2344. # Skip the attribute silently if it is not writable.
  2345. # AttributeError happens if the object has __slots__ or a
  2346. # read-only property, TypeError if it's a builtin class.
  2347. pass
  2348. return arg
  2349. # Python 3.13.3+ contains a fix for the wrapped __new__
  2350. # Breakpoint: https://github.com/python/cpython/pull/132160
  2351. if sys.version_info >= (3, 13, 3):
  2352. deprecated = warnings.deprecated
  2353. else:
  2354. _T = typing.TypeVar("_T")
  2355. class deprecated:
  2356. """Indicate that a class, function or overload is deprecated.
  2357. When this decorator is applied to an object, the type checker
  2358. will generate a diagnostic on usage of the deprecated object.
  2359. Usage:
  2360. @deprecated("Use B instead")
  2361. class A:
  2362. pass
  2363. @deprecated("Use g instead")
  2364. def f():
  2365. pass
  2366. @overload
  2367. @deprecated("int support is deprecated")
  2368. def g(x: int) -> int: ...
  2369. @overload
  2370. def g(x: str) -> int: ...
  2371. The warning specified by *category* will be emitted at runtime
  2372. on use of deprecated objects. For functions, that happens on calls;
  2373. for classes, on instantiation and on creation of subclasses.
  2374. If the *category* is ``None``, no warning is emitted at runtime.
  2375. The *stacklevel* determines where the
  2376. warning is emitted. If it is ``1`` (the default), the warning
  2377. is emitted at the direct caller of the deprecated object; if it
  2378. is higher, it is emitted further up the stack.
  2379. Static type checker behavior is not affected by the *category*
  2380. and *stacklevel* arguments.
  2381. The deprecation message passed to the decorator is saved in the
  2382. ``__deprecated__`` attribute on the decorated object.
  2383. If applied to an overload, the decorator
  2384. must be after the ``@overload`` decorator for the attribute to
  2385. exist on the overload as returned by ``get_overloads()``.
  2386. See PEP 702 for details.
  2387. """
  2388. def __init__(
  2389. self,
  2390. message: str,
  2391. /,
  2392. *,
  2393. category: typing.Optional[typing.Type[Warning]] = DeprecationWarning,
  2394. stacklevel: int = 1,
  2395. ) -> None:
  2396. if not isinstance(message, str):
  2397. raise TypeError(
  2398. "Expected an object of type str for 'message', not "
  2399. f"{type(message).__name__!r}"
  2400. )
  2401. self.message = message
  2402. self.category = category
  2403. self.stacklevel = stacklevel
  2404. def __call__(self, arg: _T, /) -> _T:
  2405. # Make sure the inner functions created below don't
  2406. # retain a reference to self.
  2407. msg = self.message
  2408. category = self.category
  2409. stacklevel = self.stacklevel
  2410. if category is None:
  2411. arg.__deprecated__ = msg
  2412. return arg
  2413. elif isinstance(arg, type):
  2414. import functools
  2415. from types import MethodType
  2416. original_new = arg.__new__
  2417. @functools.wraps(original_new)
  2418. def __new__(cls, /, *args, **kwargs):
  2419. if cls is arg:
  2420. warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
  2421. if original_new is not object.__new__:
  2422. return original_new(cls, *args, **kwargs)
  2423. # Mirrors a similar check in object.__new__.
  2424. elif cls.__init__ is object.__init__ and (args or kwargs):
  2425. raise TypeError(f"{cls.__name__}() takes no arguments")
  2426. else:
  2427. return original_new(cls)
  2428. arg.__new__ = staticmethod(__new__)
  2429. original_init_subclass = arg.__init_subclass__
  2430. # We need slightly different behavior if __init_subclass__
  2431. # is a bound method (likely if it was implemented in Python)
  2432. if isinstance(original_init_subclass, MethodType):
  2433. original_init_subclass = original_init_subclass.__func__
  2434. @functools.wraps(original_init_subclass)
  2435. def __init_subclass__(*args, **kwargs):
  2436. warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
  2437. return original_init_subclass(*args, **kwargs)
  2438. arg.__init_subclass__ = classmethod(__init_subclass__)
  2439. # Or otherwise, which likely means it's a builtin such as
  2440. # object's implementation of __init_subclass__.
  2441. else:
  2442. @functools.wraps(original_init_subclass)
  2443. def __init_subclass__(*args, **kwargs):
  2444. warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
  2445. return original_init_subclass(*args, **kwargs)
  2446. arg.__init_subclass__ = __init_subclass__
  2447. arg.__deprecated__ = __new__.__deprecated__ = msg
  2448. __init_subclass__.__deprecated__ = msg
  2449. return arg
  2450. elif callable(arg):
  2451. import asyncio.coroutines
  2452. import functools
  2453. import inspect
  2454. @functools.wraps(arg)
  2455. def wrapper(*args, **kwargs):
  2456. warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
  2457. return arg(*args, **kwargs)
  2458. if asyncio.coroutines.iscoroutinefunction(arg):
  2459. # Breakpoint: https://github.com/python/cpython/pull/99247
  2460. if sys.version_info >= (3, 12):
  2461. wrapper = inspect.markcoroutinefunction(wrapper)
  2462. else:
  2463. wrapper._is_coroutine = asyncio.coroutines._is_coroutine
  2464. arg.__deprecated__ = wrapper.__deprecated__ = msg
  2465. return wrapper
  2466. else:
  2467. raise TypeError(
  2468. "@deprecated decorator with non-None category must be applied to "
  2469. f"a class or callable, not {arg!r}"
  2470. )
  2471. # Breakpoint: https://github.com/python/cpython/pull/23702
  2472. if sys.version_info < (3, 10):
  2473. def _is_param_expr(arg):
  2474. return arg is ... or isinstance(
  2475. arg, (tuple, list, ParamSpec, _ConcatenateGenericAlias)
  2476. )
  2477. else:
  2478. def _is_param_expr(arg):
  2479. return arg is ... or isinstance(
  2480. arg,
  2481. (
  2482. tuple,
  2483. list,
  2484. ParamSpec,
  2485. _ConcatenateGenericAlias,
  2486. typing._ConcatenateGenericAlias,
  2487. ),
  2488. )
  2489. # We have to do some monkey patching to deal with the dual nature of
  2490. # Unpack/TypeVarTuple:
  2491. # - We want Unpack to be a kind of TypeVar so it gets accepted in
  2492. # Generic[Unpack[Ts]]
  2493. # - We want it to *not* be treated as a TypeVar for the purposes of
  2494. # counting generic parameters, so that when we subscript a generic,
  2495. # the runtime doesn't try to substitute the Unpack with the subscripted type.
  2496. if not hasattr(typing, "TypeVarTuple"):
  2497. def _check_generic(cls, parameters, elen=_marker):
  2498. """Check correct count for parameters of a generic cls (internal helper).
  2499. This gives a nice error message in case of count mismatch.
  2500. """
  2501. # If substituting a single ParamSpec with multiple arguments
  2502. # we do not check the count
  2503. if (inspect.isclass(cls) and issubclass(cls, typing.Generic)
  2504. and len(cls.__parameters__) == 1
  2505. and isinstance(cls.__parameters__[0], ParamSpec)
  2506. and parameters
  2507. and not _is_param_expr(parameters[0])
  2508. ):
  2509. # Generic modifies parameters variable, but here we cannot do this
  2510. return
  2511. if not elen:
  2512. raise TypeError(f"{cls} is not a generic class")
  2513. if elen is _marker:
  2514. if not hasattr(cls, "__parameters__") or not cls.__parameters__:
  2515. raise TypeError(f"{cls} is not a generic class")
  2516. elen = len(cls.__parameters__)
  2517. alen = len(parameters)
  2518. if alen != elen:
  2519. expect_val = elen
  2520. if hasattr(cls, "__parameters__"):
  2521. parameters = [p for p in cls.__parameters__ if not _is_unpack(p)]
  2522. num_tv_tuples = sum(isinstance(p, TypeVarTuple) for p in parameters)
  2523. if (num_tv_tuples > 0) and (alen >= elen - num_tv_tuples):
  2524. return
  2525. # deal with TypeVarLike defaults
  2526. # required TypeVarLikes cannot appear after a defaulted one.
  2527. if alen < elen:
  2528. # since we validate TypeVarLike default in _collect_type_vars
  2529. # or _collect_parameters we can safely check parameters[alen]
  2530. if (
  2531. getattr(parameters[alen], '__default__', NoDefault)
  2532. is not NoDefault
  2533. ):
  2534. return
  2535. num_default_tv = sum(getattr(p, '__default__', NoDefault)
  2536. is not NoDefault for p in parameters)
  2537. elen -= num_default_tv
  2538. expect_val = f"at least {elen}"
  2539. # Breakpoint: https://github.com/python/cpython/pull/27515
  2540. things = "arguments" if sys.version_info >= (3, 10) else "parameters"
  2541. raise TypeError(f"Too {'many' if alen > elen else 'few'} {things}"
  2542. f" for {cls}; actual {alen}, expected {expect_val}")
  2543. else:
  2544. # Python 3.11+
  2545. def _check_generic(cls, parameters, elen):
  2546. """Check correct count for parameters of a generic cls (internal helper).
  2547. This gives a nice error message in case of count mismatch.
  2548. """
  2549. if not elen:
  2550. raise TypeError(f"{cls} is not a generic class")
  2551. alen = len(parameters)
  2552. if alen != elen:
  2553. expect_val = elen
  2554. if hasattr(cls, "__parameters__"):
  2555. parameters = [p for p in cls.__parameters__ if not _is_unpack(p)]
  2556. # deal with TypeVarLike defaults
  2557. # required TypeVarLikes cannot appear after a defaulted one.
  2558. if alen < elen:
  2559. # since we validate TypeVarLike default in _collect_type_vars
  2560. # or _collect_parameters we can safely check parameters[alen]
  2561. if (
  2562. getattr(parameters[alen], '__default__', NoDefault)
  2563. is not NoDefault
  2564. ):
  2565. return
  2566. num_default_tv = sum(getattr(p, '__default__', NoDefault)
  2567. is not NoDefault for p in parameters)
  2568. elen -= num_default_tv
  2569. expect_val = f"at least {elen}"
  2570. raise TypeError(f"Too {'many' if alen > elen else 'few'} arguments"
  2571. f" for {cls}; actual {alen}, expected {expect_val}")
  2572. if not _PEP_696_IMPLEMENTED:
  2573. typing._check_generic = _check_generic
  2574. def _has_generic_or_protocol_as_origin() -> bool:
  2575. try:
  2576. frame = sys._getframe(2)
  2577. # - Catch AttributeError: not all Python implementations have sys._getframe()
  2578. # - Catch ValueError: maybe we're called from an unexpected module
  2579. # and the call stack isn't deep enough
  2580. except (AttributeError, ValueError):
  2581. return False # err on the side of leniency
  2582. else:
  2583. # If we somehow get invoked from outside typing.py,
  2584. # also err on the side of leniency
  2585. if frame.f_globals.get("__name__") != "typing":
  2586. return False
  2587. origin = frame.f_locals.get("origin")
  2588. # Cannot use "in" because origin may be an object with a buggy __eq__ that
  2589. # throws an error.
  2590. return origin is typing.Generic or origin is Protocol or origin is typing.Protocol
  2591. _TYPEVARTUPLE_TYPES = {TypeVarTuple, getattr(typing, "TypeVarTuple", None)}
  2592. def _is_unpacked_typevartuple(x) -> bool:
  2593. if get_origin(x) is not Unpack:
  2594. return False
  2595. args = get_args(x)
  2596. return (
  2597. bool(args)
  2598. and len(args) == 1
  2599. and type(args[0]) in _TYPEVARTUPLE_TYPES
  2600. )
  2601. # Python 3.11+ _collect_type_vars was renamed to _collect_parameters
  2602. if hasattr(typing, '_collect_type_vars'):
  2603. def _collect_type_vars(types, typevar_types=None):
  2604. """Collect all type variable contained in types in order of
  2605. first appearance (lexicographic order). For example::
  2606. _collect_type_vars((T, List[S, T])) == (T, S)
  2607. """
  2608. if typevar_types is None:
  2609. typevar_types = typing.TypeVar
  2610. tvars = []
  2611. # A required TypeVarLike cannot appear after a TypeVarLike with a default
  2612. # if it was a direct call to `Generic[]` or `Protocol[]`
  2613. enforce_default_ordering = _has_generic_or_protocol_as_origin()
  2614. default_encountered = False
  2615. # Also, a TypeVarLike with a default cannot appear after a TypeVarTuple
  2616. type_var_tuple_encountered = False
  2617. for t in types:
  2618. if _is_unpacked_typevartuple(t):
  2619. type_var_tuple_encountered = True
  2620. elif (
  2621. isinstance(t, typevar_types) and not isinstance(t, _UnpackAlias)
  2622. and t not in tvars
  2623. ):
  2624. if enforce_default_ordering:
  2625. has_default = getattr(t, '__default__', NoDefault) is not NoDefault
  2626. if has_default:
  2627. if type_var_tuple_encountered:
  2628. raise TypeError('Type parameter with a default'
  2629. ' follows TypeVarTuple')
  2630. default_encountered = True
  2631. elif default_encountered:
  2632. raise TypeError(f'Type parameter {t!r} without a default'
  2633. ' follows type parameter with a default')
  2634. tvars.append(t)
  2635. if _should_collect_from_parameters(t):
  2636. tvars.extend([t for t in t.__parameters__ if t not in tvars])
  2637. elif isinstance(t, tuple):
  2638. # Collect nested type_vars
  2639. # tuple wrapped by _prepare_paramspec_params(cls, params)
  2640. for x in t:
  2641. for collected in _collect_type_vars([x]):
  2642. if collected not in tvars:
  2643. tvars.append(collected)
  2644. return tuple(tvars)
  2645. typing._collect_type_vars = _collect_type_vars
  2646. else:
  2647. def _collect_parameters(args):
  2648. """Collect all type variables and parameter specifications in args
  2649. in order of first appearance (lexicographic order).
  2650. For example::
  2651. assert _collect_parameters((T, Callable[P, T])) == (T, P)
  2652. """
  2653. parameters = []
  2654. # A required TypeVarLike cannot appear after a TypeVarLike with default
  2655. # if it was a direct call to `Generic[]` or `Protocol[]`
  2656. enforce_default_ordering = _has_generic_or_protocol_as_origin()
  2657. default_encountered = False
  2658. # Also, a TypeVarLike with a default cannot appear after a TypeVarTuple
  2659. type_var_tuple_encountered = False
  2660. for t in args:
  2661. if isinstance(t, type):
  2662. # We don't want __parameters__ descriptor of a bare Python class.
  2663. pass
  2664. elif isinstance(t, tuple):
  2665. # `t` might be a tuple, when `ParamSpec` is substituted with
  2666. # `[T, int]`, or `[int, *Ts]`, etc.
  2667. for x in t:
  2668. for collected in _collect_parameters([x]):
  2669. if collected not in parameters:
  2670. parameters.append(collected)
  2671. elif hasattr(t, '__typing_subst__'):
  2672. if t not in parameters:
  2673. if enforce_default_ordering:
  2674. has_default = (
  2675. getattr(t, '__default__', NoDefault) is not NoDefault
  2676. )
  2677. if type_var_tuple_encountered and has_default:
  2678. raise TypeError('Type parameter with a default'
  2679. ' follows TypeVarTuple')
  2680. if has_default:
  2681. default_encountered = True
  2682. elif default_encountered:
  2683. raise TypeError(f'Type parameter {t!r} without a default'
  2684. ' follows type parameter with a default')
  2685. parameters.append(t)
  2686. else:
  2687. if _is_unpacked_typevartuple(t):
  2688. type_var_tuple_encountered = True
  2689. for x in getattr(t, '__parameters__', ()):
  2690. if x not in parameters:
  2691. parameters.append(x)
  2692. return tuple(parameters)
  2693. if not _PEP_696_IMPLEMENTED:
  2694. typing._collect_parameters = _collect_parameters
  2695. # Backport typing.NamedTuple as it exists in Python 3.13.
  2696. # In 3.11, the ability to define generic `NamedTuple`s was supported.
  2697. # This was explicitly disallowed in 3.9-3.10, and only half-worked in <=3.8.
  2698. # On 3.12, we added __orig_bases__ to call-based NamedTuples
  2699. # On 3.13, we deprecated kwargs-based NamedTuples
  2700. # Breakpoint: https://github.com/python/cpython/pull/105609
  2701. if sys.version_info >= (3, 13):
  2702. NamedTuple = typing.NamedTuple
  2703. else:
  2704. def _make_nmtuple(name, types, module, defaults=()):
  2705. fields = [n for n, t in types]
  2706. annotations = {n: typing._type_check(t, f"field {n} annotation must be a type")
  2707. for n, t in types}
  2708. nm_tpl = collections.namedtuple(name, fields,
  2709. defaults=defaults, module=module)
  2710. nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = annotations
  2711. return nm_tpl
  2712. _prohibited_namedtuple_fields = typing._prohibited
  2713. _special_namedtuple_fields = frozenset({'__module__', '__name__', '__annotations__'})
  2714. class _NamedTupleMeta(type):
  2715. def __new__(cls, typename, bases, ns):
  2716. assert _NamedTuple in bases
  2717. for base in bases:
  2718. if base is not _NamedTuple and base is not typing.Generic:
  2719. raise TypeError(
  2720. 'can only inherit from a NamedTuple type and Generic')
  2721. bases = tuple(tuple if base is _NamedTuple else base for base in bases)
  2722. if "__annotations__" in ns:
  2723. types = ns["__annotations__"]
  2724. elif "__annotate__" in ns:
  2725. # TODO: Use inspect.VALUE here, and make the annotations lazily evaluated
  2726. types = ns["__annotate__"](1)
  2727. else:
  2728. types = {}
  2729. default_names = []
  2730. for field_name in types:
  2731. if field_name in ns:
  2732. default_names.append(field_name)
  2733. elif default_names:
  2734. raise TypeError(f"Non-default namedtuple field {field_name} "
  2735. f"cannot follow default field"
  2736. f"{'s' if len(default_names) > 1 else ''} "
  2737. f"{', '.join(default_names)}")
  2738. nm_tpl = _make_nmtuple(
  2739. typename, types.items(),
  2740. defaults=[ns[n] for n in default_names],
  2741. module=ns['__module__']
  2742. )
  2743. nm_tpl.__bases__ = bases
  2744. if typing.Generic in bases:
  2745. if hasattr(typing, '_generic_class_getitem'): # 3.12+
  2746. nm_tpl.__class_getitem__ = classmethod(typing._generic_class_getitem)
  2747. else:
  2748. class_getitem = typing.Generic.__class_getitem__.__func__
  2749. nm_tpl.__class_getitem__ = classmethod(class_getitem)
  2750. # update from user namespace without overriding special namedtuple attributes
  2751. for key, val in ns.items():
  2752. if key in _prohibited_namedtuple_fields:
  2753. raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
  2754. elif key not in _special_namedtuple_fields:
  2755. if key not in nm_tpl._fields:
  2756. setattr(nm_tpl, key, ns[key])
  2757. try:
  2758. set_name = type(val).__set_name__
  2759. except AttributeError:
  2760. pass
  2761. else:
  2762. try:
  2763. set_name(val, nm_tpl, key)
  2764. except BaseException as e:
  2765. msg = (
  2766. f"Error calling __set_name__ on {type(val).__name__!r} "
  2767. f"instance {key!r} in {typename!r}"
  2768. )
  2769. # BaseException.add_note() existed on py311,
  2770. # but the __set_name__ machinery didn't start
  2771. # using add_note() until py312.
  2772. # Making sure exceptions are raised in the same way
  2773. # as in "normal" classes seems most important here.
  2774. # Breakpoint: https://github.com/python/cpython/pull/95915
  2775. if sys.version_info >= (3, 12):
  2776. e.add_note(msg)
  2777. raise
  2778. else:
  2779. raise RuntimeError(msg) from e
  2780. if typing.Generic in bases:
  2781. nm_tpl.__init_subclass__()
  2782. return nm_tpl
  2783. _NamedTuple = type.__new__(_NamedTupleMeta, 'NamedTuple', (), {})
  2784. def _namedtuple_mro_entries(bases):
  2785. assert NamedTuple in bases
  2786. return (_NamedTuple,)
  2787. def NamedTuple(typename, fields=_marker, /, **kwargs):
  2788. """Typed version of namedtuple.
  2789. Usage::
  2790. class Employee(NamedTuple):
  2791. name: str
  2792. id: int
  2793. This is equivalent to::
  2794. Employee = collections.namedtuple('Employee', ['name', 'id'])
  2795. The resulting class has an extra __annotations__ attribute, giving a
  2796. dict that maps field names to types. (The field names are also in
  2797. the _fields attribute, which is part of the namedtuple API.)
  2798. An alternative equivalent functional syntax is also accepted::
  2799. Employee = NamedTuple('Employee', [('name', str), ('id', int)])
  2800. """
  2801. if fields is _marker:
  2802. if kwargs:
  2803. deprecated_thing = "Creating NamedTuple classes using keyword arguments"
  2804. deprecation_msg = (
  2805. "{name} is deprecated and will be disallowed in Python {remove}. "
  2806. "Use the class-based or functional syntax instead."
  2807. )
  2808. else:
  2809. deprecated_thing = "Failing to pass a value for the 'fields' parameter"
  2810. example = f"`{typename} = NamedTuple({typename!r}, [])`"
  2811. deprecation_msg = (
  2812. "{name} is deprecated and will be disallowed in Python {remove}. "
  2813. "To create a NamedTuple class with 0 fields "
  2814. "using the functional syntax, "
  2815. "pass an empty list, e.g. "
  2816. ) + example + "."
  2817. elif fields is None:
  2818. if kwargs:
  2819. raise TypeError(
  2820. "Cannot pass `None` as the 'fields' parameter "
  2821. "and also specify fields using keyword arguments"
  2822. )
  2823. else:
  2824. deprecated_thing = "Passing `None` as the 'fields' parameter"
  2825. example = f"`{typename} = NamedTuple({typename!r}, [])`"
  2826. deprecation_msg = (
  2827. "{name} is deprecated and will be disallowed in Python {remove}. "
  2828. "To create a NamedTuple class with 0 fields "
  2829. "using the functional syntax, "
  2830. "pass an empty list, e.g. "
  2831. ) + example + "."
  2832. elif kwargs:
  2833. raise TypeError("Either list of fields or keywords"
  2834. " can be provided to NamedTuple, not both")
  2835. if fields is _marker or fields is None:
  2836. warnings.warn(
  2837. deprecation_msg.format(name=deprecated_thing, remove="3.15"),
  2838. DeprecationWarning,
  2839. stacklevel=2,
  2840. )
  2841. fields = kwargs.items()
  2842. nt = _make_nmtuple(typename, fields, module=_caller())
  2843. nt.__orig_bases__ = (NamedTuple,)
  2844. return nt
  2845. NamedTuple.__mro_entries__ = _namedtuple_mro_entries
  2846. if hasattr(collections.abc, "Buffer"):
  2847. Buffer = collections.abc.Buffer
  2848. else:
  2849. class Buffer(abc.ABC): # noqa: B024
  2850. """Base class for classes that implement the buffer protocol.
  2851. The buffer protocol allows Python objects to expose a low-level
  2852. memory buffer interface. Before Python 3.12, it is not possible
  2853. to implement the buffer protocol in pure Python code, or even
  2854. to check whether a class implements the buffer protocol. In
  2855. Python 3.12 and higher, the ``__buffer__`` method allows access
  2856. to the buffer protocol from Python code, and the
  2857. ``collections.abc.Buffer`` ABC allows checking whether a class
  2858. implements the buffer protocol.
  2859. To indicate support for the buffer protocol in earlier versions,
  2860. inherit from this ABC, either in a stub file or at runtime,
  2861. or use ABC registration. This ABC provides no methods, because
  2862. there is no Python-accessible methods shared by pre-3.12 buffer
  2863. classes. It is useful primarily for static checks.
  2864. """
  2865. # As a courtesy, register the most common stdlib buffer classes.
  2866. Buffer.register(memoryview)
  2867. Buffer.register(bytearray)
  2868. Buffer.register(bytes)
  2869. # Backport of types.get_original_bases, available on 3.12+ in CPython
  2870. if hasattr(_types, "get_original_bases"):
  2871. get_original_bases = _types.get_original_bases
  2872. else:
  2873. def get_original_bases(cls, /):
  2874. """Return the class's "original" bases prior to modification by `__mro_entries__`.
  2875. Examples::
  2876. from typing import TypeVar, Generic
  2877. from typing_extensions import NamedTuple, TypedDict
  2878. T = TypeVar("T")
  2879. class Foo(Generic[T]): ...
  2880. class Bar(Foo[int], float): ...
  2881. class Baz(list[str]): ...
  2882. Eggs = NamedTuple("Eggs", [("a", int), ("b", str)])
  2883. Spam = TypedDict("Spam", {"a": int, "b": str})
  2884. assert get_original_bases(Bar) == (Foo[int], float)
  2885. assert get_original_bases(Baz) == (list[str],)
  2886. assert get_original_bases(Eggs) == (NamedTuple,)
  2887. assert get_original_bases(Spam) == (TypedDict,)
  2888. assert get_original_bases(int) == (object,)
  2889. """
  2890. try:
  2891. return cls.__dict__.get("__orig_bases__", cls.__bases__)
  2892. except AttributeError:
  2893. raise TypeError(
  2894. f'Expected an instance of type, not {type(cls).__name__!r}'
  2895. ) from None
  2896. # NewType is a class on Python 3.10+, making it pickleable
  2897. # The error message for subclassing instances of NewType was improved on 3.11+
  2898. # Breakpoint: https://github.com/python/cpython/pull/30268
  2899. if sys.version_info >= (3, 11):
  2900. NewType = typing.NewType
  2901. else:
  2902. class NewType:
  2903. """NewType creates simple unique types with almost zero
  2904. runtime overhead. NewType(name, tp) is considered a subtype of tp
  2905. by static type checkers. At runtime, NewType(name, tp) returns
  2906. a dummy callable that simply returns its argument. Usage::
  2907. UserId = NewType('UserId', int)
  2908. def name_by_id(user_id: UserId) -> str:
  2909. ...
  2910. UserId('user') # Fails type check
  2911. name_by_id(42) # Fails type check
  2912. name_by_id(UserId(42)) # OK
  2913. num = UserId(5) + 1 # type: int
  2914. """
  2915. def __call__(self, obj, /):
  2916. return obj
  2917. def __init__(self, name, tp):
  2918. self.__qualname__ = name
  2919. if '.' in name:
  2920. name = name.rpartition('.')[-1]
  2921. self.__name__ = name
  2922. self.__supertype__ = tp
  2923. def_mod = _caller()
  2924. if def_mod != 'typing_extensions':
  2925. self.__module__ = def_mod
  2926. def __mro_entries__(self, bases):
  2927. # We defined __mro_entries__ to get a better error message
  2928. # if a user attempts to subclass a NewType instance. bpo-46170
  2929. supercls_name = self.__name__
  2930. class Dummy:
  2931. def __init_subclass__(cls):
  2932. subcls_name = cls.__name__
  2933. raise TypeError(
  2934. f"Cannot subclass an instance of NewType. "
  2935. f"Perhaps you were looking for: "
  2936. f"`{subcls_name} = NewType({subcls_name!r}, {supercls_name})`"
  2937. )
  2938. return (Dummy,)
  2939. def __repr__(self):
  2940. return f'{self.__module__}.{self.__qualname__}'
  2941. def __reduce__(self):
  2942. return self.__qualname__
  2943. # Breakpoint: https://github.com/python/cpython/pull/21515
  2944. if sys.version_info >= (3, 10):
  2945. # PEP 604 methods
  2946. # It doesn't make sense to have these methods on Python <3.10
  2947. def __or__(self, other):
  2948. return typing.Union[self, other]
  2949. def __ror__(self, other):
  2950. return typing.Union[other, self]
  2951. # Breakpoint: https://github.com/python/cpython/pull/124795
  2952. if sys.version_info >= (3, 14):
  2953. TypeAliasType = typing.TypeAliasType
  2954. # <=3.13
  2955. else:
  2956. # Breakpoint: https://github.com/python/cpython/pull/103764
  2957. if sys.version_info >= (3, 12):
  2958. # 3.12-3.13
  2959. def _is_unionable(obj):
  2960. """Corresponds to is_unionable() in unionobject.c in CPython."""
  2961. return obj is None or isinstance(obj, (
  2962. type,
  2963. _types.GenericAlias,
  2964. _types.UnionType,
  2965. typing.TypeAliasType,
  2966. TypeAliasType,
  2967. ))
  2968. else:
  2969. # <=3.11
  2970. def _is_unionable(obj):
  2971. """Corresponds to is_unionable() in unionobject.c in CPython."""
  2972. return obj is None or isinstance(obj, (
  2973. type,
  2974. _types.GenericAlias,
  2975. _types.UnionType,
  2976. TypeAliasType,
  2977. ))
  2978. if sys.version_info < (3, 10):
  2979. # Copied and pasted from https://github.com/python/cpython/blob/986a4e1b6fcae7fe7a1d0a26aea446107dd58dd2/Objects/genericaliasobject.c#L568-L582,
  2980. # so that we emulate the behaviour of `types.GenericAlias`
  2981. # on the latest versions of CPython
  2982. _ATTRIBUTE_DELEGATION_EXCLUSIONS = frozenset({
  2983. "__class__",
  2984. "__bases__",
  2985. "__origin__",
  2986. "__args__",
  2987. "__unpacked__",
  2988. "__parameters__",
  2989. "__typing_unpacked_tuple_args__",
  2990. "__mro_entries__",
  2991. "__reduce_ex__",
  2992. "__reduce__",
  2993. "__copy__",
  2994. "__deepcopy__",
  2995. })
  2996. class _TypeAliasGenericAlias(typing._GenericAlias, _root=True):
  2997. def __getattr__(self, attr):
  2998. if attr in _ATTRIBUTE_DELEGATION_EXCLUSIONS:
  2999. return object.__getattr__(self, attr)
  3000. return getattr(self.__origin__, attr)
  3001. class TypeAliasType:
  3002. """Create named, parameterized type aliases.
  3003. This provides a backport of the new `type` statement in Python 3.12:
  3004. type ListOrSet[T] = list[T] | set[T]
  3005. is equivalent to:
  3006. T = TypeVar("T")
  3007. ListOrSet = TypeAliasType("ListOrSet", list[T] | set[T], type_params=(T,))
  3008. The name ListOrSet can then be used as an alias for the type it refers to.
  3009. The type_params argument should contain all the type parameters used
  3010. in the value of the type alias. If the alias is not generic, this
  3011. argument is omitted.
  3012. Static type checkers should only support type aliases declared using
  3013. TypeAliasType that follow these rules:
  3014. - The first argument (the name) must be a string literal.
  3015. - The TypeAliasType instance must be immediately assigned to a variable
  3016. of the same name. (For example, 'X = TypeAliasType("Y", int)' is invalid,
  3017. as is 'X, Y = TypeAliasType("X", int), TypeAliasType("Y", int)').
  3018. """
  3019. def __init__(self, name: str, value, *, type_params=()):
  3020. if not isinstance(name, str):
  3021. raise TypeError("TypeAliasType name must be a string")
  3022. if not isinstance(type_params, tuple):
  3023. raise TypeError("type_params must be a tuple")
  3024. self.__value__ = value
  3025. self.__type_params__ = type_params
  3026. default_value_encountered = False
  3027. parameters = []
  3028. for type_param in type_params:
  3029. if (
  3030. not isinstance(type_param, (TypeVar, TypeVarTuple, ParamSpec))
  3031. # <=3.11
  3032. # Unpack Backport passes isinstance(type_param, TypeVar)
  3033. or _is_unpack(type_param)
  3034. ):
  3035. raise TypeError(f"Expected a type param, got {type_param!r}")
  3036. has_default = (
  3037. getattr(type_param, '__default__', NoDefault) is not NoDefault
  3038. )
  3039. if default_value_encountered and not has_default:
  3040. raise TypeError(f"non-default type parameter '{type_param!r}'"
  3041. " follows default type parameter")
  3042. if has_default:
  3043. default_value_encountered = True
  3044. if isinstance(type_param, TypeVarTuple):
  3045. parameters.extend(type_param)
  3046. else:
  3047. parameters.append(type_param)
  3048. self.__parameters__ = tuple(parameters)
  3049. def_mod = _caller()
  3050. if def_mod != 'typing_extensions':
  3051. self.__module__ = def_mod
  3052. # Setting this attribute closes the TypeAliasType from further modification
  3053. self.__name__ = name
  3054. def __setattr__(self, name: str, value: object, /) -> None:
  3055. if hasattr(self, "__name__"):
  3056. self._raise_attribute_error(name)
  3057. super().__setattr__(name, value)
  3058. def __delattr__(self, name: str, /) -> Never:
  3059. self._raise_attribute_error(name)
  3060. def _raise_attribute_error(self, name: str) -> Never:
  3061. # Match the Python 3.12 error messages exactly
  3062. if name == "__name__":
  3063. raise AttributeError("readonly attribute")
  3064. elif name in {"__value__", "__type_params__", "__parameters__", "__module__"}:
  3065. raise AttributeError(
  3066. f"attribute '{name}' of 'typing.TypeAliasType' objects "
  3067. "is not writable"
  3068. )
  3069. else:
  3070. raise AttributeError(
  3071. f"'typing.TypeAliasType' object has no attribute '{name}'"
  3072. )
  3073. def __repr__(self) -> str:
  3074. return self.__name__
  3075. if sys.version_info < (3, 11):
  3076. def _check_single_param(self, param, recursion=0):
  3077. # Allow [], [int], [int, str], [int, ...], [int, T]
  3078. if param is ...:
  3079. return ...
  3080. if param is None:
  3081. return None
  3082. # Note in <= 3.9 _ConcatenateGenericAlias inherits from list
  3083. if isinstance(param, list) and recursion == 0:
  3084. return [self._check_single_param(arg, recursion+1)
  3085. for arg in param]
  3086. return typing._type_check(
  3087. param, f'Subscripting {self.__name__} requires a type.'
  3088. )
  3089. def _check_parameters(self, parameters):
  3090. if sys.version_info < (3, 11):
  3091. return tuple(
  3092. self._check_single_param(item)
  3093. for item in parameters
  3094. )
  3095. return tuple(typing._type_check(
  3096. item, f'Subscripting {self.__name__} requires a type.'
  3097. )
  3098. for item in parameters
  3099. )
  3100. def __getitem__(self, parameters):
  3101. if not self.__type_params__:
  3102. raise TypeError("Only generic type aliases are subscriptable")
  3103. if not isinstance(parameters, tuple):
  3104. parameters = (parameters,)
  3105. # Using 3.9 here will create problems with Concatenate
  3106. if sys.version_info >= (3, 10):
  3107. return _types.GenericAlias(self, parameters)
  3108. type_vars = _collect_type_vars(parameters)
  3109. parameters = self._check_parameters(parameters)
  3110. alias = _TypeAliasGenericAlias(self, parameters)
  3111. # alias.__parameters__ is not complete if Concatenate is present
  3112. # as it is converted to a list from which no parameters are extracted.
  3113. if alias.__parameters__ != type_vars:
  3114. alias.__parameters__ = type_vars
  3115. return alias
  3116. def __reduce__(self):
  3117. return self.__name__
  3118. def __init_subclass__(cls, *args, **kwargs):
  3119. raise TypeError(
  3120. "type 'typing_extensions.TypeAliasType' is not an acceptable base type"
  3121. )
  3122. # The presence of this method convinces typing._type_check
  3123. # that TypeAliasTypes are types.
  3124. def __call__(self):
  3125. raise TypeError("Type alias is not callable")
  3126. # Breakpoint: https://github.com/python/cpython/pull/21515
  3127. if sys.version_info >= (3, 10):
  3128. def __or__(self, right):
  3129. # For forward compatibility with 3.12, reject Unions
  3130. # that are not accepted by the built-in Union.
  3131. if not _is_unionable(right):
  3132. return NotImplemented
  3133. return typing.Union[self, right]
  3134. def __ror__(self, left):
  3135. if not _is_unionable(left):
  3136. return NotImplemented
  3137. return typing.Union[left, self]
  3138. if hasattr(typing, "is_protocol"):
  3139. is_protocol = typing.is_protocol
  3140. get_protocol_members = typing.get_protocol_members
  3141. else:
  3142. def is_protocol(tp: type, /) -> bool:
  3143. """Return True if the given type is a Protocol.
  3144. Example::
  3145. >>> from typing_extensions import Protocol, is_protocol
  3146. >>> class P(Protocol):
  3147. ... def a(self) -> str: ...
  3148. ... b: int
  3149. >>> is_protocol(P)
  3150. True
  3151. >>> is_protocol(int)
  3152. False
  3153. """
  3154. return (
  3155. isinstance(tp, type)
  3156. and getattr(tp, '_is_protocol', False)
  3157. and tp is not Protocol
  3158. and tp is not typing.Protocol
  3159. )
  3160. def get_protocol_members(tp: type, /) -> typing.FrozenSet[str]:
  3161. """Return the set of members defined in a Protocol.
  3162. Example::
  3163. >>> from typing_extensions import Protocol, get_protocol_members
  3164. >>> class P(Protocol):
  3165. ... def a(self) -> str: ...
  3166. ... b: int
  3167. >>> get_protocol_members(P)
  3168. frozenset({'a', 'b'})
  3169. Raise a TypeError for arguments that are not Protocols.
  3170. """
  3171. if not is_protocol(tp):
  3172. raise TypeError(f'{tp!r} is not a Protocol')
  3173. if hasattr(tp, '__protocol_attrs__'):
  3174. return frozenset(tp.__protocol_attrs__)
  3175. return frozenset(_get_protocol_attrs(tp))
  3176. if hasattr(typing, "Doc"):
  3177. Doc = typing.Doc
  3178. else:
  3179. class Doc:
  3180. """Define the documentation of a type annotation using ``Annotated``, to be
  3181. used in class attributes, function and method parameters, return values,
  3182. and variables.
  3183. The value should be a positional-only string literal to allow static tools
  3184. like editors and documentation generators to use it.
  3185. This complements docstrings.
  3186. The string value passed is available in the attribute ``documentation``.
  3187. Example::
  3188. >>> from typing_extensions import Annotated, Doc
  3189. >>> def hi(to: Annotated[str, Doc("Who to say hi to")]) -> None: ...
  3190. """
  3191. def __init__(self, documentation: str, /) -> None:
  3192. self.documentation = documentation
  3193. def __repr__(self) -> str:
  3194. return f"Doc({self.documentation!r})"
  3195. def __hash__(self) -> int:
  3196. return hash(self.documentation)
  3197. def __eq__(self, other: object) -> bool:
  3198. if not isinstance(other, Doc):
  3199. return NotImplemented
  3200. return self.documentation == other.documentation
  3201. _CapsuleType = getattr(_types, "CapsuleType", None)
  3202. if _CapsuleType is None:
  3203. try:
  3204. import _socket
  3205. except ImportError:
  3206. pass
  3207. else:
  3208. _CAPI = getattr(_socket, "CAPI", None)
  3209. if _CAPI is not None:
  3210. _CapsuleType = type(_CAPI)
  3211. if _CapsuleType is not None:
  3212. CapsuleType = _CapsuleType
  3213. __all__.append("CapsuleType")
  3214. if sys.version_info >= (3, 14):
  3215. from annotationlib import Format, get_annotations
  3216. else:
  3217. # Available since Python 3.14.0a3
  3218. # PR: https://github.com/python/cpython/pull/124415
  3219. class Format(enum.IntEnum):
  3220. VALUE = 1
  3221. VALUE_WITH_FAKE_GLOBALS = 2
  3222. FORWARDREF = 3
  3223. STRING = 4
  3224. # Available since Python 3.14.0a1
  3225. # PR: https://github.com/python/cpython/pull/119891
  3226. def get_annotations(obj, *, globals=None, locals=None, eval_str=False,
  3227. format=Format.VALUE):
  3228. """Compute the annotations dict for an object.
  3229. obj may be a callable, class, or module.
  3230. Passing in an object of any other type raises TypeError.
  3231. Returns a dict. get_annotations() returns a new dict every time
  3232. it's called; calling it twice on the same object will return two
  3233. different but equivalent dicts.
  3234. This is a backport of `inspect.get_annotations`, which has been
  3235. in the standard library since Python 3.10. See the standard library
  3236. documentation for more:
  3237. https://docs.python.org/3/library/inspect.html#inspect.get_annotations
  3238. This backport adds the *format* argument introduced by PEP 649. The
  3239. three formats supported are:
  3240. * VALUE: the annotations are returned as-is. This is the default and
  3241. it is compatible with the behavior on previous Python versions.
  3242. * FORWARDREF: return annotations as-is if possible, but replace any
  3243. undefined names with ForwardRef objects. The implementation proposed by
  3244. PEP 649 relies on language changes that cannot be backported; the
  3245. typing-extensions implementation simply returns the same result as VALUE.
  3246. * STRING: return annotations as strings, in a format close to the original
  3247. source. Again, this behavior cannot be replicated directly in a backport.
  3248. As an approximation, typing-extensions retrieves the annotations under
  3249. VALUE semantics and then stringifies them.
  3250. The purpose of this backport is to allow users who would like to use
  3251. FORWARDREF or STRING semantics once PEP 649 is implemented, but who also
  3252. want to support earlier Python versions, to simply write:
  3253. typing_extensions.get_annotations(obj, format=Format.FORWARDREF)
  3254. """
  3255. format = Format(format)
  3256. if format is Format.VALUE_WITH_FAKE_GLOBALS:
  3257. raise ValueError(
  3258. "The VALUE_WITH_FAKE_GLOBALS format is for internal use only"
  3259. )
  3260. if eval_str and format is not Format.VALUE:
  3261. raise ValueError("eval_str=True is only supported with format=Format.VALUE")
  3262. if isinstance(obj, type):
  3263. # class
  3264. obj_dict = getattr(obj, '__dict__', None)
  3265. if obj_dict and hasattr(obj_dict, 'get'):
  3266. ann = obj_dict.get('__annotations__', None)
  3267. if isinstance(ann, _types.GetSetDescriptorType):
  3268. ann = None
  3269. else:
  3270. ann = None
  3271. obj_globals = None
  3272. module_name = getattr(obj, '__module__', None)
  3273. if module_name:
  3274. module = sys.modules.get(module_name, None)
  3275. if module:
  3276. obj_globals = getattr(module, '__dict__', None)
  3277. obj_locals = dict(vars(obj))
  3278. unwrap = obj
  3279. elif isinstance(obj, _types.ModuleType):
  3280. # module
  3281. ann = getattr(obj, '__annotations__', None)
  3282. obj_globals = obj.__dict__
  3283. obj_locals = None
  3284. unwrap = None
  3285. elif callable(obj):
  3286. # this includes types.Function, types.BuiltinFunctionType,
  3287. # types.BuiltinMethodType, functools.partial, functools.singledispatch,
  3288. # "class funclike" from Lib/test/test_inspect... on and on it goes.
  3289. ann = getattr(obj, '__annotations__', None)
  3290. obj_globals = getattr(obj, '__globals__', None)
  3291. obj_locals = None
  3292. unwrap = obj
  3293. elif hasattr(obj, '__annotations__'):
  3294. ann = obj.__annotations__
  3295. obj_globals = obj_locals = unwrap = None
  3296. else:
  3297. raise TypeError(f"{obj!r} is not a module, class, or callable.")
  3298. if ann is None:
  3299. return {}
  3300. if not isinstance(ann, dict):
  3301. raise ValueError(f"{obj!r}.__annotations__ is neither a dict nor None")
  3302. if not ann:
  3303. return {}
  3304. if not eval_str:
  3305. if format is Format.STRING:
  3306. return {
  3307. key: value if isinstance(value, str) else typing._type_repr(value)
  3308. for key, value in ann.items()
  3309. }
  3310. return dict(ann)
  3311. if unwrap is not None:
  3312. while True:
  3313. if hasattr(unwrap, '__wrapped__'):
  3314. unwrap = unwrap.__wrapped__
  3315. continue
  3316. if isinstance(unwrap, functools.partial):
  3317. unwrap = unwrap.func
  3318. continue
  3319. break
  3320. if hasattr(unwrap, "__globals__"):
  3321. obj_globals = unwrap.__globals__
  3322. if globals is None:
  3323. globals = obj_globals
  3324. if locals is None:
  3325. locals = obj_locals or {}
  3326. # "Inject" type parameters into the local namespace
  3327. # (unless they are shadowed by assignments *in* the local namespace),
  3328. # as a way of emulating annotation scopes when calling `eval()`
  3329. if type_params := getattr(obj, "__type_params__", ()):
  3330. locals = {param.__name__: param for param in type_params} | locals
  3331. return_value = {key:
  3332. value if not isinstance(value, str) else eval(value, globals, locals)
  3333. for key, value in ann.items() }
  3334. return return_value
  3335. if hasattr(typing, "evaluate_forward_ref"):
  3336. evaluate_forward_ref = typing.evaluate_forward_ref
  3337. else:
  3338. # Implements annotationlib.ForwardRef.evaluate
  3339. def _eval_with_owner(
  3340. forward_ref, *, owner=None, globals=None, locals=None, type_params=None
  3341. ):
  3342. if forward_ref.__forward_evaluated__:
  3343. return forward_ref.__forward_value__
  3344. if getattr(forward_ref, "__cell__", None) is not None:
  3345. try:
  3346. value = forward_ref.__cell__.cell_contents
  3347. except ValueError:
  3348. pass
  3349. else:
  3350. forward_ref.__forward_evaluated__ = True
  3351. forward_ref.__forward_value__ = value
  3352. return value
  3353. if owner is None:
  3354. owner = getattr(forward_ref, "__owner__", None)
  3355. if (
  3356. globals is None
  3357. and getattr(forward_ref, "__forward_module__", None) is not None
  3358. ):
  3359. globals = getattr(
  3360. sys.modules.get(forward_ref.__forward_module__, None), "__dict__", None
  3361. )
  3362. if globals is None:
  3363. globals = getattr(forward_ref, "__globals__", None)
  3364. if globals is None:
  3365. if isinstance(owner, type):
  3366. module_name = getattr(owner, "__module__", None)
  3367. if module_name:
  3368. module = sys.modules.get(module_name, None)
  3369. if module:
  3370. globals = getattr(module, "__dict__", None)
  3371. elif isinstance(owner, _types.ModuleType):
  3372. globals = getattr(owner, "__dict__", None)
  3373. elif callable(owner):
  3374. globals = getattr(owner, "__globals__", None)
  3375. # If we pass None to eval() below, the globals of this module are used.
  3376. if globals is None:
  3377. globals = {}
  3378. if locals is None:
  3379. locals = {}
  3380. if isinstance(owner, type):
  3381. locals.update(vars(owner))
  3382. if type_params is None and owner is not None:
  3383. # "Inject" type parameters into the local namespace
  3384. # (unless they are shadowed by assignments *in* the local namespace),
  3385. # as a way of emulating annotation scopes when calling `eval()`
  3386. type_params = getattr(owner, "__type_params__", None)
  3387. # Type parameters exist in their own scope, which is logically
  3388. # between the locals and the globals. We simulate this by adding
  3389. # them to the globals.
  3390. if type_params is not None:
  3391. globals = dict(globals)
  3392. for param in type_params:
  3393. globals[param.__name__] = param
  3394. arg = forward_ref.__forward_arg__
  3395. if arg.isidentifier() and not keyword.iskeyword(arg):
  3396. if arg in locals:
  3397. value = locals[arg]
  3398. elif arg in globals:
  3399. value = globals[arg]
  3400. elif hasattr(builtins, arg):
  3401. return getattr(builtins, arg)
  3402. else:
  3403. raise NameError(arg)
  3404. else:
  3405. code = forward_ref.__forward_code__
  3406. value = eval(code, globals, locals)
  3407. forward_ref.__forward_evaluated__ = True
  3408. forward_ref.__forward_value__ = value
  3409. return value
  3410. def evaluate_forward_ref(
  3411. forward_ref,
  3412. *,
  3413. owner=None,
  3414. globals=None,
  3415. locals=None,
  3416. type_params=None,
  3417. format=None,
  3418. _recursive_guard=frozenset(),
  3419. ):
  3420. """Evaluate a forward reference as a type hint.
  3421. This is similar to calling the ForwardRef.evaluate() method,
  3422. but unlike that method, evaluate_forward_ref() also:
  3423. * Recursively evaluates forward references nested within the type hint.
  3424. * Rejects certain objects that are not valid type hints.
  3425. * Replaces type hints that evaluate to None with types.NoneType.
  3426. * Supports the *FORWARDREF* and *STRING* formats.
  3427. *forward_ref* must be an instance of ForwardRef. *owner*, if given,
  3428. should be the object that holds the annotations that the forward reference
  3429. derived from, such as a module, class object, or function. It is used to
  3430. infer the namespaces to use for looking up names. *globals* and *locals*
  3431. can also be explicitly given to provide the global and local namespaces.
  3432. *type_params* is a tuple of type parameters that are in scope when
  3433. evaluating the forward reference. This parameter must be provided (though
  3434. it may be an empty tuple) if *owner* is not given and the forward reference
  3435. does not already have an owner set. *format* specifies the format of the
  3436. annotation and is a member of the annotationlib.Format enum.
  3437. """
  3438. if format == Format.STRING:
  3439. return forward_ref.__forward_arg__
  3440. if forward_ref.__forward_arg__ in _recursive_guard:
  3441. return forward_ref
  3442. # Evaluate the forward reference
  3443. try:
  3444. value = _eval_with_owner(
  3445. forward_ref,
  3446. owner=owner,
  3447. globals=globals,
  3448. locals=locals,
  3449. type_params=type_params,
  3450. )
  3451. except NameError:
  3452. if format == Format.FORWARDREF:
  3453. return forward_ref
  3454. else:
  3455. raise
  3456. if isinstance(value, str):
  3457. value = ForwardRef(value)
  3458. # Recursively evaluate the type
  3459. if isinstance(value, ForwardRef):
  3460. if getattr(value, "__forward_module__", True) is not None:
  3461. globals = None
  3462. return evaluate_forward_ref(
  3463. value,
  3464. globals=globals,
  3465. locals=locals,
  3466. type_params=type_params, owner=owner,
  3467. _recursive_guard=_recursive_guard, format=format
  3468. )
  3469. if sys.version_info < (3, 12, 5) and type_params:
  3470. # Make use of type_params
  3471. locals = dict(locals) if locals else {}
  3472. for tvar in type_params:
  3473. if tvar.__name__ not in locals: # lets not overwrite something present
  3474. locals[tvar.__name__] = tvar
  3475. if sys.version_info < (3, 12, 5):
  3476. return typing._eval_type(
  3477. value,
  3478. globals,
  3479. locals,
  3480. recursive_guard=_recursive_guard | {forward_ref.__forward_arg__},
  3481. )
  3482. else:
  3483. return typing._eval_type(
  3484. value,
  3485. globals,
  3486. locals,
  3487. type_params,
  3488. recursive_guard=_recursive_guard | {forward_ref.__forward_arg__},
  3489. )
  3490. class Sentinel:
  3491. """Create a unique sentinel object.
  3492. *name* should be the name of the variable to which the return value shall be assigned.
  3493. *repr*, if supplied, will be used for the repr of the sentinel object.
  3494. If not provided, "<name>" will be used.
  3495. """
  3496. def __init__(
  3497. self,
  3498. name: str,
  3499. repr: typing.Optional[str] = None,
  3500. ):
  3501. self._name = name
  3502. self._repr = repr if repr is not None else f'<{name}>'
  3503. def __repr__(self):
  3504. return self._repr
  3505. if sys.version_info < (3, 11):
  3506. # The presence of this method convinces typing._type_check
  3507. # that Sentinels are types.
  3508. def __call__(self, *args, **kwargs):
  3509. raise TypeError(f"{type(self).__name__!r} object is not callable")
  3510. # Breakpoint: https://github.com/python/cpython/pull/21515
  3511. if sys.version_info >= (3, 10):
  3512. def __or__(self, other):
  3513. return typing.Union[self, other]
  3514. def __ror__(self, other):
  3515. return typing.Union[other, self]
  3516. def __getstate__(self):
  3517. raise TypeError(f"Cannot pickle {type(self).__name__!r} object")
  3518. if sys.version_info >= (3, 14, 0, "beta"):
  3519. type_repr = annotationlib.type_repr
  3520. else:
  3521. def type_repr(value):
  3522. """Convert a Python value to a format suitable for use with the STRING format.
  3523. This is intended as a helper for tools that support the STRING format but do
  3524. not have access to the code that originally produced the annotations. It uses
  3525. repr() for most objects.
  3526. """
  3527. if isinstance(value, (type, _types.FunctionType, _types.BuiltinFunctionType)):
  3528. if value.__module__ == "builtins":
  3529. return value.__qualname__
  3530. return f"{value.__module__}.{value.__qualname__}"
  3531. if value is ...:
  3532. return "..."
  3533. return repr(value)
  3534. # Aliases for items that are in typing in all supported versions.
  3535. # We use hasattr() checks so this library will continue to import on
  3536. # future versions of Python that may remove these names.
  3537. _typing_names = [
  3538. "AbstractSet",
  3539. "AnyStr",
  3540. "BinaryIO",
  3541. "Callable",
  3542. "Collection",
  3543. "Container",
  3544. "Dict",
  3545. "FrozenSet",
  3546. "Hashable",
  3547. "IO",
  3548. "ItemsView",
  3549. "Iterable",
  3550. "Iterator",
  3551. "KeysView",
  3552. "List",
  3553. "Mapping",
  3554. "MappingView",
  3555. "Match",
  3556. "MutableMapping",
  3557. "MutableSequence",
  3558. "MutableSet",
  3559. "Optional",
  3560. "Pattern",
  3561. "Reversible",
  3562. "Sequence",
  3563. "Set",
  3564. "Sized",
  3565. "TextIO",
  3566. "Tuple",
  3567. "Union",
  3568. "ValuesView",
  3569. "cast",
  3570. "no_type_check",
  3571. "no_type_check_decorator",
  3572. # This is private, but it was defined by typing_extensions for a long time
  3573. # and some users rely on it.
  3574. "_AnnotatedAlias",
  3575. ]
  3576. globals().update(
  3577. {name: getattr(typing, name) for name in _typing_names if hasattr(typing, name)}
  3578. )
  3579. # These are defined unconditionally because they are used in
  3580. # typing-extensions itself.
  3581. Generic = typing.Generic
  3582. ForwardRef = typing.ForwardRef
  3583. Annotated = typing.Annotated