typing.py 114 KB

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