typing_extensions.py 131 KB

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