typing.py 116 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480
  1. """
  2. The typing module: Support for gradual typing as defined by PEP 484 and subsequent PEPs.
  3. Among other things, the module includes the following:
  4. * Generic, Protocol, and internal machinery to support generic aliases.
  5. All subscripted types like X[int], Union[int, str] are generic aliases.
  6. * Various "special forms" that have unique meanings in type annotations:
  7. NoReturn, Never, ClassVar, Self, Concatenate, Unpack, and others.
  8. * Classes whose instances can be type arguments to generic classes and functions:
  9. TypeVar, ParamSpec, TypeVarTuple.
  10. * Public helper functions: get_type_hints, overload, cast, final, and others.
  11. * Several protocols to support duck-typing:
  12. SupportsFloat, SupportsIndex, SupportsAbs, and others.
  13. * Special types: NewType, NamedTuple, TypedDict.
  14. * Deprecated wrapper submodules for re and io related types.
  15. * Deprecated aliases for builtin types and collections.abc ABCs.
  16. Any name not present in __all__ is an implementation detail
  17. that may be changed without notice. Use at your own risk!
  18. """
  19. from abc import abstractmethod, ABCMeta
  20. import collections
  21. from collections import defaultdict
  22. import collections.abc
  23. import copyreg
  24. import contextlib
  25. import functools
  26. import operator
  27. import re as stdlib_re # Avoid confusion with the re we export.
  28. import sys
  29. import types
  30. import warnings
  31. from types import WrapperDescriptorType, MethodWrapperType, MethodDescriptorType, GenericAlias
  32. from _typing import (
  33. _idfunc,
  34. TypeVar,
  35. ParamSpec,
  36. TypeVarTuple,
  37. ParamSpecArgs,
  38. ParamSpecKwargs,
  39. TypeAliasType,
  40. Generic,
  41. )
  42. # Please keep __all__ alphabetized within each category.
  43. __all__ = [
  44. # Super-special typing primitives.
  45. 'Annotated',
  46. 'Any',
  47. 'Callable',
  48. 'ClassVar',
  49. 'Concatenate',
  50. 'Final',
  51. 'ForwardRef',
  52. 'Generic',
  53. 'Literal',
  54. 'Optional',
  55. 'ParamSpec',
  56. 'Protocol',
  57. 'Tuple',
  58. 'Type',
  59. 'TypeVar',
  60. 'TypeVarTuple',
  61. 'Union',
  62. # ABCs (from collections.abc).
  63. 'AbstractSet', # collections.abc.Set.
  64. 'ByteString',
  65. 'Container',
  66. 'ContextManager',
  67. 'Hashable',
  68. 'ItemsView',
  69. 'Iterable',
  70. 'Iterator',
  71. 'KeysView',
  72. 'Mapping',
  73. 'MappingView',
  74. 'MutableMapping',
  75. 'MutableSequence',
  76. 'MutableSet',
  77. 'Sequence',
  78. 'Sized',
  79. 'ValuesView',
  80. 'Awaitable',
  81. 'AsyncIterator',
  82. 'AsyncIterable',
  83. 'Coroutine',
  84. 'Collection',
  85. 'AsyncGenerator',
  86. 'AsyncContextManager',
  87. # Structural checks, a.k.a. protocols.
  88. 'Reversible',
  89. 'SupportsAbs',
  90. 'SupportsBytes',
  91. 'SupportsComplex',
  92. 'SupportsFloat',
  93. 'SupportsIndex',
  94. 'SupportsInt',
  95. 'SupportsRound',
  96. # Concrete collection types.
  97. 'ChainMap',
  98. 'Counter',
  99. 'Deque',
  100. 'Dict',
  101. 'DefaultDict',
  102. 'List',
  103. 'OrderedDict',
  104. 'Set',
  105. 'FrozenSet',
  106. 'NamedTuple', # Not really a type.
  107. 'TypedDict', # Not really a type.
  108. 'Generator',
  109. # Other concrete types.
  110. 'BinaryIO',
  111. 'IO',
  112. 'Match',
  113. 'Pattern',
  114. 'TextIO',
  115. # One-off things.
  116. 'AnyStr',
  117. 'assert_type',
  118. 'assert_never',
  119. 'cast',
  120. 'clear_overloads',
  121. 'dataclass_transform',
  122. 'final',
  123. 'get_args',
  124. 'get_origin',
  125. 'get_overloads',
  126. 'get_type_hints',
  127. 'is_typeddict',
  128. 'LiteralString',
  129. 'Never',
  130. 'NewType',
  131. 'no_type_check',
  132. 'no_type_check_decorator',
  133. 'NoReturn',
  134. 'NotRequired',
  135. 'overload',
  136. 'override',
  137. 'ParamSpecArgs',
  138. 'ParamSpecKwargs',
  139. 'Required',
  140. 'reveal_type',
  141. 'runtime_checkable',
  142. 'Self',
  143. 'Text',
  144. 'TYPE_CHECKING',
  145. 'TypeAlias',
  146. 'TypeGuard',
  147. 'TypeAliasType',
  148. 'Unpack',
  149. ]
  150. # The pseudo-submodules 're' and 'io' are part of the public
  151. # namespace, but excluded from __all__ because they might stomp on
  152. # legitimate imports of those modules.
  153. def _type_convert(arg, module=None, *, allow_special_forms=False):
  154. """For converting None to type(None), and strings to ForwardRef."""
  155. if arg is None:
  156. return type(None)
  157. if isinstance(arg, str):
  158. return ForwardRef(arg, module=module, is_class=allow_special_forms)
  159. return arg
  160. def _type_check(arg, msg, is_argument=True, module=None, *, allow_special_forms=False):
  161. """Check that the argument is a type, and return it (internal helper).
  162. As a special case, accept None and return type(None) instead. Also wrap strings
  163. into ForwardRef instances. Consider several corner cases, for example plain
  164. special forms like Union are not valid, while Union[int, str] is OK, etc.
  165. The msg argument is a human-readable error message, e.g.::
  166. "Union[arg, ...]: arg should be a type."
  167. We append the repr() of the actual value (truncated to 100 chars).
  168. """
  169. invalid_generic_forms = (Generic, Protocol)
  170. if not allow_special_forms:
  171. invalid_generic_forms += (ClassVar,)
  172. if is_argument:
  173. invalid_generic_forms += (Final,)
  174. arg = _type_convert(arg, module=module, allow_special_forms=allow_special_forms)
  175. if (isinstance(arg, _GenericAlias) and
  176. arg.__origin__ in invalid_generic_forms):
  177. raise TypeError(f"{arg} is not valid as type argument")
  178. if arg in (Any, LiteralString, NoReturn, Never, Self, TypeAlias):
  179. return arg
  180. if allow_special_forms and arg in (ClassVar, Final):
  181. return arg
  182. if isinstance(arg, _SpecialForm) or arg in (Generic, Protocol):
  183. raise TypeError(f"Plain {arg} is not valid as type argument")
  184. if type(arg) is tuple:
  185. raise TypeError(f"{msg} Got {arg!r:.100}.")
  186. return arg
  187. def _is_param_expr(arg):
  188. return arg is ... or isinstance(arg,
  189. (tuple, list, ParamSpec, _ConcatenateGenericAlias))
  190. def _should_unflatten_callable_args(typ, args):
  191. """Internal helper for munging collections.abc.Callable's __args__.
  192. The canonical representation for a Callable's __args__ flattens the
  193. argument types, see https://github.com/python/cpython/issues/86361.
  194. For example::
  195. >>> import collections.abc
  196. >>> P = ParamSpec('P')
  197. >>> collections.abc.Callable[[int, int], str].__args__ == (int, int, str)
  198. True
  199. >>> collections.abc.Callable[P, str].__args__ == (P, str)
  200. True
  201. As a result, if we need to reconstruct the Callable from its __args__,
  202. we need to unflatten it.
  203. """
  204. return (
  205. typ.__origin__ is collections.abc.Callable
  206. and not (len(args) == 2 and _is_param_expr(args[0]))
  207. )
  208. def _type_repr(obj):
  209. """Return the repr() of an object, special-casing types (internal helper).
  210. If obj is a type, we return a shorter version than the default
  211. type.__repr__, based on the module and qualified name, which is
  212. typically enough to uniquely identify a type. For everything
  213. else, we fall back on repr(obj).
  214. """
  215. # When changing this function, don't forget about
  216. # `_collections_abc._type_repr`, which does the same thing
  217. # and must be consistent with this one.
  218. if isinstance(obj, type):
  219. if obj.__module__ == 'builtins':
  220. return obj.__qualname__
  221. return f'{obj.__module__}.{obj.__qualname__}'
  222. if obj is ...:
  223. return '...'
  224. if isinstance(obj, types.FunctionType):
  225. return obj.__name__
  226. if isinstance(obj, tuple):
  227. # Special case for `repr` of types with `ParamSpec`:
  228. return '[' + ', '.join(_type_repr(t) for t in obj) + ']'
  229. return repr(obj)
  230. def _collect_parameters(args):
  231. """Collect all type variables and parameter specifications in args
  232. in order of first appearance (lexicographic order).
  233. For example::
  234. >>> P = ParamSpec('P')
  235. >>> T = TypeVar('T')
  236. >>> _collect_parameters((T, Callable[P, T]))
  237. (~T, ~P)
  238. """
  239. parameters = []
  240. for t in args:
  241. if isinstance(t, type):
  242. # We don't want __parameters__ descriptor of a bare Python class.
  243. pass
  244. elif isinstance(t, tuple):
  245. # `t` might be a tuple, when `ParamSpec` is substituted with
  246. # `[T, int]`, or `[int, *Ts]`, etc.
  247. for x in t:
  248. for collected in _collect_parameters([x]):
  249. if collected not in parameters:
  250. parameters.append(collected)
  251. elif hasattr(t, '__typing_subst__'):
  252. if t not in parameters:
  253. parameters.append(t)
  254. else:
  255. for x in getattr(t, '__parameters__', ()):
  256. if x not in parameters:
  257. parameters.append(x)
  258. return tuple(parameters)
  259. def _check_generic(cls, parameters, elen):
  260. """Check correct count for parameters of a generic cls (internal helper).
  261. This gives a nice error message in case of count mismatch.
  262. """
  263. if not elen:
  264. raise TypeError(f"{cls} is not a generic class")
  265. alen = len(parameters)
  266. if alen != elen:
  267. raise TypeError(f"Too {'many' if alen > elen else 'few'} arguments for {cls};"
  268. f" actual {alen}, expected {elen}")
  269. def _unpack_args(args):
  270. newargs = []
  271. for arg in args:
  272. subargs = getattr(arg, '__typing_unpacked_tuple_args__', None)
  273. if subargs is not None and not (subargs and subargs[-1] is ...):
  274. newargs.extend(subargs)
  275. else:
  276. newargs.append(arg)
  277. return newargs
  278. def _deduplicate(params, *, unhashable_fallback=False):
  279. # Weed out strict duplicates, preserving the first of each occurrence.
  280. try:
  281. return dict.fromkeys(params)
  282. except TypeError:
  283. if not unhashable_fallback:
  284. raise
  285. # Happens for cases like `Annotated[dict, {'x': IntValidator()}]`
  286. return _deduplicate_unhashable(params)
  287. def _deduplicate_unhashable(unhashable_params):
  288. new_unhashable = []
  289. for t in unhashable_params:
  290. if t not in new_unhashable:
  291. new_unhashable.append(t)
  292. return new_unhashable
  293. def _compare_args_orderless(first_args, second_args):
  294. first_unhashable = _deduplicate_unhashable(first_args)
  295. second_unhashable = _deduplicate_unhashable(second_args)
  296. t = list(second_unhashable)
  297. try:
  298. for elem in first_unhashable:
  299. t.remove(elem)
  300. except ValueError:
  301. return False
  302. return not t
  303. def _remove_dups_flatten(parameters):
  304. """Internal helper for Union creation and substitution.
  305. Flatten Unions among parameters, then remove duplicates.
  306. """
  307. # Flatten out Union[Union[...], ...].
  308. params = []
  309. for p in parameters:
  310. if isinstance(p, (_UnionGenericAlias, types.UnionType)):
  311. params.extend(p.__args__)
  312. else:
  313. params.append(p)
  314. return tuple(_deduplicate(params, unhashable_fallback=True))
  315. def _flatten_literal_params(parameters):
  316. """Internal helper for Literal creation: flatten Literals among parameters."""
  317. params = []
  318. for p in parameters:
  319. if isinstance(p, _LiteralGenericAlias):
  320. params.extend(p.__args__)
  321. else:
  322. params.append(p)
  323. return tuple(params)
  324. _cleanups = []
  325. _caches = {}
  326. def _tp_cache(func=None, /, *, typed=False):
  327. """Internal wrapper caching __getitem__ of generic types.
  328. For non-hashable arguments, the original function is used as a fallback.
  329. """
  330. def decorator(func):
  331. # The callback 'inner' references the newly created lru_cache
  332. # indirectly by performing a lookup in the global '_caches' dictionary.
  333. # This breaks a reference that can be problematic when combined with
  334. # C API extensions that leak references to types. See GH-98253.
  335. cache = functools.lru_cache(typed=typed)(func)
  336. _caches[func] = cache
  337. _cleanups.append(cache.cache_clear)
  338. del cache
  339. @functools.wraps(func)
  340. def inner(*args, **kwds):
  341. try:
  342. return _caches[func](*args, **kwds)
  343. except TypeError:
  344. pass # All real errors (not unhashable args) are raised below.
  345. return func(*args, **kwds)
  346. return inner
  347. if func is not None:
  348. return decorator(func)
  349. return decorator
  350. def _eval_type(t, globalns, localns, type_params=None, *, recursive_guard=frozenset()):
  351. """Evaluate all forward references in the given type t.
  352. For use of globalns and localns see the docstring for get_type_hints().
  353. recursive_guard is used to prevent infinite recursion with a recursive
  354. ForwardRef.
  355. """
  356. if isinstance(t, ForwardRef):
  357. return t._evaluate(globalns, localns, type_params, recursive_guard=recursive_guard)
  358. if isinstance(t, (_GenericAlias, GenericAlias, types.UnionType)):
  359. if isinstance(t, GenericAlias):
  360. args = tuple(
  361. ForwardRef(arg) if isinstance(arg, str) else arg
  362. for arg in t.__args__
  363. )
  364. is_unpacked = t.__unpacked__
  365. if _should_unflatten_callable_args(t, args):
  366. t = t.__origin__[(args[:-1], args[-1])]
  367. else:
  368. t = t.__origin__[args]
  369. if is_unpacked:
  370. t = Unpack[t]
  371. ev_args = tuple(
  372. _eval_type(
  373. a, globalns, localns, type_params, recursive_guard=recursive_guard
  374. )
  375. for a in t.__args__
  376. )
  377. if ev_args == t.__args__:
  378. return t
  379. if isinstance(t, GenericAlias):
  380. return GenericAlias(t.__origin__, ev_args)
  381. if isinstance(t, types.UnionType):
  382. return functools.reduce(operator.or_, ev_args)
  383. else:
  384. return t.copy_with(ev_args)
  385. return t
  386. class _Final:
  387. """Mixin to prohibit subclassing."""
  388. __slots__ = ('__weakref__',)
  389. def __init_subclass__(cls, /, *args, **kwds):
  390. if '_root' not in kwds:
  391. raise TypeError("Cannot subclass special typing classes")
  392. class _NotIterable:
  393. """Mixin to prevent iteration, without being compatible with Iterable.
  394. That is, we could do::
  395. def __iter__(self): raise TypeError()
  396. But this would make users of this mixin duck type-compatible with
  397. collections.abc.Iterable - isinstance(foo, Iterable) would be True.
  398. Luckily, we can instead prevent iteration by setting __iter__ to None, which
  399. is treated specially.
  400. """
  401. __slots__ = ()
  402. __iter__ = None
  403. # Internal indicator of special typing constructs.
  404. # See __doc__ instance attribute for specific docs.
  405. class _SpecialForm(_Final, _NotIterable, _root=True):
  406. __slots__ = ('_name', '__doc__', '_getitem')
  407. def __init__(self, getitem):
  408. self._getitem = getitem
  409. self._name = getitem.__name__
  410. self.__doc__ = getitem.__doc__
  411. def __getattr__(self, item):
  412. if item in {'__name__', '__qualname__'}:
  413. return self._name
  414. raise AttributeError(item)
  415. def __mro_entries__(self, bases):
  416. raise TypeError(f"Cannot subclass {self!r}")
  417. def __repr__(self):
  418. return 'typing.' + self._name
  419. def __reduce__(self):
  420. return self._name
  421. def __call__(self, *args, **kwds):
  422. raise TypeError(f"Cannot instantiate {self!r}")
  423. def __or__(self, other):
  424. return Union[self, other]
  425. def __ror__(self, other):
  426. return Union[other, self]
  427. def __instancecheck__(self, obj):
  428. raise TypeError(f"{self} cannot be used with isinstance()")
  429. def __subclasscheck__(self, cls):
  430. raise TypeError(f"{self} cannot be used with issubclass()")
  431. @_tp_cache
  432. def __getitem__(self, parameters):
  433. return self._getitem(self, parameters)
  434. class _LiteralSpecialForm(_SpecialForm, _root=True):
  435. def __getitem__(self, parameters):
  436. if not isinstance(parameters, tuple):
  437. parameters = (parameters,)
  438. return self._getitem(self, *parameters)
  439. class _AnyMeta(type):
  440. def __instancecheck__(self, obj):
  441. if self is Any:
  442. raise TypeError("typing.Any cannot be used with isinstance()")
  443. return super().__instancecheck__(obj)
  444. def __repr__(self):
  445. if self is Any:
  446. return "typing.Any"
  447. return super().__repr__() # respect to subclasses
  448. class Any(metaclass=_AnyMeta):
  449. """Special type indicating an unconstrained type.
  450. - Any is compatible with every type.
  451. - Any assumed to have all methods.
  452. - All values assumed to be instances of Any.
  453. Note that all the above statements are true from the point of view of
  454. static type checkers. At runtime, Any should not be used with instance
  455. checks.
  456. """
  457. def __new__(cls, *args, **kwargs):
  458. if cls is Any:
  459. raise TypeError("Any cannot be instantiated")
  460. return super().__new__(cls)
  461. @_SpecialForm
  462. def NoReturn(self, parameters):
  463. """Special type indicating functions that never return.
  464. Example::
  465. from typing import NoReturn
  466. def stop() -> NoReturn:
  467. raise Exception('no way')
  468. NoReturn can also be used as a bottom type, a type that
  469. has no values. Starting in Python 3.11, the Never type should
  470. be used for this concept instead. Type checkers should treat the two
  471. equivalently.
  472. """
  473. raise TypeError(f"{self} is not subscriptable")
  474. # This is semantically identical to NoReturn, but it is implemented
  475. # separately so that type checkers can distinguish between the two
  476. # if they want.
  477. @_SpecialForm
  478. def Never(self, parameters):
  479. """The bottom type, a type that has no members.
  480. This can be used to define a function that should never be
  481. called, or a function that never returns::
  482. from typing import Never
  483. def never_call_me(arg: Never) -> None:
  484. pass
  485. def int_or_str(arg: int | str) -> None:
  486. never_call_me(arg) # type checker error
  487. match arg:
  488. case int():
  489. print("It's an int")
  490. case str():
  491. print("It's a str")
  492. case _:
  493. never_call_me(arg) # OK, arg is of type Never
  494. """
  495. raise TypeError(f"{self} is not subscriptable")
  496. @_SpecialForm
  497. def Self(self, parameters):
  498. """Used to spell the type of "self" in classes.
  499. Example::
  500. from typing import Self
  501. class Foo:
  502. def return_self(self) -> Self:
  503. ...
  504. return self
  505. This is especially useful for:
  506. - classmethods that are used as alternative constructors
  507. - annotating an `__enter__` method which returns self
  508. """
  509. raise TypeError(f"{self} is not subscriptable")
  510. @_SpecialForm
  511. def LiteralString(self, parameters):
  512. """Represents an arbitrary literal string.
  513. Example::
  514. from typing import LiteralString
  515. def run_query(sql: LiteralString) -> None:
  516. ...
  517. def caller(arbitrary_string: str, literal_string: LiteralString) -> None:
  518. run_query("SELECT * FROM students") # OK
  519. run_query(literal_string) # OK
  520. run_query("SELECT * FROM " + literal_string) # OK
  521. run_query(arbitrary_string) # type checker error
  522. run_query( # type checker error
  523. f"SELECT * FROM students WHERE name = {arbitrary_string}"
  524. )
  525. Only string literals and other LiteralStrings are compatible
  526. with LiteralString. This provides a tool to help prevent
  527. security issues such as SQL injection.
  528. """
  529. raise TypeError(f"{self} is not subscriptable")
  530. @_SpecialForm
  531. def ClassVar(self, parameters):
  532. """Special type construct to mark class variables.
  533. An annotation wrapped in ClassVar indicates that a given
  534. attribute is intended to be used as a class variable and
  535. should not be set on instances of that class.
  536. Usage::
  537. class Starship:
  538. stats: ClassVar[dict[str, int]] = {} # class variable
  539. damage: int = 10 # instance variable
  540. ClassVar accepts only types and cannot be further subscribed.
  541. Note that ClassVar is not a class itself, and should not
  542. be used with isinstance() or issubclass().
  543. """
  544. item = _type_check(parameters, f'{self} accepts only single type.')
  545. return _GenericAlias(self, (item,))
  546. @_SpecialForm
  547. def Final(self, parameters):
  548. """Special typing construct to indicate final names to type checkers.
  549. A final name cannot be re-assigned or overridden in a subclass.
  550. For example::
  551. MAX_SIZE: Final = 9000
  552. MAX_SIZE += 1 # Error reported by type checker
  553. class Connection:
  554. TIMEOUT: Final[int] = 10
  555. class FastConnector(Connection):
  556. TIMEOUT = 1 # Error reported by type checker
  557. There is no runtime checking of these properties.
  558. """
  559. item = _type_check(parameters, f'{self} accepts only single type.')
  560. return _GenericAlias(self, (item,))
  561. @_SpecialForm
  562. def Union(self, parameters):
  563. """Union type; Union[X, Y] means either X or Y.
  564. On Python 3.10 and higher, the | operator
  565. can also be used to denote unions;
  566. X | Y means the same thing to the type checker as Union[X, Y].
  567. To define a union, use e.g. Union[int, str]. Details:
  568. - The arguments must be types and there must be at least one.
  569. - None as an argument is a special case and is replaced by
  570. type(None).
  571. - Unions of unions are flattened, e.g.::
  572. assert Union[Union[int, str], float] == Union[int, str, float]
  573. - Unions of a single argument vanish, e.g.::
  574. assert Union[int] == int # The constructor actually returns int
  575. - Redundant arguments are skipped, e.g.::
  576. assert Union[int, str, int] == Union[int, str]
  577. - When comparing unions, the argument order is ignored, e.g.::
  578. assert Union[int, str] == Union[str, int]
  579. - You cannot subclass or instantiate a union.
  580. - You can use Optional[X] as a shorthand for Union[X, None].
  581. """
  582. if parameters == ():
  583. raise TypeError("Cannot take a Union of no types.")
  584. if not isinstance(parameters, tuple):
  585. parameters = (parameters,)
  586. msg = "Union[arg, ...]: each arg must be a type."
  587. parameters = tuple(_type_check(p, msg) for p in parameters)
  588. parameters = _remove_dups_flatten(parameters)
  589. if len(parameters) == 1:
  590. return parameters[0]
  591. if len(parameters) == 2 and type(None) in parameters:
  592. return _UnionGenericAlias(self, parameters, name="Optional")
  593. return _UnionGenericAlias(self, parameters)
  594. def _make_union(left, right):
  595. """Used from the C implementation of TypeVar.
  596. TypeVar.__or__ calls this instead of returning types.UnionType
  597. because we want to allow unions between TypeVars and strings
  598. (forward references).
  599. """
  600. return Union[left, right]
  601. @_SpecialForm
  602. def Optional(self, parameters):
  603. """Optional[X] is equivalent to Union[X, None]."""
  604. arg = _type_check(parameters, f"{self} requires a single type.")
  605. return Union[arg, type(None)]
  606. @_LiteralSpecialForm
  607. @_tp_cache(typed=True)
  608. def Literal(self, *parameters):
  609. """Special typing form to define literal types (a.k.a. value types).
  610. This form can be used to indicate to type checkers that the corresponding
  611. variable or function parameter has a value equivalent to the provided
  612. literal (or one of several literals)::
  613. def validate_simple(data: Any) -> Literal[True]: # always returns True
  614. ...
  615. MODE = Literal['r', 'rb', 'w', 'wb']
  616. def open_helper(file: str, mode: MODE) -> str:
  617. ...
  618. open_helper('/some/path', 'r') # Passes type check
  619. open_helper('/other/path', 'typo') # Error in type checker
  620. Literal[...] cannot be subclassed. At runtime, an arbitrary value
  621. is allowed as type argument to Literal[...], but type checkers may
  622. impose restrictions.
  623. """
  624. # There is no '_type_check' call because arguments to Literal[...] are
  625. # values, not types.
  626. parameters = _flatten_literal_params(parameters)
  627. try:
  628. parameters = tuple(p for p, _ in _deduplicate(list(_value_and_type_iter(parameters))))
  629. except TypeError: # unhashable parameters
  630. pass
  631. return _LiteralGenericAlias(self, parameters)
  632. @_SpecialForm
  633. def TypeAlias(self, parameters):
  634. """Special form for marking type aliases.
  635. Use TypeAlias to indicate that an assignment should
  636. be recognized as a proper type alias definition by type
  637. checkers.
  638. For example::
  639. Predicate: TypeAlias = Callable[..., bool]
  640. It's invalid when used anywhere except as in the example above.
  641. """
  642. raise TypeError(f"{self} is not subscriptable")
  643. @_SpecialForm
  644. def Concatenate(self, parameters):
  645. """Special form for annotating higher-order functions.
  646. ``Concatenate`` can be used in conjunction with ``ParamSpec`` and
  647. ``Callable`` to represent a higher-order function which adds, removes or
  648. transforms the parameters of a callable.
  649. For example::
  650. Callable[Concatenate[int, P], int]
  651. See PEP 612 for detailed information.
  652. """
  653. if parameters == ():
  654. raise TypeError("Cannot take a Concatenate of no types.")
  655. if not isinstance(parameters, tuple):
  656. parameters = (parameters,)
  657. if not (parameters[-1] is ... or isinstance(parameters[-1], ParamSpec)):
  658. raise TypeError("The last parameter to Concatenate should be a "
  659. "ParamSpec variable or ellipsis.")
  660. msg = "Concatenate[arg, ...]: each arg must be a type."
  661. parameters = (*(_type_check(p, msg) for p in parameters[:-1]), parameters[-1])
  662. return _ConcatenateGenericAlias(self, parameters)
  663. @_SpecialForm
  664. def TypeGuard(self, parameters):
  665. """Special typing construct for marking user-defined type guard functions.
  666. ``TypeGuard`` can be used to annotate the return type of a user-defined
  667. type guard function. ``TypeGuard`` only accepts a single type argument.
  668. At runtime, functions marked this way should return a boolean.
  669. ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
  670. type checkers to determine a more precise type of an expression within a
  671. program's code flow. Usually type narrowing is done by analyzing
  672. conditional code flow and applying the narrowing to a block of code. The
  673. conditional expression here is sometimes referred to as a "type guard".
  674. Sometimes it would be convenient to use a user-defined boolean function
  675. as a type guard. Such a function should use ``TypeGuard[...]`` as its
  676. return type to alert static type checkers to this intention.
  677. Using ``-> TypeGuard`` tells the static type checker that for a given
  678. function:
  679. 1. The return value is a boolean.
  680. 2. If the return value is ``True``, the type of its argument
  681. is the type inside ``TypeGuard``.
  682. For example::
  683. def is_str_list(val: list[object]) -> TypeGuard[list[str]]:
  684. '''Determines whether all objects in the list are strings'''
  685. return all(isinstance(x, str) for x in val)
  686. def func1(val: list[object]):
  687. if is_str_list(val):
  688. # Type of ``val`` is narrowed to ``list[str]``.
  689. print(" ".join(val))
  690. else:
  691. # Type of ``val`` remains as ``list[object]``.
  692. print("Not a list of strings!")
  693. Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
  694. form of ``TypeA`` (it can even be a wider form) and this may lead to
  695. type-unsafe results. The main reason is to allow for things like
  696. narrowing ``list[object]`` to ``list[str]`` even though the latter is not
  697. a subtype of the former, since ``list`` is invariant. The responsibility of
  698. writing type-safe type guards is left to the user.
  699. ``TypeGuard`` also works with type variables. For more information, see
  700. PEP 647 (User-Defined Type Guards).
  701. """
  702. item = _type_check(parameters, f'{self} accepts only single type.')
  703. return _GenericAlias(self, (item,))
  704. class ForwardRef(_Final, _root=True):
  705. """Internal wrapper to hold a forward reference."""
  706. __slots__ = ('__forward_arg__', '__forward_code__',
  707. '__forward_evaluated__', '__forward_value__',
  708. '__forward_is_argument__', '__forward_is_class__',
  709. '__forward_module__')
  710. def __init__(self, arg, is_argument=True, module=None, *, is_class=False):
  711. if not isinstance(arg, str):
  712. raise TypeError(f"Forward reference must be a string -- got {arg!r}")
  713. # If we do `def f(*args: *Ts)`, then we'll have `arg = '*Ts'`.
  714. # Unfortunately, this isn't a valid expression on its own, so we
  715. # do the unpacking manually.
  716. if arg.startswith('*'):
  717. arg_to_compile = f'({arg},)[0]' # E.g. (*Ts,)[0] or (*tuple[int, int],)[0]
  718. else:
  719. arg_to_compile = arg
  720. try:
  721. code = compile(arg_to_compile, '<string>', 'eval')
  722. except SyntaxError:
  723. raise SyntaxError(f"Forward reference must be an expression -- got {arg!r}")
  724. self.__forward_arg__ = arg
  725. self.__forward_code__ = code
  726. self.__forward_evaluated__ = False
  727. self.__forward_value__ = None
  728. self.__forward_is_argument__ = is_argument
  729. self.__forward_is_class__ = is_class
  730. self.__forward_module__ = module
  731. def _evaluate(self, globalns, localns, type_params=None, *, recursive_guard):
  732. if self.__forward_arg__ in recursive_guard:
  733. return self
  734. if not self.__forward_evaluated__ or localns is not globalns:
  735. if globalns is None and localns is None:
  736. globalns = localns = {}
  737. elif globalns is None:
  738. globalns = localns
  739. elif localns is None:
  740. localns = globalns
  741. if self.__forward_module__ is not None:
  742. globalns = getattr(
  743. sys.modules.get(self.__forward_module__, None), '__dict__', globalns
  744. )
  745. if type_params:
  746. # "Inject" type parameters into the local namespace
  747. # (unless they are shadowed by assignments *in* the local namespace),
  748. # as a way of emulating annotation scopes when calling `eval()`
  749. locals_to_pass = {param.__name__: param for param in type_params} | localns
  750. else:
  751. locals_to_pass = localns
  752. type_ = _type_check(
  753. eval(self.__forward_code__, globalns, locals_to_pass),
  754. "Forward references must evaluate to types.",
  755. is_argument=self.__forward_is_argument__,
  756. allow_special_forms=self.__forward_is_class__,
  757. )
  758. self.__forward_value__ = _eval_type(
  759. type_,
  760. globalns,
  761. localns,
  762. type_params,
  763. recursive_guard=(recursive_guard | {self.__forward_arg__}),
  764. )
  765. self.__forward_evaluated__ = True
  766. return self.__forward_value__
  767. def __eq__(self, other):
  768. if not isinstance(other, ForwardRef):
  769. return NotImplemented
  770. if self.__forward_evaluated__ and other.__forward_evaluated__:
  771. return (self.__forward_arg__ == other.__forward_arg__ and
  772. self.__forward_value__ == other.__forward_value__)
  773. return (self.__forward_arg__ == other.__forward_arg__ and
  774. self.__forward_module__ == other.__forward_module__)
  775. def __hash__(self):
  776. return hash((self.__forward_arg__, self.__forward_module__))
  777. def __or__(self, other):
  778. return Union[self, other]
  779. def __ror__(self, other):
  780. return Union[other, self]
  781. def __repr__(self):
  782. if self.__forward_module__ is None:
  783. module_repr = ''
  784. else:
  785. module_repr = f', module={self.__forward_module__!r}'
  786. return f'ForwardRef({self.__forward_arg__!r}{module_repr})'
  787. def _is_unpacked_typevartuple(x: Any) -> bool:
  788. return ((not isinstance(x, type)) and
  789. getattr(x, '__typing_is_unpacked_typevartuple__', False))
  790. def _is_typevar_like(x: Any) -> bool:
  791. return isinstance(x, (TypeVar, ParamSpec)) or _is_unpacked_typevartuple(x)
  792. class _PickleUsingNameMixin:
  793. """Mixin enabling pickling based on self.__name__."""
  794. def __reduce__(self):
  795. return self.__name__
  796. def _typevar_subst(self, arg):
  797. msg = "Parameters to generic types must be types."
  798. arg = _type_check(arg, msg, is_argument=True)
  799. if ((isinstance(arg, _GenericAlias) and arg.__origin__ is Unpack) or
  800. (isinstance(arg, GenericAlias) and getattr(arg, '__unpacked__', False))):
  801. raise TypeError(f"{arg} is not valid as type argument")
  802. return arg
  803. def _typevartuple_prepare_subst(self, alias, args):
  804. params = alias.__parameters__
  805. typevartuple_index = params.index(self)
  806. for param in params[typevartuple_index + 1:]:
  807. if isinstance(param, TypeVarTuple):
  808. raise TypeError(f"More than one TypeVarTuple parameter in {alias}")
  809. alen = len(args)
  810. plen = len(params)
  811. left = typevartuple_index
  812. right = plen - typevartuple_index - 1
  813. var_tuple_index = None
  814. fillarg = None
  815. for k, arg in enumerate(args):
  816. if not isinstance(arg, type):
  817. subargs = getattr(arg, '__typing_unpacked_tuple_args__', None)
  818. if subargs and len(subargs) == 2 and subargs[-1] is ...:
  819. if var_tuple_index is not None:
  820. raise TypeError("More than one unpacked arbitrary-length tuple argument")
  821. var_tuple_index = k
  822. fillarg = subargs[0]
  823. if var_tuple_index is not None:
  824. left = min(left, var_tuple_index)
  825. right = min(right, alen - var_tuple_index - 1)
  826. elif left + right > alen:
  827. raise TypeError(f"Too few arguments for {alias};"
  828. f" actual {alen}, expected at least {plen-1}")
  829. return (
  830. *args[:left],
  831. *([fillarg]*(typevartuple_index - left)),
  832. tuple(args[left: alen - right]),
  833. *([fillarg]*(plen - right - left - typevartuple_index - 1)),
  834. *args[alen - right:],
  835. )
  836. def _paramspec_subst(self, arg):
  837. if isinstance(arg, (list, tuple)):
  838. arg = tuple(_type_check(a, "Expected a type.") for a in arg)
  839. elif not _is_param_expr(arg):
  840. raise TypeError(f"Expected a list of types, an ellipsis, "
  841. f"ParamSpec, or Concatenate. Got {arg}")
  842. return arg
  843. def _paramspec_prepare_subst(self, alias, args):
  844. params = alias.__parameters__
  845. i = params.index(self)
  846. if i >= len(args):
  847. raise TypeError(f"Too few arguments for {alias}")
  848. # Special case where Z[[int, str, bool]] == Z[int, str, bool] in PEP 612.
  849. if len(params) == 1 and not _is_param_expr(args[0]):
  850. assert i == 0
  851. args = (args,)
  852. # Convert lists to tuples to help other libraries cache the results.
  853. elif isinstance(args[i], list):
  854. args = (*args[:i], tuple(args[i]), *args[i+1:])
  855. return args
  856. @_tp_cache
  857. def _generic_class_getitem(cls, params):
  858. """Parameterizes a generic class.
  859. At least, parameterizing a generic class is the *main* thing this method
  860. does. For example, for some generic class `Foo`, this is called when we
  861. do `Foo[int]` - there, with `cls=Foo` and `params=int`.
  862. However, note that this method is also called when defining generic
  863. classes in the first place with `class Foo(Generic[T]): ...`.
  864. """
  865. if not isinstance(params, tuple):
  866. params = (params,)
  867. params = tuple(_type_convert(p) for p in params)
  868. is_generic_or_protocol = cls in (Generic, Protocol)
  869. if is_generic_or_protocol:
  870. # Generic and Protocol can only be subscripted with unique type variables.
  871. if not params:
  872. raise TypeError(
  873. f"Parameter list to {cls.__qualname__}[...] cannot be empty"
  874. )
  875. if not all(_is_typevar_like(p) for p in params):
  876. raise TypeError(
  877. f"Parameters to {cls.__name__}[...] must all be type variables "
  878. f"or parameter specification variables.")
  879. if len(set(params)) != len(params):
  880. raise TypeError(
  881. f"Parameters to {cls.__name__}[...] must all be unique")
  882. else:
  883. # Subscripting a regular Generic subclass.
  884. for param in cls.__parameters__:
  885. prepare = getattr(param, '__typing_prepare_subst__', None)
  886. if prepare is not None:
  887. params = prepare(cls, params)
  888. _check_generic(cls, params, len(cls.__parameters__))
  889. new_args = []
  890. for param, new_arg in zip(cls.__parameters__, params):
  891. if isinstance(param, TypeVarTuple):
  892. new_args.extend(new_arg)
  893. else:
  894. new_args.append(new_arg)
  895. params = tuple(new_args)
  896. return _GenericAlias(cls, params)
  897. def _generic_init_subclass(cls, *args, **kwargs):
  898. super(Generic, cls).__init_subclass__(*args, **kwargs)
  899. tvars = []
  900. if '__orig_bases__' in cls.__dict__:
  901. error = Generic in cls.__orig_bases__
  902. else:
  903. error = (Generic in cls.__bases__ and
  904. cls.__name__ != 'Protocol' and
  905. type(cls) != _TypedDictMeta)
  906. if error:
  907. raise TypeError("Cannot inherit from plain Generic")
  908. if '__orig_bases__' in cls.__dict__:
  909. tvars = _collect_parameters(cls.__orig_bases__)
  910. # Look for Generic[T1, ..., Tn].
  911. # If found, tvars must be a subset of it.
  912. # If not found, tvars is it.
  913. # Also check for and reject plain Generic,
  914. # and reject multiple Generic[...].
  915. gvars = None
  916. for base in cls.__orig_bases__:
  917. if (isinstance(base, _GenericAlias) and
  918. base.__origin__ is Generic):
  919. if gvars is not None:
  920. raise TypeError(
  921. "Cannot inherit from Generic[...] multiple times.")
  922. gvars = base.__parameters__
  923. if gvars is not None:
  924. tvarset = set(tvars)
  925. gvarset = set(gvars)
  926. if not tvarset <= gvarset:
  927. s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)
  928. s_args = ', '.join(str(g) for g in gvars)
  929. raise TypeError(f"Some type variables ({s_vars}) are"
  930. f" not listed in Generic[{s_args}]")
  931. tvars = gvars
  932. cls.__parameters__ = tuple(tvars)
  933. def _is_dunder(attr):
  934. return attr.startswith('__') and attr.endswith('__')
  935. class _BaseGenericAlias(_Final, _root=True):
  936. """The central part of the internal API.
  937. This represents a generic version of type 'origin' with type arguments 'params'.
  938. There are two kind of these aliases: user defined and special. The special ones
  939. are wrappers around builtin collections and ABCs in collections.abc. These must
  940. have 'name' always set. If 'inst' is False, then the alias can't be instantiated;
  941. this is used by e.g. typing.List and typing.Dict.
  942. """
  943. def __init__(self, origin, *, inst=True, name=None):
  944. self._inst = inst
  945. self._name = name
  946. self.__origin__ = origin
  947. self.__slots__ = None # This is not documented.
  948. def __call__(self, *args, **kwargs):
  949. if not self._inst:
  950. raise TypeError(f"Type {self._name} cannot be instantiated; "
  951. f"use {self.__origin__.__name__}() instead")
  952. result = self.__origin__(*args, **kwargs)
  953. try:
  954. result.__orig_class__ = self
  955. # Some objects raise TypeError (or something even more exotic)
  956. # if you try to set attributes on them; we guard against that here
  957. except Exception:
  958. pass
  959. return result
  960. def __mro_entries__(self, bases):
  961. res = []
  962. if self.__origin__ not in bases:
  963. res.append(self.__origin__)
  964. i = bases.index(self)
  965. for b in bases[i+1:]:
  966. if isinstance(b, _BaseGenericAlias) or issubclass(b, Generic):
  967. break
  968. else:
  969. res.append(Generic)
  970. return tuple(res)
  971. def __getattr__(self, attr):
  972. if attr in {'__name__', '__qualname__'}:
  973. return self._name or self.__origin__.__name__
  974. # We are careful for copy and pickle.
  975. # Also for simplicity we don't relay any dunder names
  976. if '__origin__' in self.__dict__ and not _is_dunder(attr):
  977. return getattr(self.__origin__, attr)
  978. raise AttributeError(attr)
  979. def __setattr__(self, attr, val):
  980. if _is_dunder(attr) or attr in {'_name', '_inst', '_nparams'}:
  981. super().__setattr__(attr, val)
  982. else:
  983. setattr(self.__origin__, attr, val)
  984. def __instancecheck__(self, obj):
  985. return self.__subclasscheck__(type(obj))
  986. def __subclasscheck__(self, cls):
  987. raise TypeError("Subscripted generics cannot be used with"
  988. " class and instance checks")
  989. def __dir__(self):
  990. return list(set(super().__dir__()
  991. + [attr for attr in dir(self.__origin__) if not _is_dunder(attr)]))
  992. # Special typing constructs Union, Optional, Generic, Callable and Tuple
  993. # use three special attributes for internal bookkeeping of generic types:
  994. # * __parameters__ is a tuple of unique free type parameters of a generic
  995. # type, for example, Dict[T, T].__parameters__ == (T,);
  996. # * __origin__ keeps a reference to a type that was subscripted,
  997. # e.g., Union[T, int].__origin__ == Union, or the non-generic version of
  998. # the type.
  999. # * __args__ is a tuple of all arguments used in subscripting,
  1000. # e.g., Dict[T, int].__args__ == (T, int).
  1001. class _GenericAlias(_BaseGenericAlias, _root=True):
  1002. # The type of parameterized generics.
  1003. #
  1004. # That is, for example, `type(List[int])` is `_GenericAlias`.
  1005. #
  1006. # Objects which are instances of this class include:
  1007. # * Parameterized container types, e.g. `Tuple[int]`, `List[int]`.
  1008. # * Note that native container types, e.g. `tuple`, `list`, use
  1009. # `types.GenericAlias` instead.
  1010. # * Parameterized classes:
  1011. # class C[T]: pass
  1012. # # C[int] is a _GenericAlias
  1013. # * `Callable` aliases, generic `Callable` aliases, and
  1014. # parameterized `Callable` aliases:
  1015. # T = TypeVar('T')
  1016. # # _CallableGenericAlias inherits from _GenericAlias.
  1017. # A = Callable[[], None] # _CallableGenericAlias
  1018. # B = Callable[[T], None] # _CallableGenericAlias
  1019. # C = B[int] # _CallableGenericAlias
  1020. # * Parameterized `Final`, `ClassVar` and `TypeGuard`:
  1021. # # All _GenericAlias
  1022. # Final[int]
  1023. # ClassVar[float]
  1024. # TypeVar[bool]
  1025. def __init__(self, origin, args, *, inst=True, name=None):
  1026. super().__init__(origin, inst=inst, name=name)
  1027. if not isinstance(args, tuple):
  1028. args = (args,)
  1029. self.__args__ = tuple(... if a is _TypingEllipsis else
  1030. a for a in args)
  1031. self.__parameters__ = _collect_parameters(args)
  1032. if not name:
  1033. self.__module__ = origin.__module__
  1034. def __eq__(self, other):
  1035. if not isinstance(other, _GenericAlias):
  1036. return NotImplemented
  1037. return (self.__origin__ == other.__origin__
  1038. and self.__args__ == other.__args__)
  1039. def __hash__(self):
  1040. return hash((self.__origin__, self.__args__))
  1041. def __or__(self, right):
  1042. return Union[self, right]
  1043. def __ror__(self, left):
  1044. return Union[left, self]
  1045. @_tp_cache
  1046. def __getitem__(self, args):
  1047. # Parameterizes an already-parameterized object.
  1048. #
  1049. # For example, we arrive here doing something like:
  1050. # T1 = TypeVar('T1')
  1051. # T2 = TypeVar('T2')
  1052. # T3 = TypeVar('T3')
  1053. # class A(Generic[T1]): pass
  1054. # B = A[T2] # B is a _GenericAlias
  1055. # C = B[T3] # Invokes _GenericAlias.__getitem__
  1056. #
  1057. # We also arrive here when parameterizing a generic `Callable` alias:
  1058. # T = TypeVar('T')
  1059. # C = Callable[[T], None]
  1060. # C[int] # Invokes _GenericAlias.__getitem__
  1061. if self.__origin__ in (Generic, Protocol):
  1062. # Can't subscript Generic[...] or Protocol[...].
  1063. raise TypeError(f"Cannot subscript already-subscripted {self}")
  1064. if not self.__parameters__:
  1065. raise TypeError(f"{self} is not a generic class")
  1066. # Preprocess `args`.
  1067. if not isinstance(args, tuple):
  1068. args = (args,)
  1069. args = tuple(_type_convert(p) for p in args)
  1070. args = _unpack_args(args)
  1071. new_args = self._determine_new_args(args)
  1072. r = self.copy_with(new_args)
  1073. return r
  1074. def _determine_new_args(self, args):
  1075. # Determines new __args__ for __getitem__.
  1076. #
  1077. # For example, suppose we had:
  1078. # T1 = TypeVar('T1')
  1079. # T2 = TypeVar('T2')
  1080. # class A(Generic[T1, T2]): pass
  1081. # T3 = TypeVar('T3')
  1082. # B = A[int, T3]
  1083. # C = B[str]
  1084. # `B.__args__` is `(int, T3)`, so `C.__args__` should be `(int, str)`.
  1085. # Unfortunately, this is harder than it looks, because if `T3` is
  1086. # anything more exotic than a plain `TypeVar`, we need to consider
  1087. # edge cases.
  1088. params = self.__parameters__
  1089. # In the example above, this would be {T3: str}
  1090. for param in params:
  1091. prepare = getattr(param, '__typing_prepare_subst__', None)
  1092. if prepare is not None:
  1093. args = prepare(self, args)
  1094. alen = len(args)
  1095. plen = len(params)
  1096. if alen != plen:
  1097. raise TypeError(f"Too {'many' if alen > plen else 'few'} arguments for {self};"
  1098. f" actual {alen}, expected {plen}")
  1099. new_arg_by_param = dict(zip(params, args))
  1100. return tuple(self._make_substitution(self.__args__, new_arg_by_param))
  1101. def _make_substitution(self, args, new_arg_by_param):
  1102. """Create a list of new type arguments."""
  1103. new_args = []
  1104. for old_arg in args:
  1105. if isinstance(old_arg, type):
  1106. new_args.append(old_arg)
  1107. continue
  1108. substfunc = getattr(old_arg, '__typing_subst__', None)
  1109. if substfunc:
  1110. new_arg = substfunc(new_arg_by_param[old_arg])
  1111. else:
  1112. subparams = getattr(old_arg, '__parameters__', ())
  1113. if not subparams:
  1114. new_arg = old_arg
  1115. else:
  1116. subargs = []
  1117. for x in subparams:
  1118. if isinstance(x, TypeVarTuple):
  1119. subargs.extend(new_arg_by_param[x])
  1120. else:
  1121. subargs.append(new_arg_by_param[x])
  1122. new_arg = old_arg[tuple(subargs)]
  1123. if self.__origin__ == collections.abc.Callable and isinstance(new_arg, tuple):
  1124. # Consider the following `Callable`.
  1125. # C = Callable[[int], str]
  1126. # Here, `C.__args__` should be (int, str) - NOT ([int], str).
  1127. # That means that if we had something like...
  1128. # P = ParamSpec('P')
  1129. # T = TypeVar('T')
  1130. # C = Callable[P, T]
  1131. # D = C[[int, str], float]
  1132. # ...we need to be careful; `new_args` should end up as
  1133. # `(int, str, float)` rather than `([int, str], float)`.
  1134. new_args.extend(new_arg)
  1135. elif _is_unpacked_typevartuple(old_arg):
  1136. # Consider the following `_GenericAlias`, `B`:
  1137. # class A(Generic[*Ts]): ...
  1138. # B = A[T, *Ts]
  1139. # If we then do:
  1140. # B[float, int, str]
  1141. # The `new_arg` corresponding to `T` will be `float`, and the
  1142. # `new_arg` corresponding to `*Ts` will be `(int, str)`. We
  1143. # should join all these types together in a flat list
  1144. # `(float, int, str)` - so again, we should `extend`.
  1145. new_args.extend(new_arg)
  1146. elif isinstance(old_arg, tuple):
  1147. # Corner case:
  1148. # P = ParamSpec('P')
  1149. # T = TypeVar('T')
  1150. # class Base(Generic[P]): ...
  1151. # Can be substituted like this:
  1152. # X = Base[[int, T]]
  1153. # In this case, `old_arg` will be a tuple:
  1154. new_args.append(
  1155. tuple(self._make_substitution(old_arg, new_arg_by_param)),
  1156. )
  1157. else:
  1158. new_args.append(new_arg)
  1159. return new_args
  1160. def copy_with(self, args):
  1161. return self.__class__(self.__origin__, args, name=self._name, inst=self._inst)
  1162. def __repr__(self):
  1163. if self._name:
  1164. name = 'typing.' + self._name
  1165. else:
  1166. name = _type_repr(self.__origin__)
  1167. if self.__args__:
  1168. args = ", ".join([_type_repr(a) for a in self.__args__])
  1169. else:
  1170. # To ensure the repr is eval-able.
  1171. args = "()"
  1172. return f'{name}[{args}]'
  1173. def __reduce__(self):
  1174. if self._name:
  1175. origin = globals()[self._name]
  1176. else:
  1177. origin = self.__origin__
  1178. args = tuple(self.__args__)
  1179. if len(args) == 1 and not isinstance(args[0], tuple):
  1180. args, = args
  1181. return operator.getitem, (origin, args)
  1182. def __mro_entries__(self, bases):
  1183. if isinstance(self.__origin__, _SpecialForm):
  1184. raise TypeError(f"Cannot subclass {self!r}")
  1185. if self._name: # generic version of an ABC or built-in class
  1186. return super().__mro_entries__(bases)
  1187. if self.__origin__ is Generic:
  1188. if Protocol in bases:
  1189. return ()
  1190. i = bases.index(self)
  1191. for b in bases[i+1:]:
  1192. if isinstance(b, _BaseGenericAlias) and b is not self:
  1193. return ()
  1194. return (self.__origin__,)
  1195. def __iter__(self):
  1196. yield Unpack[self]
  1197. # _nparams is the number of accepted parameters, e.g. 0 for Hashable,
  1198. # 1 for List and 2 for Dict. It may be -1 if variable number of
  1199. # parameters are accepted (needs custom __getitem__).
  1200. class _SpecialGenericAlias(_NotIterable, _BaseGenericAlias, _root=True):
  1201. def __init__(self, origin, nparams, *, inst=True, name=None):
  1202. if name is None:
  1203. name = origin.__name__
  1204. super().__init__(origin, inst=inst, name=name)
  1205. self._nparams = nparams
  1206. if origin.__module__ == 'builtins':
  1207. self.__doc__ = f'A generic version of {origin.__qualname__}.'
  1208. else:
  1209. self.__doc__ = f'A generic version of {origin.__module__}.{origin.__qualname__}.'
  1210. @_tp_cache
  1211. def __getitem__(self, params):
  1212. if not isinstance(params, tuple):
  1213. params = (params,)
  1214. msg = "Parameters to generic types must be types."
  1215. params = tuple(_type_check(p, msg) for p in params)
  1216. _check_generic(self, params, self._nparams)
  1217. return self.copy_with(params)
  1218. def copy_with(self, params):
  1219. return _GenericAlias(self.__origin__, params,
  1220. name=self._name, inst=self._inst)
  1221. def __repr__(self):
  1222. return 'typing.' + self._name
  1223. def __subclasscheck__(self, cls):
  1224. if isinstance(cls, _SpecialGenericAlias):
  1225. return issubclass(cls.__origin__, self.__origin__)
  1226. if not isinstance(cls, _GenericAlias):
  1227. return issubclass(cls, self.__origin__)
  1228. return super().__subclasscheck__(cls)
  1229. def __reduce__(self):
  1230. return self._name
  1231. def __or__(self, right):
  1232. return Union[self, right]
  1233. def __ror__(self, left):
  1234. return Union[left, self]
  1235. class _DeprecatedGenericAlias(_SpecialGenericAlias, _root=True):
  1236. def __init__(
  1237. self, origin, nparams, *, removal_version, inst=True, name=None
  1238. ):
  1239. super().__init__(origin, nparams, inst=inst, name=name)
  1240. self._removal_version = removal_version
  1241. def __instancecheck__(self, inst):
  1242. import warnings
  1243. warnings._deprecated(
  1244. f"{self.__module__}.{self._name}", remove=self._removal_version
  1245. )
  1246. return super().__instancecheck__(inst)
  1247. class _CallableGenericAlias(_NotIterable, _GenericAlias, _root=True):
  1248. def __repr__(self):
  1249. assert self._name == 'Callable'
  1250. args = self.__args__
  1251. if len(args) == 2 and _is_param_expr(args[0]):
  1252. return super().__repr__()
  1253. return (f'typing.Callable'
  1254. f'[[{", ".join([_type_repr(a) for a in args[:-1]])}], '
  1255. f'{_type_repr(args[-1])}]')
  1256. def __reduce__(self):
  1257. args = self.__args__
  1258. if not (len(args) == 2 and _is_param_expr(args[0])):
  1259. args = list(args[:-1]), args[-1]
  1260. return operator.getitem, (Callable, args)
  1261. class _CallableType(_SpecialGenericAlias, _root=True):
  1262. def copy_with(self, params):
  1263. return _CallableGenericAlias(self.__origin__, params,
  1264. name=self._name, inst=self._inst)
  1265. def __getitem__(self, params):
  1266. if not isinstance(params, tuple) or len(params) != 2:
  1267. raise TypeError("Callable must be used as "
  1268. "Callable[[arg, ...], result].")
  1269. args, result = params
  1270. # This relaxes what args can be on purpose to allow things like
  1271. # PEP 612 ParamSpec. Responsibility for whether a user is using
  1272. # Callable[...] properly is deferred to static type checkers.
  1273. if isinstance(args, list):
  1274. params = (tuple(args), result)
  1275. else:
  1276. params = (args, result)
  1277. return self.__getitem_inner__(params)
  1278. @_tp_cache
  1279. def __getitem_inner__(self, params):
  1280. args, result = params
  1281. msg = "Callable[args, result]: result must be a type."
  1282. result = _type_check(result, msg)
  1283. if args is Ellipsis:
  1284. return self.copy_with((_TypingEllipsis, result))
  1285. if not isinstance(args, tuple):
  1286. args = (args,)
  1287. args = tuple(_type_convert(arg) for arg in args)
  1288. params = args + (result,)
  1289. return self.copy_with(params)
  1290. class _TupleType(_SpecialGenericAlias, _root=True):
  1291. @_tp_cache
  1292. def __getitem__(self, params):
  1293. if not isinstance(params, tuple):
  1294. params = (params,)
  1295. if len(params) >= 2 and params[-1] is ...:
  1296. msg = "Tuple[t, ...]: t must be a type."
  1297. params = tuple(_type_check(p, msg) for p in params[:-1])
  1298. return self.copy_with((*params, _TypingEllipsis))
  1299. msg = "Tuple[t0, t1, ...]: each t must be a type."
  1300. params = tuple(_type_check(p, msg) for p in params)
  1301. return self.copy_with(params)
  1302. class _UnionGenericAlias(_NotIterable, _GenericAlias, _root=True):
  1303. def copy_with(self, params):
  1304. return Union[params]
  1305. def __eq__(self, other):
  1306. if not isinstance(other, (_UnionGenericAlias, types.UnionType)):
  1307. return NotImplemented
  1308. try: # fast path
  1309. return set(self.__args__) == set(other.__args__)
  1310. except TypeError: # not hashable, slow path
  1311. return _compare_args_orderless(self.__args__, other.__args__)
  1312. def __hash__(self):
  1313. return hash(frozenset(self.__args__))
  1314. def __repr__(self):
  1315. args = self.__args__
  1316. if len(args) == 2:
  1317. if args[0] is type(None):
  1318. return f'typing.Optional[{_type_repr(args[1])}]'
  1319. elif args[1] is type(None):
  1320. return f'typing.Optional[{_type_repr(args[0])}]'
  1321. return super().__repr__()
  1322. def __instancecheck__(self, obj):
  1323. return self.__subclasscheck__(type(obj))
  1324. def __subclasscheck__(self, cls):
  1325. for arg in self.__args__:
  1326. if issubclass(cls, arg):
  1327. return True
  1328. def __reduce__(self):
  1329. func, (origin, args) = super().__reduce__()
  1330. return func, (Union, args)
  1331. def _value_and_type_iter(parameters):
  1332. return ((p, type(p)) for p in parameters)
  1333. class _LiteralGenericAlias(_GenericAlias, _root=True):
  1334. def __eq__(self, other):
  1335. if not isinstance(other, _LiteralGenericAlias):
  1336. return NotImplemented
  1337. return set(_value_and_type_iter(self.__args__)) == set(_value_and_type_iter(other.__args__))
  1338. def __hash__(self):
  1339. return hash(frozenset(_value_and_type_iter(self.__args__)))
  1340. class _ConcatenateGenericAlias(_GenericAlias, _root=True):
  1341. def copy_with(self, params):
  1342. if isinstance(params[-1], (list, tuple)):
  1343. return (*params[:-1], *params[-1])
  1344. if isinstance(params[-1], _ConcatenateGenericAlias):
  1345. params = (*params[:-1], *params[-1].__args__)
  1346. return super().copy_with(params)
  1347. @_SpecialForm
  1348. def Unpack(self, parameters):
  1349. """Type unpack operator.
  1350. The type unpack operator takes the child types from some container type,
  1351. such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'.
  1352. For example::
  1353. # For some generic class `Foo`:
  1354. Foo[Unpack[tuple[int, str]]] # Equivalent to Foo[int, str]
  1355. Ts = TypeVarTuple('Ts')
  1356. # Specifies that `Bar` is generic in an arbitrary number of types.
  1357. # (Think of `Ts` as a tuple of an arbitrary number of individual
  1358. # `TypeVar`s, which the `Unpack` is 'pulling out' directly into the
  1359. # `Generic[]`.)
  1360. class Bar(Generic[Unpack[Ts]]): ...
  1361. Bar[int] # Valid
  1362. Bar[int, str] # Also valid
  1363. From Python 3.11, this can also be done using the `*` operator::
  1364. Foo[*tuple[int, str]]
  1365. class Bar(Generic[*Ts]): ...
  1366. And from Python 3.12, it can be done using built-in syntax for generics::
  1367. Foo[*tuple[int, str]]
  1368. class Bar[*Ts]: ...
  1369. The operator can also be used along with a `TypedDict` to annotate
  1370. `**kwargs` in a function signature::
  1371. class Movie(TypedDict):
  1372. name: str
  1373. year: int
  1374. # This function expects two keyword arguments - *name* of type `str` and
  1375. # *year* of type `int`.
  1376. def foo(**kwargs: Unpack[Movie]): ...
  1377. Note that there is only some runtime checking of this operator. Not
  1378. everything the runtime allows may be accepted by static type checkers.
  1379. For more information, see PEPs 646 and 692.
  1380. """
  1381. item = _type_check(parameters, f'{self} accepts only single type.')
  1382. return _UnpackGenericAlias(origin=self, args=(item,))
  1383. class _UnpackGenericAlias(_GenericAlias, _root=True):
  1384. def __repr__(self):
  1385. # `Unpack` only takes one argument, so __args__ should contain only
  1386. # a single item.
  1387. return f'typing.Unpack[{_type_repr(self.__args__[0])}]'
  1388. def __getitem__(self, args):
  1389. if self.__typing_is_unpacked_typevartuple__:
  1390. return args
  1391. return super().__getitem__(args)
  1392. @property
  1393. def __typing_unpacked_tuple_args__(self):
  1394. assert self.__origin__ is Unpack
  1395. assert len(self.__args__) == 1
  1396. arg, = self.__args__
  1397. if isinstance(arg, (_GenericAlias, types.GenericAlias)):
  1398. if arg.__origin__ is not tuple:
  1399. raise TypeError("Unpack[...] must be used with a tuple type")
  1400. return arg.__args__
  1401. return None
  1402. @property
  1403. def __typing_is_unpacked_typevartuple__(self):
  1404. assert self.__origin__ is Unpack
  1405. assert len(self.__args__) == 1
  1406. return isinstance(self.__args__[0], TypeVarTuple)
  1407. class _TypingEllipsis:
  1408. """Internal placeholder for ... (ellipsis)."""
  1409. _TYPING_INTERNALS = frozenset({
  1410. '__parameters__', '__orig_bases__', '__orig_class__',
  1411. '_is_protocol', '_is_runtime_protocol', '__protocol_attrs__',
  1412. '__non_callable_proto_members__', '__type_params__',
  1413. })
  1414. _SPECIAL_NAMES = frozenset({
  1415. '__abstractmethods__', '__annotations__', '__dict__', '__doc__',
  1416. '__init__', '__module__', '__new__', '__slots__',
  1417. '__subclasshook__', '__weakref__', '__class_getitem__'
  1418. })
  1419. # These special attributes will be not collected as protocol members.
  1420. EXCLUDED_ATTRIBUTES = _TYPING_INTERNALS | _SPECIAL_NAMES | {'_MutableMapping__marker'}
  1421. def _get_protocol_attrs(cls):
  1422. """Collect protocol members from a protocol class objects.
  1423. This includes names actually defined in the class dictionary, as well
  1424. as names that appear in annotations. Special names (above) are skipped.
  1425. """
  1426. attrs = set()
  1427. for base in cls.__mro__[:-1]: # without object
  1428. if base.__name__ in {'Protocol', 'Generic'}:
  1429. continue
  1430. annotations = getattr(base, '__annotations__', {})
  1431. for attr in (*base.__dict__, *annotations):
  1432. if not attr.startswith('_abc_') and attr not in EXCLUDED_ATTRIBUTES:
  1433. attrs.add(attr)
  1434. return attrs
  1435. def _no_init_or_replace_init(self, *args, **kwargs):
  1436. cls = type(self)
  1437. if cls._is_protocol:
  1438. raise TypeError('Protocols cannot be instantiated')
  1439. # Already using a custom `__init__`. No need to calculate correct
  1440. # `__init__` to call. This can lead to RecursionError. See bpo-45121.
  1441. if cls.__init__ is not _no_init_or_replace_init:
  1442. return
  1443. # Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`.
  1444. # The first instantiation of the subclass will call `_no_init_or_replace_init` which
  1445. # searches for a proper new `__init__` in the MRO. The new `__init__`
  1446. # replaces the subclass' old `__init__` (ie `_no_init_or_replace_init`). Subsequent
  1447. # instantiation of the protocol subclass will thus use the new
  1448. # `__init__` and no longer call `_no_init_or_replace_init`.
  1449. for base in cls.__mro__:
  1450. init = base.__dict__.get('__init__', _no_init_or_replace_init)
  1451. if init is not _no_init_or_replace_init:
  1452. cls.__init__ = init
  1453. break
  1454. else:
  1455. # should not happen
  1456. cls.__init__ = object.__init__
  1457. cls.__init__(self, *args, **kwargs)
  1458. def _caller(depth=1, default='__main__'):
  1459. try:
  1460. return sys._getframemodulename(depth + 1) or default
  1461. except AttributeError: # For platforms without _getframemodulename()
  1462. pass
  1463. try:
  1464. return sys._getframe(depth + 1).f_globals.get('__name__', default)
  1465. except (AttributeError, ValueError): # For platforms without _getframe()
  1466. pass
  1467. return None
  1468. def _allow_reckless_class_checks(depth=2):
  1469. """Allow instance and class checks for special stdlib modules.
  1470. The abc and functools modules indiscriminately call isinstance() and
  1471. issubclass() on the whole MRO of a user class, which may contain protocols.
  1472. """
  1473. return _caller(depth) in {'abc', 'functools', None}
  1474. _PROTO_ALLOWLIST = {
  1475. 'collections.abc': [
  1476. 'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable',
  1477. 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible', 'Buffer',
  1478. ],
  1479. 'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'],
  1480. }
  1481. @functools.cache
  1482. def _lazy_load_getattr_static():
  1483. # Import getattr_static lazily so as not to slow down the import of typing.py
  1484. # Cache the result so we don't slow down _ProtocolMeta.__instancecheck__ unnecessarily
  1485. from inspect import getattr_static
  1486. return getattr_static
  1487. _cleanups.append(_lazy_load_getattr_static.cache_clear)
  1488. def _pickle_psargs(psargs):
  1489. return ParamSpecArgs, (psargs.__origin__,)
  1490. copyreg.pickle(ParamSpecArgs, _pickle_psargs)
  1491. def _pickle_pskwargs(pskwargs):
  1492. return ParamSpecKwargs, (pskwargs.__origin__,)
  1493. copyreg.pickle(ParamSpecKwargs, _pickle_pskwargs)
  1494. del _pickle_psargs, _pickle_pskwargs
  1495. class _ProtocolMeta(ABCMeta):
  1496. # This metaclass is somewhat unfortunate,
  1497. # but is necessary for several reasons...
  1498. def __new__(mcls, name, bases, namespace, /, **kwargs):
  1499. if name == "Protocol" and bases == (Generic,):
  1500. pass
  1501. elif Protocol in bases:
  1502. for base in bases:
  1503. if not (
  1504. base in {object, Generic}
  1505. or base.__name__ in _PROTO_ALLOWLIST.get(base.__module__, [])
  1506. or (
  1507. issubclass(base, Generic)
  1508. and getattr(base, "_is_protocol", False)
  1509. )
  1510. ):
  1511. raise TypeError(
  1512. f"Protocols can only inherit from other protocols, "
  1513. f"got {base!r}"
  1514. )
  1515. return super().__new__(mcls, name, bases, namespace, **kwargs)
  1516. def __init__(cls, *args, **kwargs):
  1517. super().__init__(*args, **kwargs)
  1518. if getattr(cls, "_is_protocol", False):
  1519. cls.__protocol_attrs__ = _get_protocol_attrs(cls)
  1520. def __subclasscheck__(cls, other):
  1521. if cls is Protocol:
  1522. return type.__subclasscheck__(cls, other)
  1523. if (
  1524. getattr(cls, '_is_protocol', False)
  1525. and not _allow_reckless_class_checks()
  1526. ):
  1527. if not isinstance(other, type):
  1528. # Same error message as for issubclass(1, int).
  1529. raise TypeError('issubclass() arg 1 must be a class')
  1530. if not getattr(cls, '_is_runtime_protocol', False):
  1531. raise TypeError(
  1532. "Instance and class checks can only be used with "
  1533. "@runtime_checkable protocols"
  1534. )
  1535. if (
  1536. # this attribute is set by @runtime_checkable:
  1537. cls.__non_callable_proto_members__
  1538. and cls.__dict__.get("__subclasshook__") is _proto_hook
  1539. ):
  1540. raise TypeError(
  1541. "Protocols with non-method members don't support issubclass()"
  1542. )
  1543. return super().__subclasscheck__(other)
  1544. def __instancecheck__(cls, instance):
  1545. # We need this method for situations where attributes are
  1546. # assigned in __init__.
  1547. if cls is Protocol:
  1548. return type.__instancecheck__(cls, instance)
  1549. if not getattr(cls, "_is_protocol", False):
  1550. # i.e., it's a concrete subclass of a protocol
  1551. return super().__instancecheck__(instance)
  1552. if (
  1553. not getattr(cls, '_is_runtime_protocol', False) and
  1554. not _allow_reckless_class_checks()
  1555. ):
  1556. raise TypeError("Instance and class checks can only be used with"
  1557. " @runtime_checkable protocols")
  1558. if super().__instancecheck__(instance):
  1559. return True
  1560. getattr_static = _lazy_load_getattr_static()
  1561. for attr in cls.__protocol_attrs__:
  1562. try:
  1563. val = getattr_static(instance, attr)
  1564. except AttributeError:
  1565. break
  1566. # this attribute is set by @runtime_checkable:
  1567. if val is None and attr not in cls.__non_callable_proto_members__:
  1568. break
  1569. else:
  1570. return True
  1571. return False
  1572. @classmethod
  1573. def _proto_hook(cls, other):
  1574. if not cls.__dict__.get('_is_protocol', False):
  1575. return NotImplemented
  1576. for attr in cls.__protocol_attrs__:
  1577. for base in other.__mro__:
  1578. # Check if the members appears in the class dictionary...
  1579. if attr in base.__dict__:
  1580. if base.__dict__[attr] is None:
  1581. return NotImplemented
  1582. break
  1583. # ...or in annotations, if it is a sub-protocol.
  1584. annotations = getattr(base, '__annotations__', {})
  1585. if (isinstance(annotations, collections.abc.Mapping) and
  1586. attr in annotations and
  1587. issubclass(other, Generic) and getattr(other, '_is_protocol', False)):
  1588. break
  1589. else:
  1590. return NotImplemented
  1591. return True
  1592. class Protocol(Generic, metaclass=_ProtocolMeta):
  1593. """Base class for protocol classes.
  1594. Protocol classes are defined as::
  1595. class Proto(Protocol):
  1596. def meth(self) -> int:
  1597. ...
  1598. Such classes are primarily used with static type checkers that recognize
  1599. structural subtyping (static duck-typing).
  1600. For example::
  1601. class C:
  1602. def meth(self) -> int:
  1603. return 0
  1604. def func(x: Proto) -> int:
  1605. return x.meth()
  1606. func(C()) # Passes static type check
  1607. See PEP 544 for details. Protocol classes decorated with
  1608. @typing.runtime_checkable act as simple-minded runtime protocols that check
  1609. only the presence of given attributes, ignoring their type signatures.
  1610. Protocol classes can be generic, they are defined as::
  1611. class GenProto[T](Protocol):
  1612. def meth(self) -> T:
  1613. ...
  1614. """
  1615. __slots__ = ()
  1616. _is_protocol = True
  1617. _is_runtime_protocol = False
  1618. def __init_subclass__(cls, *args, **kwargs):
  1619. super().__init_subclass__(*args, **kwargs)
  1620. # Determine if this is a protocol or a concrete subclass.
  1621. if not cls.__dict__.get('_is_protocol', False):
  1622. cls._is_protocol = any(b is Protocol for b in cls.__bases__)
  1623. # Set (or override) the protocol subclass hook.
  1624. if '__subclasshook__' not in cls.__dict__:
  1625. cls.__subclasshook__ = _proto_hook
  1626. # Prohibit instantiation for protocol classes
  1627. if cls._is_protocol and cls.__init__ is Protocol.__init__:
  1628. cls.__init__ = _no_init_or_replace_init
  1629. class _AnnotatedAlias(_NotIterable, _GenericAlias, _root=True):
  1630. """Runtime representation of an annotated type.
  1631. At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
  1632. with extra annotations. The alias behaves like a normal typing alias.
  1633. Instantiating is the same as instantiating the underlying type; binding
  1634. it to types is also the same.
  1635. The metadata itself is stored in a '__metadata__' attribute as a tuple.
  1636. """
  1637. def __init__(self, origin, metadata):
  1638. if isinstance(origin, _AnnotatedAlias):
  1639. metadata = origin.__metadata__ + metadata
  1640. origin = origin.__origin__
  1641. super().__init__(origin, origin, name='Annotated')
  1642. self.__metadata__ = metadata
  1643. def copy_with(self, params):
  1644. assert len(params) == 1
  1645. new_type = params[0]
  1646. return _AnnotatedAlias(new_type, self.__metadata__)
  1647. def __repr__(self):
  1648. return "typing.Annotated[{}, {}]".format(
  1649. _type_repr(self.__origin__),
  1650. ", ".join(repr(a) for a in self.__metadata__)
  1651. )
  1652. def __reduce__(self):
  1653. return operator.getitem, (
  1654. Annotated, (self.__origin__,) + self.__metadata__
  1655. )
  1656. def __eq__(self, other):
  1657. if not isinstance(other, _AnnotatedAlias):
  1658. return NotImplemented
  1659. return (self.__origin__ == other.__origin__
  1660. and self.__metadata__ == other.__metadata__)
  1661. def __hash__(self):
  1662. return hash((self.__origin__, self.__metadata__))
  1663. def __getattr__(self, attr):
  1664. if attr in {'__name__', '__qualname__'}:
  1665. return 'Annotated'
  1666. return super().__getattr__(attr)
  1667. def __mro_entries__(self, bases):
  1668. return (self.__origin__,)
  1669. class Annotated:
  1670. """Add context-specific metadata to a type.
  1671. Example: Annotated[int, runtime_check.Unsigned] indicates to the
  1672. hypothetical runtime_check module that this type is an unsigned int.
  1673. Every other consumer of this type can ignore this metadata and treat
  1674. this type as int.
  1675. The first argument to Annotated must be a valid type.
  1676. Details:
  1677. - It's an error to call `Annotated` with less than two arguments.
  1678. - Access the metadata via the ``__metadata__`` attribute::
  1679. assert Annotated[int, '$'].__metadata__ == ('$',)
  1680. - Nested Annotated types are flattened::
  1681. assert Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
  1682. - Instantiating an annotated type is equivalent to instantiating the
  1683. underlying type::
  1684. assert Annotated[C, Ann1](5) == C(5)
  1685. - Annotated can be used as a generic type alias::
  1686. type Optimized[T] = Annotated[T, runtime.Optimize()]
  1687. # type checker will treat Optimized[int]
  1688. # as equivalent to Annotated[int, runtime.Optimize()]
  1689. type OptimizedList[T] = Annotated[list[T], runtime.Optimize()]
  1690. # type checker will treat OptimizedList[int]
  1691. # as equivalent to Annotated[list[int], runtime.Optimize()]
  1692. - Annotated cannot be used with an unpacked TypeVarTuple::
  1693. type Variadic[*Ts] = Annotated[*Ts, Ann1] # NOT valid
  1694. This would be equivalent to::
  1695. Annotated[T1, T2, T3, ..., Ann1]
  1696. where T1, T2 etc. are TypeVars, which would be invalid, because
  1697. only one type should be passed to Annotated.
  1698. """
  1699. __slots__ = ()
  1700. def __new__(cls, *args, **kwargs):
  1701. raise TypeError("Type Annotated cannot be instantiated.")
  1702. def __class_getitem__(cls, params):
  1703. if not isinstance(params, tuple):
  1704. params = (params,)
  1705. return cls._class_getitem_inner(cls, *params)
  1706. @_tp_cache(typed=True)
  1707. def _class_getitem_inner(cls, *params):
  1708. if len(params) < 2:
  1709. raise TypeError("Annotated[...] should be used "
  1710. "with at least two arguments (a type and an "
  1711. "annotation).")
  1712. if _is_unpacked_typevartuple(params[0]):
  1713. raise TypeError("Annotated[...] should not be used with an "
  1714. "unpacked TypeVarTuple")
  1715. msg = "Annotated[t, ...]: t must be a type."
  1716. origin = _type_check(params[0], msg, allow_special_forms=True)
  1717. metadata = tuple(params[1:])
  1718. return _AnnotatedAlias(origin, metadata)
  1719. def __init_subclass__(cls, *args, **kwargs):
  1720. raise TypeError(
  1721. "Cannot subclass {}.Annotated".format(cls.__module__)
  1722. )
  1723. def runtime_checkable(cls):
  1724. """Mark a protocol class as a runtime protocol.
  1725. Such protocol can be used with isinstance() and issubclass().
  1726. Raise TypeError if applied to a non-protocol class.
  1727. This allows a simple-minded structural check very similar to
  1728. one trick ponies in collections.abc such as Iterable.
  1729. For example::
  1730. @runtime_checkable
  1731. class Closable(Protocol):
  1732. def close(self): ...
  1733. assert isinstance(open('/some/file'), Closable)
  1734. Warning: this will check only the presence of the required methods,
  1735. not their type signatures!
  1736. """
  1737. if not issubclass(cls, Generic) or not getattr(cls, '_is_protocol', False):
  1738. raise TypeError('@runtime_checkable can be only applied to protocol classes,'
  1739. ' got %r' % cls)
  1740. cls._is_runtime_protocol = True
  1741. # PEP 544 prohibits using issubclass()
  1742. # with protocols that have non-method members.
  1743. # See gh-113320 for why we compute this attribute here,
  1744. # rather than in `_ProtocolMeta.__init__`
  1745. cls.__non_callable_proto_members__ = set()
  1746. for attr in cls.__protocol_attrs__:
  1747. try:
  1748. is_callable = callable(getattr(cls, attr, None))
  1749. except Exception as e:
  1750. raise TypeError(
  1751. f"Failed to determine whether protocol member {attr!r} "
  1752. "is a method member"
  1753. ) from e
  1754. else:
  1755. if not is_callable:
  1756. cls.__non_callable_proto_members__.add(attr)
  1757. return cls
  1758. def cast(typ, val):
  1759. """Cast a value to a type.
  1760. This returns the value unchanged. To the type checker this
  1761. signals that the return value has the designated type, but at
  1762. runtime we intentionally don't check anything (we want this
  1763. to be as fast as possible).
  1764. """
  1765. return val
  1766. def assert_type(val, typ, /):
  1767. """Ask a static type checker to confirm that the value is of the given type.
  1768. At runtime this does nothing: it returns the first argument unchanged with no
  1769. checks or side effects, no matter the actual type of the argument.
  1770. When a static type checker encounters a call to assert_type(), it
  1771. emits an error if the value is not of the specified type::
  1772. def greet(name: str) -> None:
  1773. assert_type(name, str) # OK
  1774. assert_type(name, int) # type checker error
  1775. """
  1776. return val
  1777. _allowed_types = (types.FunctionType, types.BuiltinFunctionType,
  1778. types.MethodType, types.ModuleType,
  1779. WrapperDescriptorType, MethodWrapperType, MethodDescriptorType)
  1780. def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
  1781. """Return type hints for an object.
  1782. This is often the same as obj.__annotations__, but it handles
  1783. forward references encoded as string literals and recursively replaces all
  1784. 'Annotated[T, ...]' with 'T' (unless 'include_extras=True').
  1785. The argument may be a module, class, method, or function. The annotations
  1786. are returned as a dictionary. For classes, annotations include also
  1787. inherited members.
  1788. TypeError is raised if the argument is not of a type that can contain
  1789. annotations, and an empty dictionary is returned if no annotations are
  1790. present.
  1791. BEWARE -- the behavior of globalns and localns is counterintuitive
  1792. (unless you are familiar with how eval() and exec() work). The
  1793. search order is locals first, then globals.
  1794. - If no dict arguments are passed, an attempt is made to use the
  1795. globals from obj (or the respective module's globals for classes),
  1796. and these are also used as the locals. If the object does not appear
  1797. to have globals, an empty dictionary is used. For classes, the search
  1798. order is globals first then locals.
  1799. - If one dict argument is passed, it is used for both globals and
  1800. locals.
  1801. - If two dict arguments are passed, they specify globals and
  1802. locals, respectively.
  1803. """
  1804. if getattr(obj, '__no_type_check__', None):
  1805. return {}
  1806. # Classes require a special treatment.
  1807. if isinstance(obj, type):
  1808. hints = {}
  1809. for base in reversed(obj.__mro__):
  1810. if globalns is None:
  1811. base_globals = getattr(sys.modules.get(base.__module__, None), '__dict__', {})
  1812. else:
  1813. base_globals = globalns
  1814. ann = base.__dict__.get('__annotations__', {})
  1815. if isinstance(ann, types.GetSetDescriptorType):
  1816. ann = {}
  1817. base_locals = dict(vars(base)) if localns is None else localns
  1818. if localns is None and globalns is None:
  1819. # This is surprising, but required. Before Python 3.10,
  1820. # get_type_hints only evaluated the globalns of
  1821. # a class. To maintain backwards compatibility, we reverse
  1822. # the globalns and localns order so that eval() looks into
  1823. # *base_globals* first rather than *base_locals*.
  1824. # This only affects ForwardRefs.
  1825. base_globals, base_locals = base_locals, base_globals
  1826. for name, value in ann.items():
  1827. if value is None:
  1828. value = type(None)
  1829. if isinstance(value, str):
  1830. value = ForwardRef(value, is_argument=False, is_class=True)
  1831. value = _eval_type(value, base_globals, base_locals, base.__type_params__)
  1832. hints[name] = value
  1833. return hints if include_extras else {k: _strip_annotations(t) for k, t in hints.items()}
  1834. if globalns is None:
  1835. if isinstance(obj, types.ModuleType):
  1836. globalns = obj.__dict__
  1837. else:
  1838. nsobj = obj
  1839. # Find globalns for the unwrapped object.
  1840. while hasattr(nsobj, '__wrapped__'):
  1841. nsobj = nsobj.__wrapped__
  1842. globalns = getattr(nsobj, '__globals__', {})
  1843. if localns is None:
  1844. localns = globalns
  1845. elif localns is None:
  1846. localns = globalns
  1847. hints = getattr(obj, '__annotations__', None)
  1848. if hints is None:
  1849. # Return empty annotations for something that _could_ have them.
  1850. if isinstance(obj, _allowed_types):
  1851. return {}
  1852. else:
  1853. raise TypeError('{!r} is not a module, class, method, '
  1854. 'or function.'.format(obj))
  1855. hints = dict(hints)
  1856. type_params = getattr(obj, "__type_params__", ())
  1857. for name, value in hints.items():
  1858. if value is None:
  1859. value = type(None)
  1860. if isinstance(value, str):
  1861. # class-level forward refs were handled above, this must be either
  1862. # a module-level annotation or a function argument annotation
  1863. value = ForwardRef(
  1864. value,
  1865. is_argument=not isinstance(obj, types.ModuleType),
  1866. is_class=False,
  1867. )
  1868. hints[name] = _eval_type(value, globalns, localns, type_params)
  1869. return hints if include_extras else {k: _strip_annotations(t) for k, t in hints.items()}
  1870. def _strip_annotations(t):
  1871. """Strip the annotations from a given type."""
  1872. if isinstance(t, _AnnotatedAlias):
  1873. return _strip_annotations(t.__origin__)
  1874. if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired):
  1875. return _strip_annotations(t.__args__[0])
  1876. if isinstance(t, _GenericAlias):
  1877. stripped_args = tuple(_strip_annotations(a) for a in t.__args__)
  1878. if stripped_args == t.__args__:
  1879. return t
  1880. return t.copy_with(stripped_args)
  1881. if isinstance(t, GenericAlias):
  1882. stripped_args = tuple(_strip_annotations(a) for a in t.__args__)
  1883. if stripped_args == t.__args__:
  1884. return t
  1885. return GenericAlias(t.__origin__, stripped_args)
  1886. if isinstance(t, types.UnionType):
  1887. stripped_args = tuple(_strip_annotations(a) for a in t.__args__)
  1888. if stripped_args == t.__args__:
  1889. return t
  1890. return functools.reduce(operator.or_, stripped_args)
  1891. return t
  1892. def get_origin(tp):
  1893. """Get the unsubscripted version of a type.
  1894. This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar,
  1895. Annotated, and others. Return None for unsupported types.
  1896. Examples::
  1897. >>> P = ParamSpec('P')
  1898. >>> assert get_origin(Literal[42]) is Literal
  1899. >>> assert get_origin(int) is None
  1900. >>> assert get_origin(ClassVar[int]) is ClassVar
  1901. >>> assert get_origin(Generic) is Generic
  1902. >>> assert get_origin(Generic[T]) is Generic
  1903. >>> assert get_origin(Union[T, int]) is Union
  1904. >>> assert get_origin(List[Tuple[T, T]][int]) is list
  1905. >>> assert get_origin(P.args) is P
  1906. """
  1907. if isinstance(tp, _AnnotatedAlias):
  1908. return Annotated
  1909. if isinstance(tp, (_BaseGenericAlias, GenericAlias,
  1910. ParamSpecArgs, ParamSpecKwargs)):
  1911. return tp.__origin__
  1912. if tp is Generic:
  1913. return Generic
  1914. if isinstance(tp, types.UnionType):
  1915. return types.UnionType
  1916. return None
  1917. def get_args(tp):
  1918. """Get type arguments with all substitutions performed.
  1919. For unions, basic simplifications used by Union constructor are performed.
  1920. Examples::
  1921. >>> T = TypeVar('T')
  1922. >>> assert get_args(Dict[str, int]) == (str, int)
  1923. >>> assert get_args(int) == ()
  1924. >>> assert get_args(Union[int, Union[T, int], str][int]) == (int, str)
  1925. >>> assert get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
  1926. >>> assert get_args(Callable[[], T][int]) == ([], int)
  1927. """
  1928. if isinstance(tp, _AnnotatedAlias):
  1929. return (tp.__origin__,) + tp.__metadata__
  1930. if isinstance(tp, (_GenericAlias, GenericAlias)):
  1931. res = tp.__args__
  1932. if _should_unflatten_callable_args(tp, res):
  1933. res = (list(res[:-1]), res[-1])
  1934. return res
  1935. if isinstance(tp, types.UnionType):
  1936. return tp.__args__
  1937. return ()
  1938. def is_typeddict(tp):
  1939. """Check if an annotation is a TypedDict class.
  1940. For example::
  1941. >>> from typing import TypedDict
  1942. >>> class Film(TypedDict):
  1943. ... title: str
  1944. ... year: int
  1945. ...
  1946. >>> is_typeddict(Film)
  1947. True
  1948. >>> is_typeddict(dict)
  1949. False
  1950. """
  1951. return isinstance(tp, _TypedDictMeta)
  1952. _ASSERT_NEVER_REPR_MAX_LENGTH = 100
  1953. def assert_never(arg: Never, /) -> Never:
  1954. """Statically assert that a line of code is unreachable.
  1955. Example::
  1956. def int_or_str(arg: int | str) -> None:
  1957. match arg:
  1958. case int():
  1959. print("It's an int")
  1960. case str():
  1961. print("It's a str")
  1962. case _:
  1963. assert_never(arg)
  1964. If a type checker finds that a call to assert_never() is
  1965. reachable, it will emit an error.
  1966. At runtime, this throws an exception when called.
  1967. """
  1968. value = repr(arg)
  1969. if len(value) > _ASSERT_NEVER_REPR_MAX_LENGTH:
  1970. value = value[:_ASSERT_NEVER_REPR_MAX_LENGTH] + '...'
  1971. raise AssertionError(f"Expected code to be unreachable, but got: {value}")
  1972. def no_type_check(arg):
  1973. """Decorator to indicate that annotations are not type hints.
  1974. The argument must be a class or function; if it is a class, it
  1975. applies recursively to all methods and classes defined in that class
  1976. (but not to methods defined in its superclasses or subclasses).
  1977. This mutates the function(s) or class(es) in place.
  1978. """
  1979. if isinstance(arg, type):
  1980. for key in dir(arg):
  1981. obj = getattr(arg, key)
  1982. if (
  1983. not hasattr(obj, '__qualname__')
  1984. or obj.__qualname__ != f'{arg.__qualname__}.{obj.__name__}'
  1985. or getattr(obj, '__module__', None) != arg.__module__
  1986. ):
  1987. # We only modify objects that are defined in this type directly.
  1988. # If classes / methods are nested in multiple layers,
  1989. # we will modify them when processing their direct holders.
  1990. continue
  1991. # Instance, class, and static methods:
  1992. if isinstance(obj, types.FunctionType):
  1993. obj.__no_type_check__ = True
  1994. if isinstance(obj, types.MethodType):
  1995. obj.__func__.__no_type_check__ = True
  1996. # Nested types:
  1997. if isinstance(obj, type):
  1998. no_type_check(obj)
  1999. try:
  2000. arg.__no_type_check__ = True
  2001. except TypeError: # built-in classes
  2002. pass
  2003. return arg
  2004. def no_type_check_decorator(decorator):
  2005. """Decorator to give another decorator the @no_type_check effect.
  2006. This wraps the decorator with something that wraps the decorated
  2007. function in @no_type_check.
  2008. """
  2009. @functools.wraps(decorator)
  2010. def wrapped_decorator(*args, **kwds):
  2011. func = decorator(*args, **kwds)
  2012. func = no_type_check(func)
  2013. return func
  2014. return wrapped_decorator
  2015. def _overload_dummy(*args, **kwds):
  2016. """Helper for @overload to raise when called."""
  2017. raise NotImplementedError(
  2018. "You should not call an overloaded function. "
  2019. "A series of @overload-decorated functions "
  2020. "outside a stub module should always be followed "
  2021. "by an implementation that is not @overload-ed.")
  2022. # {module: {qualname: {firstlineno: func}}}
  2023. _overload_registry = defaultdict(functools.partial(defaultdict, dict))
  2024. def overload(func):
  2025. """Decorator for overloaded functions/methods.
  2026. In a stub file, place two or more stub definitions for the same
  2027. function in a row, each decorated with @overload.
  2028. For example::
  2029. @overload
  2030. def utf8(value: None) -> None: ...
  2031. @overload
  2032. def utf8(value: bytes) -> bytes: ...
  2033. @overload
  2034. def utf8(value: str) -> bytes: ...
  2035. In a non-stub file (i.e. a regular .py file), do the same but
  2036. follow it with an implementation. The implementation should *not*
  2037. be decorated with @overload::
  2038. @overload
  2039. def utf8(value: None) -> None: ...
  2040. @overload
  2041. def utf8(value: bytes) -> bytes: ...
  2042. @overload
  2043. def utf8(value: str) -> bytes: ...
  2044. def utf8(value):
  2045. ... # implementation goes here
  2046. The overloads for a function can be retrieved at runtime using the
  2047. get_overloads() function.
  2048. """
  2049. # classmethod and staticmethod
  2050. f = getattr(func, "__func__", func)
  2051. try:
  2052. _overload_registry[f.__module__][f.__qualname__][f.__code__.co_firstlineno] = func
  2053. except AttributeError:
  2054. # Not a normal function; ignore.
  2055. pass
  2056. return _overload_dummy
  2057. def get_overloads(func):
  2058. """Return all defined overloads for *func* as a sequence."""
  2059. # classmethod and staticmethod
  2060. f = getattr(func, "__func__", func)
  2061. if f.__module__ not in _overload_registry:
  2062. return []
  2063. mod_dict = _overload_registry[f.__module__]
  2064. if f.__qualname__ not in mod_dict:
  2065. return []
  2066. return list(mod_dict[f.__qualname__].values())
  2067. def clear_overloads():
  2068. """Clear all overloads in the registry."""
  2069. _overload_registry.clear()
  2070. def final(f):
  2071. """Decorator to indicate final methods and final classes.
  2072. Use this decorator to indicate to type checkers that the decorated
  2073. method cannot be overridden, and decorated class cannot be subclassed.
  2074. For example::
  2075. class Base:
  2076. @final
  2077. def done(self) -> None:
  2078. ...
  2079. class Sub(Base):
  2080. def done(self) -> None: # Error reported by type checker
  2081. ...
  2082. @final
  2083. class Leaf:
  2084. ...
  2085. class Other(Leaf): # Error reported by type checker
  2086. ...
  2087. There is no runtime checking of these properties. The decorator
  2088. attempts to set the ``__final__`` attribute to ``True`` on the decorated
  2089. object to allow runtime introspection.
  2090. """
  2091. try:
  2092. f.__final__ = True
  2093. except (AttributeError, TypeError):
  2094. # Skip the attribute silently if it is not writable.
  2095. # AttributeError happens if the object has __slots__ or a
  2096. # read-only property, TypeError if it's a builtin class.
  2097. pass
  2098. return f
  2099. # Some unconstrained type variables. These were initially used by the container types.
  2100. # They were never meant for export and are now unused, but we keep them around to
  2101. # avoid breaking compatibility with users who import them.
  2102. T = TypeVar('T') # Any type.
  2103. KT = TypeVar('KT') # Key type.
  2104. VT = TypeVar('VT') # Value type.
  2105. T_co = TypeVar('T_co', covariant=True) # Any type covariant containers.
  2106. V_co = TypeVar('V_co', covariant=True) # Any type covariant containers.
  2107. VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
  2108. T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
  2109. # Internal type variable used for Type[].
  2110. CT_co = TypeVar('CT_co', covariant=True, bound=type)
  2111. # A useful type variable with constraints. This represents string types.
  2112. # (This one *is* for export!)
  2113. AnyStr = TypeVar('AnyStr', bytes, str)
  2114. # Various ABCs mimicking those in collections.abc.
  2115. _alias = _SpecialGenericAlias
  2116. Hashable = _alias(collections.abc.Hashable, 0) # Not generic.
  2117. Awaitable = _alias(collections.abc.Awaitable, 1)
  2118. Coroutine = _alias(collections.abc.Coroutine, 3)
  2119. AsyncIterable = _alias(collections.abc.AsyncIterable, 1)
  2120. AsyncIterator = _alias(collections.abc.AsyncIterator, 1)
  2121. Iterable = _alias(collections.abc.Iterable, 1)
  2122. Iterator = _alias(collections.abc.Iterator, 1)
  2123. Reversible = _alias(collections.abc.Reversible, 1)
  2124. Sized = _alias(collections.abc.Sized, 0) # Not generic.
  2125. Container = _alias(collections.abc.Container, 1)
  2126. Collection = _alias(collections.abc.Collection, 1)
  2127. Callable = _CallableType(collections.abc.Callable, 2)
  2128. Callable.__doc__ = \
  2129. """Deprecated alias to collections.abc.Callable.
  2130. Callable[[int], str] signifies a function that takes a single
  2131. parameter of type int and returns a str.
  2132. The subscription syntax must always be used with exactly two
  2133. values: the argument list and the return type.
  2134. The argument list must be a list of types, a ParamSpec,
  2135. Concatenate or ellipsis. The return type must be a single type.
  2136. There is no syntax to indicate optional or keyword arguments;
  2137. such function types are rarely used as callback types.
  2138. """
  2139. AbstractSet = _alias(collections.abc.Set, 1, name='AbstractSet')
  2140. MutableSet = _alias(collections.abc.MutableSet, 1)
  2141. # NOTE: Mapping is only covariant in the value type.
  2142. Mapping = _alias(collections.abc.Mapping, 2)
  2143. MutableMapping = _alias(collections.abc.MutableMapping, 2)
  2144. Sequence = _alias(collections.abc.Sequence, 1)
  2145. MutableSequence = _alias(collections.abc.MutableSequence, 1)
  2146. ByteString = _DeprecatedGenericAlias(
  2147. collections.abc.ByteString, 0, removal_version=(3, 14) # Not generic.
  2148. )
  2149. # Tuple accepts variable number of parameters.
  2150. Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
  2151. Tuple.__doc__ = \
  2152. """Deprecated alias to builtins.tuple.
  2153. Tuple[X, Y] is the cross-product type of X and Y.
  2154. Example: Tuple[T1, T2] is a tuple of two elements corresponding
  2155. to type variables T1 and T2. Tuple[int, float, str] is a tuple
  2156. of an int, a float and a string.
  2157. To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
  2158. """
  2159. List = _alias(list, 1, inst=False, name='List')
  2160. Deque = _alias(collections.deque, 1, name='Deque')
  2161. Set = _alias(set, 1, inst=False, name='Set')
  2162. FrozenSet = _alias(frozenset, 1, inst=False, name='FrozenSet')
  2163. MappingView = _alias(collections.abc.MappingView, 1)
  2164. KeysView = _alias(collections.abc.KeysView, 1)
  2165. ItemsView = _alias(collections.abc.ItemsView, 2)
  2166. ValuesView = _alias(collections.abc.ValuesView, 1)
  2167. ContextManager = _alias(contextlib.AbstractContextManager, 1, name='ContextManager')
  2168. AsyncContextManager = _alias(contextlib.AbstractAsyncContextManager, 1, name='AsyncContextManager')
  2169. Dict = _alias(dict, 2, inst=False, name='Dict')
  2170. DefaultDict = _alias(collections.defaultdict, 2, name='DefaultDict')
  2171. OrderedDict = _alias(collections.OrderedDict, 2)
  2172. Counter = _alias(collections.Counter, 1)
  2173. ChainMap = _alias(collections.ChainMap, 2)
  2174. Generator = _alias(collections.abc.Generator, 3)
  2175. AsyncGenerator = _alias(collections.abc.AsyncGenerator, 2)
  2176. Type = _alias(type, 1, inst=False, name='Type')
  2177. Type.__doc__ = \
  2178. """Deprecated alias to builtins.type.
  2179. builtins.type or typing.Type can be used to annotate class objects.
  2180. For example, suppose we have the following classes::
  2181. class User: ... # Abstract base for User classes
  2182. class BasicUser(User): ...
  2183. class ProUser(User): ...
  2184. class TeamUser(User): ...
  2185. And a function that takes a class argument that's a subclass of
  2186. User and returns an instance of the corresponding class::
  2187. def new_user[U](user_class: Type[U]) -> U:
  2188. user = user_class()
  2189. # (Here we could write the user object to a database)
  2190. return user
  2191. joe = new_user(BasicUser)
  2192. At this point the type checker knows that joe has type BasicUser.
  2193. """
  2194. @runtime_checkable
  2195. class SupportsInt(Protocol):
  2196. """An ABC with one abstract method __int__."""
  2197. __slots__ = ()
  2198. @abstractmethod
  2199. def __int__(self) -> int:
  2200. pass
  2201. @runtime_checkable
  2202. class SupportsFloat(Protocol):
  2203. """An ABC with one abstract method __float__."""
  2204. __slots__ = ()
  2205. @abstractmethod
  2206. def __float__(self) -> float:
  2207. pass
  2208. @runtime_checkable
  2209. class SupportsComplex(Protocol):
  2210. """An ABC with one abstract method __complex__."""
  2211. __slots__ = ()
  2212. @abstractmethod
  2213. def __complex__(self) -> complex:
  2214. pass
  2215. @runtime_checkable
  2216. class SupportsBytes(Protocol):
  2217. """An ABC with one abstract method __bytes__."""
  2218. __slots__ = ()
  2219. @abstractmethod
  2220. def __bytes__(self) -> bytes:
  2221. pass
  2222. @runtime_checkable
  2223. class SupportsIndex(Protocol):
  2224. """An ABC with one abstract method __index__."""
  2225. __slots__ = ()
  2226. @abstractmethod
  2227. def __index__(self) -> int:
  2228. pass
  2229. @runtime_checkable
  2230. class SupportsAbs[T](Protocol):
  2231. """An ABC with one abstract method __abs__ that is covariant in its return type."""
  2232. __slots__ = ()
  2233. @abstractmethod
  2234. def __abs__(self) -> T:
  2235. pass
  2236. @runtime_checkable
  2237. class SupportsRound[T](Protocol):
  2238. """An ABC with one abstract method __round__ that is covariant in its return type."""
  2239. __slots__ = ()
  2240. @abstractmethod
  2241. def __round__(self, ndigits: int = 0) -> T:
  2242. pass
  2243. def _make_nmtuple(name, types, module, defaults = ()):
  2244. fields = [n for n, t in types]
  2245. types = {n: _type_check(t, f"field {n} annotation must be a type")
  2246. for n, t in types}
  2247. nm_tpl = collections.namedtuple(name, fields,
  2248. defaults=defaults, module=module)
  2249. nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = types
  2250. return nm_tpl
  2251. # attributes prohibited to set in NamedTuple class syntax
  2252. _prohibited = frozenset({'__new__', '__init__', '__slots__', '__getnewargs__',
  2253. '_fields', '_field_defaults',
  2254. '_make', '_replace', '_asdict', '_source'})
  2255. _special = frozenset({'__module__', '__name__', '__annotations__'})
  2256. class NamedTupleMeta(type):
  2257. def __new__(cls, typename, bases, ns):
  2258. assert _NamedTuple in bases
  2259. for base in bases:
  2260. if base is not _NamedTuple and base is not Generic:
  2261. raise TypeError(
  2262. 'can only inherit from a NamedTuple type and Generic')
  2263. bases = tuple(tuple if base is _NamedTuple else base for base in bases)
  2264. types = ns.get('__annotations__', {})
  2265. default_names = []
  2266. for field_name in types:
  2267. if field_name in ns:
  2268. default_names.append(field_name)
  2269. elif default_names:
  2270. raise TypeError(f"Non-default namedtuple field {field_name} "
  2271. f"cannot follow default field"
  2272. f"{'s' if len(default_names) > 1 else ''} "
  2273. f"{', '.join(default_names)}")
  2274. nm_tpl = _make_nmtuple(typename, types.items(),
  2275. defaults=[ns[n] for n in default_names],
  2276. module=ns['__module__'])
  2277. nm_tpl.__bases__ = bases
  2278. if Generic in bases:
  2279. class_getitem = _generic_class_getitem
  2280. nm_tpl.__class_getitem__ = classmethod(class_getitem)
  2281. # update from user namespace without overriding special namedtuple attributes
  2282. for key in ns:
  2283. if key in _prohibited:
  2284. raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
  2285. elif key not in _special and key not in nm_tpl._fields:
  2286. setattr(nm_tpl, key, ns[key])
  2287. if Generic in bases:
  2288. nm_tpl.__init_subclass__()
  2289. return nm_tpl
  2290. def NamedTuple(typename, fields=None, /, **kwargs):
  2291. """Typed version of namedtuple.
  2292. Usage::
  2293. class Employee(NamedTuple):
  2294. name: str
  2295. id: int
  2296. This is equivalent to::
  2297. Employee = collections.namedtuple('Employee', ['name', 'id'])
  2298. The resulting class has an extra __annotations__ attribute, giving a
  2299. dict that maps field names to types. (The field names are also in
  2300. the _fields attribute, which is part of the namedtuple API.)
  2301. An alternative equivalent functional syntax is also accepted::
  2302. Employee = NamedTuple('Employee', [('name', str), ('id', int)])
  2303. """
  2304. if fields is None:
  2305. fields = kwargs.items()
  2306. elif kwargs:
  2307. raise TypeError("Either list of fields or keywords"
  2308. " can be provided to NamedTuple, not both")
  2309. nt = _make_nmtuple(typename, fields, module=_caller())
  2310. nt.__orig_bases__ = (NamedTuple,)
  2311. return nt
  2312. _NamedTuple = type.__new__(NamedTupleMeta, 'NamedTuple', (), {})
  2313. def _namedtuple_mro_entries(bases):
  2314. assert NamedTuple in bases
  2315. return (_NamedTuple,)
  2316. NamedTuple.__mro_entries__ = _namedtuple_mro_entries
  2317. class _TypedDictMeta(type):
  2318. def __new__(cls, name, bases, ns, total=True):
  2319. """Create a new typed dict class object.
  2320. This method is called when TypedDict is subclassed,
  2321. or when TypedDict is instantiated. This way
  2322. TypedDict supports all three syntax forms described in its docstring.
  2323. Subclasses and instances of TypedDict return actual dictionaries.
  2324. """
  2325. for base in bases:
  2326. if type(base) is not _TypedDictMeta and base is not Generic:
  2327. raise TypeError('cannot inherit from both a TypedDict type '
  2328. 'and a non-TypedDict base class')
  2329. if any(issubclass(b, Generic) for b in bases):
  2330. generic_base = (Generic,)
  2331. else:
  2332. generic_base = ()
  2333. tp_dict = type.__new__(_TypedDictMeta, name, (*generic_base, dict), ns)
  2334. if not hasattr(tp_dict, '__orig_bases__'):
  2335. tp_dict.__orig_bases__ = bases
  2336. annotations = {}
  2337. own_annotations = ns.get('__annotations__', {})
  2338. msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
  2339. own_annotations = {
  2340. n: _type_check(tp, msg, module=tp_dict.__module__)
  2341. for n, tp in own_annotations.items()
  2342. }
  2343. required_keys = set()
  2344. optional_keys = set()
  2345. for base in bases:
  2346. annotations.update(base.__dict__.get('__annotations__', {}))
  2347. base_required = base.__dict__.get('__required_keys__', set())
  2348. required_keys |= base_required
  2349. optional_keys -= base_required
  2350. base_optional = base.__dict__.get('__optional_keys__', set())
  2351. required_keys -= base_optional
  2352. optional_keys |= base_optional
  2353. annotations.update(own_annotations)
  2354. for annotation_key, annotation_type in own_annotations.items():
  2355. annotation_origin = get_origin(annotation_type)
  2356. if annotation_origin is Annotated:
  2357. annotation_args = get_args(annotation_type)
  2358. if annotation_args:
  2359. annotation_type = annotation_args[0]
  2360. annotation_origin = get_origin(annotation_type)
  2361. if annotation_origin is Required:
  2362. is_required = True
  2363. elif annotation_origin is NotRequired:
  2364. is_required = False
  2365. else:
  2366. is_required = total
  2367. if is_required:
  2368. required_keys.add(annotation_key)
  2369. optional_keys.discard(annotation_key)
  2370. else:
  2371. optional_keys.add(annotation_key)
  2372. required_keys.discard(annotation_key)
  2373. assert required_keys.isdisjoint(optional_keys), (
  2374. f"Required keys overlap with optional keys in {name}:"
  2375. f" {required_keys=}, {optional_keys=}"
  2376. )
  2377. tp_dict.__annotations__ = annotations
  2378. tp_dict.__required_keys__ = frozenset(required_keys)
  2379. tp_dict.__optional_keys__ = frozenset(optional_keys)
  2380. if not hasattr(tp_dict, '__total__'):
  2381. tp_dict.__total__ = total
  2382. return tp_dict
  2383. __call__ = dict # static method
  2384. def __subclasscheck__(cls, other):
  2385. # Typed dicts are only for static structural subtyping.
  2386. raise TypeError('TypedDict does not support instance and class checks')
  2387. __instancecheck__ = __subclasscheck__
  2388. def TypedDict(typename, fields=None, /, *, total=True, **kwargs):
  2389. """A simple typed namespace. At runtime it is equivalent to a plain dict.
  2390. TypedDict creates a dictionary type such that a type checker will expect all
  2391. instances to have a certain set of keys, where each key is
  2392. associated with a value of a consistent type. This expectation
  2393. is not checked at runtime.
  2394. Usage::
  2395. >>> class Point2D(TypedDict):
  2396. ... x: int
  2397. ... y: int
  2398. ... label: str
  2399. ...
  2400. >>> a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
  2401. >>> b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
  2402. >>> Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
  2403. True
  2404. The type info can be accessed via the Point2D.__annotations__ dict, and
  2405. the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
  2406. TypedDict supports an additional equivalent form::
  2407. Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
  2408. By default, all keys must be present in a TypedDict. It is possible
  2409. to override this by specifying totality::
  2410. class Point2D(TypedDict, total=False):
  2411. x: int
  2412. y: int
  2413. This means that a Point2D TypedDict can have any of the keys omitted. A type
  2414. checker is only expected to support a literal False or True as the value of
  2415. the total argument. True is the default, and makes all items defined in the
  2416. class body be required.
  2417. The Required and NotRequired special forms can also be used to mark
  2418. individual keys as being required or not required::
  2419. class Point2D(TypedDict):
  2420. x: int # the "x" key must always be present (Required is the default)
  2421. y: NotRequired[int] # the "y" key can be omitted
  2422. See PEP 655 for more details on Required and NotRequired.
  2423. """
  2424. if fields is None:
  2425. fields = kwargs
  2426. elif kwargs:
  2427. raise TypeError("TypedDict takes either a dict or keyword arguments,"
  2428. " but not both")
  2429. if kwargs:
  2430. warnings.warn(
  2431. "The kwargs-based syntax for TypedDict definitions is deprecated "
  2432. "in Python 3.11, will be removed in Python 3.13, and may not be "
  2433. "understood by third-party type checkers.",
  2434. DeprecationWarning,
  2435. stacklevel=2,
  2436. )
  2437. ns = {'__annotations__': dict(fields)}
  2438. module = _caller()
  2439. if module is not None:
  2440. # Setting correct module is necessary to make typed dict classes pickleable.
  2441. ns['__module__'] = module
  2442. td = _TypedDictMeta(typename, (), ns, total=total)
  2443. td.__orig_bases__ = (TypedDict,)
  2444. return td
  2445. _TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {})
  2446. TypedDict.__mro_entries__ = lambda bases: (_TypedDict,)
  2447. @_SpecialForm
  2448. def Required(self, parameters):
  2449. """Special typing construct to mark a TypedDict key as required.
  2450. This is mainly useful for total=False TypedDicts.
  2451. For example::
  2452. class Movie(TypedDict, total=False):
  2453. title: Required[str]
  2454. year: int
  2455. m = Movie(
  2456. title='The Matrix', # typechecker error if key is omitted
  2457. year=1999,
  2458. )
  2459. There is no runtime checking that a required key is actually provided
  2460. when instantiating a related TypedDict.
  2461. """
  2462. item = _type_check(parameters, f'{self._name} accepts only a single type.')
  2463. return _GenericAlias(self, (item,))
  2464. @_SpecialForm
  2465. def NotRequired(self, parameters):
  2466. """Special typing construct to mark a TypedDict key as potentially missing.
  2467. For example::
  2468. class Movie(TypedDict):
  2469. title: str
  2470. year: NotRequired[int]
  2471. m = Movie(
  2472. title='The Matrix', # typechecker error if key is omitted
  2473. year=1999,
  2474. )
  2475. """
  2476. item = _type_check(parameters, f'{self._name} accepts only a single type.')
  2477. return _GenericAlias(self, (item,))
  2478. class NewType:
  2479. """NewType creates simple unique types with almost zero runtime overhead.
  2480. NewType(name, tp) is considered a subtype of tp
  2481. by static type checkers. At runtime, NewType(name, tp) returns
  2482. a dummy callable that simply returns its argument.
  2483. Usage::
  2484. UserId = NewType('UserId', int)
  2485. def name_by_id(user_id: UserId) -> str:
  2486. ...
  2487. UserId('user') # Fails type check
  2488. name_by_id(42) # Fails type check
  2489. name_by_id(UserId(42)) # OK
  2490. num = UserId(5) + 1 # type: int
  2491. """
  2492. __call__ = _idfunc
  2493. def __init__(self, name, tp):
  2494. self.__qualname__ = name
  2495. if '.' in name:
  2496. name = name.rpartition('.')[-1]
  2497. self.__name__ = name
  2498. self.__supertype__ = tp
  2499. def_mod = _caller()
  2500. if def_mod != 'typing':
  2501. self.__module__ = def_mod
  2502. def __mro_entries__(self, bases):
  2503. # We defined __mro_entries__ to get a better error message
  2504. # if a user attempts to subclass a NewType instance. bpo-46170
  2505. superclass_name = self.__name__
  2506. class Dummy:
  2507. def __init_subclass__(cls):
  2508. subclass_name = cls.__name__
  2509. raise TypeError(
  2510. f"Cannot subclass an instance of NewType. Perhaps you were looking for: "
  2511. f"`{subclass_name} = NewType({subclass_name!r}, {superclass_name})`"
  2512. )
  2513. return (Dummy,)
  2514. def __repr__(self):
  2515. return f'{self.__module__}.{self.__qualname__}'
  2516. def __reduce__(self):
  2517. return self.__qualname__
  2518. def __or__(self, other):
  2519. return Union[self, other]
  2520. def __ror__(self, other):
  2521. return Union[other, self]
  2522. # Python-version-specific alias (Python 2: unicode; Python 3: str)
  2523. Text = str
  2524. # Constant that's True when type checking, but False here.
  2525. TYPE_CHECKING = False
  2526. class IO(Generic[AnyStr]):
  2527. """Generic base class for TextIO and BinaryIO.
  2528. This is an abstract, generic version of the return of open().
  2529. NOTE: This does not distinguish between the different possible
  2530. classes (text vs. binary, read vs. write vs. read/write,
  2531. append-only, unbuffered). The TextIO and BinaryIO subclasses
  2532. below capture the distinctions between text vs. binary, which is
  2533. pervasive in the interface; however we currently do not offer a
  2534. way to track the other distinctions in the type system.
  2535. """
  2536. __slots__ = ()
  2537. @property
  2538. @abstractmethod
  2539. def mode(self) -> str:
  2540. pass
  2541. @property
  2542. @abstractmethod
  2543. def name(self) -> str:
  2544. pass
  2545. @abstractmethod
  2546. def close(self) -> None:
  2547. pass
  2548. @property
  2549. @abstractmethod
  2550. def closed(self) -> bool:
  2551. pass
  2552. @abstractmethod
  2553. def fileno(self) -> int:
  2554. pass
  2555. @abstractmethod
  2556. def flush(self) -> None:
  2557. pass
  2558. @abstractmethod
  2559. def isatty(self) -> bool:
  2560. pass
  2561. @abstractmethod
  2562. def read(self, n: int = -1) -> AnyStr:
  2563. pass
  2564. @abstractmethod
  2565. def readable(self) -> bool:
  2566. pass
  2567. @abstractmethod
  2568. def readline(self, limit: int = -1) -> AnyStr:
  2569. pass
  2570. @abstractmethod
  2571. def readlines(self, hint: int = -1) -> List[AnyStr]:
  2572. pass
  2573. @abstractmethod
  2574. def seek(self, offset: int, whence: int = 0) -> int:
  2575. pass
  2576. @abstractmethod
  2577. def seekable(self) -> bool:
  2578. pass
  2579. @abstractmethod
  2580. def tell(self) -> int:
  2581. pass
  2582. @abstractmethod
  2583. def truncate(self, size: int = None) -> int:
  2584. pass
  2585. @abstractmethod
  2586. def writable(self) -> bool:
  2587. pass
  2588. @abstractmethod
  2589. def write(self, s: AnyStr) -> int:
  2590. pass
  2591. @abstractmethod
  2592. def writelines(self, lines: List[AnyStr]) -> None:
  2593. pass
  2594. @abstractmethod
  2595. def __enter__(self) -> 'IO[AnyStr]':
  2596. pass
  2597. @abstractmethod
  2598. def __exit__(self, type, value, traceback) -> None:
  2599. pass
  2600. class BinaryIO(IO[bytes]):
  2601. """Typed version of the return of open() in binary mode."""
  2602. __slots__ = ()
  2603. @abstractmethod
  2604. def write(self, s: Union[bytes, bytearray]) -> int:
  2605. pass
  2606. @abstractmethod
  2607. def __enter__(self) -> 'BinaryIO':
  2608. pass
  2609. class TextIO(IO[str]):
  2610. """Typed version of the return of open() in text mode."""
  2611. __slots__ = ()
  2612. @property
  2613. @abstractmethod
  2614. def buffer(self) -> BinaryIO:
  2615. pass
  2616. @property
  2617. @abstractmethod
  2618. def encoding(self) -> str:
  2619. pass
  2620. @property
  2621. @abstractmethod
  2622. def errors(self) -> Optional[str]:
  2623. pass
  2624. @property
  2625. @abstractmethod
  2626. def line_buffering(self) -> bool:
  2627. pass
  2628. @property
  2629. @abstractmethod
  2630. def newlines(self) -> Any:
  2631. pass
  2632. @abstractmethod
  2633. def __enter__(self) -> 'TextIO':
  2634. pass
  2635. class _DeprecatedType(type):
  2636. def __getattribute__(cls, name):
  2637. if name not in {"__dict__", "__module__", "__doc__"} and name in cls.__dict__:
  2638. warnings.warn(
  2639. f"{cls.__name__} is deprecated, import directly "
  2640. f"from typing instead. {cls.__name__} will be removed "
  2641. "in Python 3.13.",
  2642. DeprecationWarning,
  2643. stacklevel=2,
  2644. )
  2645. return super().__getattribute__(name)
  2646. class io(metaclass=_DeprecatedType):
  2647. """Wrapper namespace for IO generic classes."""
  2648. __all__ = ['IO', 'TextIO', 'BinaryIO']
  2649. IO = IO
  2650. TextIO = TextIO
  2651. BinaryIO = BinaryIO
  2652. io.__name__ = __name__ + '.io'
  2653. sys.modules[io.__name__] = io
  2654. Pattern = _alias(stdlib_re.Pattern, 1)
  2655. Match = _alias(stdlib_re.Match, 1)
  2656. class re(metaclass=_DeprecatedType):
  2657. """Wrapper namespace for re type aliases."""
  2658. __all__ = ['Pattern', 'Match']
  2659. Pattern = Pattern
  2660. Match = Match
  2661. re.__name__ = __name__ + '.re'
  2662. sys.modules[re.__name__] = re
  2663. def reveal_type[T](obj: T, /) -> T:
  2664. """Ask a static type checker to reveal the inferred type of an expression.
  2665. When a static type checker encounters a call to ``reveal_type()``,
  2666. it will emit the inferred type of the argument::
  2667. x: int = 1
  2668. reveal_type(x)
  2669. Running a static type checker (e.g., mypy) on this example
  2670. will produce output similar to 'Revealed type is "builtins.int"'.
  2671. At runtime, the function prints the runtime type of the
  2672. argument and returns the argument unchanged.
  2673. """
  2674. print(f"Runtime type is {type(obj).__name__!r}", file=sys.stderr)
  2675. return obj
  2676. class _IdentityCallable(Protocol):
  2677. def __call__[T](self, arg: T, /) -> T:
  2678. ...
  2679. def dataclass_transform(
  2680. *,
  2681. eq_default: bool = True,
  2682. order_default: bool = False,
  2683. kw_only_default: bool = False,
  2684. frozen_default: bool = False,
  2685. field_specifiers: tuple[type[Any] | Callable[..., Any], ...] = (),
  2686. **kwargs: Any,
  2687. ) -> _IdentityCallable:
  2688. """Decorator to mark an object as providing dataclass-like behaviour.
  2689. The decorator can be applied to a function, class, or metaclass.
  2690. Example usage with a decorator function::
  2691. @dataclass_transform()
  2692. def create_model[T](cls: type[T]) -> type[T]:
  2693. ...
  2694. return cls
  2695. @create_model
  2696. class CustomerModel:
  2697. id: int
  2698. name: str
  2699. On a base class::
  2700. @dataclass_transform()
  2701. class ModelBase: ...
  2702. class CustomerModel(ModelBase):
  2703. id: int
  2704. name: str
  2705. On a metaclass::
  2706. @dataclass_transform()
  2707. class ModelMeta(type): ...
  2708. class ModelBase(metaclass=ModelMeta): ...
  2709. class CustomerModel(ModelBase):
  2710. id: int
  2711. name: str
  2712. The ``CustomerModel`` classes defined above will
  2713. be treated by type checkers similarly to classes created with
  2714. ``@dataclasses.dataclass``.
  2715. For example, type checkers will assume these classes have
  2716. ``__init__`` methods that accept ``id`` and ``name``.
  2717. The arguments to this decorator can be used to customize this behavior:
  2718. - ``eq_default`` indicates whether the ``eq`` parameter is assumed to be
  2719. ``True`` or ``False`` if it is omitted by the caller.
  2720. - ``order_default`` indicates whether the ``order`` parameter is
  2721. assumed to be True or False if it is omitted by the caller.
  2722. - ``kw_only_default`` indicates whether the ``kw_only`` parameter is
  2723. assumed to be True or False if it is omitted by the caller.
  2724. - ``frozen_default`` indicates whether the ``frozen`` parameter is
  2725. assumed to be True or False if it is omitted by the caller.
  2726. - ``field_specifiers`` specifies a static list of supported classes
  2727. or functions that describe fields, similar to ``dataclasses.field()``.
  2728. - Arbitrary other keyword arguments are accepted in order to allow for
  2729. possible future extensions.
  2730. At runtime, this decorator records its arguments in the
  2731. ``__dataclass_transform__`` attribute on the decorated object.
  2732. It has no other runtime effect.
  2733. See PEP 681 for more details.
  2734. """
  2735. def decorator(cls_or_fn):
  2736. cls_or_fn.__dataclass_transform__ = {
  2737. "eq_default": eq_default,
  2738. "order_default": order_default,
  2739. "kw_only_default": kw_only_default,
  2740. "frozen_default": frozen_default,
  2741. "field_specifiers": field_specifiers,
  2742. "kwargs": kwargs,
  2743. }
  2744. return cls_or_fn
  2745. return decorator
  2746. type _Func = Callable[..., Any]
  2747. def override[F: _Func](method: F, /) -> F:
  2748. """Indicate that a method is intended to override a method in a base class.
  2749. Usage::
  2750. class Base:
  2751. def method(self) -> None:
  2752. pass
  2753. class Child(Base):
  2754. @override
  2755. def method(self) -> None:
  2756. super().method()
  2757. When this decorator is applied to a method, the type checker will
  2758. validate that it overrides a method or attribute with the same name on a
  2759. base class. This helps prevent bugs that may occur when a base class is
  2760. changed without an equivalent change to a child class.
  2761. There is no runtime checking of this property. The decorator attempts to
  2762. set the ``__override__`` attribute to ``True`` on the decorated object to
  2763. allow runtime introspection.
  2764. See PEP 698 for details.
  2765. """
  2766. try:
  2767. method.__override__ = True
  2768. except (AttributeError, TypeError):
  2769. # Skip the attribute silently if it is not writable.
  2770. # AttributeError happens if the object has __slots__ or a
  2771. # read-only property, TypeError if it's a builtin class.
  2772. pass
  2773. return method