typing_extensions.py 119 KB

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