typing_extensions.py 101 KB

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