typing_extensions.py 115 KB

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