typing.py 114 KB

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