typing_extensions.py 161 KB

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