Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

typing_extensions.py 108KB

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