typing.py 112 KB

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