typing.py 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257
  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): Any, NoReturn, ClassVar, Union, Optional
  7. * Two classes whose instances can be type arguments in addition to types: ForwardRef and TypeVar
  8. * The core of internal generics API: _GenericAlias and _VariadicGenericAlias, the latter is
  9. currently only used by Tuple and Callable. All subscripted types like X[int], Union[int, str],
  10. etc., are instances of either of these classes.
  11. * The public counterpart of the generics API consists of two classes: Generic and Protocol.
  12. * Public helper functions: get_type_hints, overload, cast, no_type_check,
  13. no_type_check_decorator.
  14. * Generic aliases for collections.abc ABCs and few additional protocols.
  15. * Special types: NewType, NamedTuple, TypedDict.
  16. * Wrapper submodules for re and io related types.
  17. """
  18. from abc import abstractmethod, ABCMeta
  19. import collections
  20. import collections.abc
  21. import contextlib
  22. import functools
  23. import operator
  24. import re as stdlib_re # Avoid confusion with the re we export.
  25. import sys
  26. import types
  27. from types import WrapperDescriptorType, MethodWrapperType, MethodDescriptorType, GenericAlias
  28. # Please keep __all__ alphabetized within each category.
  29. __all__ = [
  30. # Super-special typing primitives.
  31. 'Annotated',
  32. 'Any',
  33. 'Callable',
  34. 'ClassVar',
  35. 'Final',
  36. 'ForwardRef',
  37. 'Generic',
  38. 'Literal',
  39. 'Optional',
  40. 'Protocol',
  41. 'Tuple',
  42. 'Type',
  43. 'TypeVar',
  44. 'Union',
  45. # ABCs (from collections.abc).
  46. 'AbstractSet', # collections.abc.Set.
  47. 'ByteString',
  48. 'Container',
  49. 'ContextManager',
  50. 'Hashable',
  51. 'ItemsView',
  52. 'Iterable',
  53. 'Iterator',
  54. 'KeysView',
  55. 'Mapping',
  56. 'MappingView',
  57. 'MutableMapping',
  58. 'MutableSequence',
  59. 'MutableSet',
  60. 'Sequence',
  61. 'Sized',
  62. 'ValuesView',
  63. 'Awaitable',
  64. 'AsyncIterator',
  65. 'AsyncIterable',
  66. 'Coroutine',
  67. 'Collection',
  68. 'AsyncGenerator',
  69. 'AsyncContextManager',
  70. # Structural checks, a.k.a. protocols.
  71. 'Reversible',
  72. 'SupportsAbs',
  73. 'SupportsBytes',
  74. 'SupportsComplex',
  75. 'SupportsFloat',
  76. 'SupportsIndex',
  77. 'SupportsInt',
  78. 'SupportsRound',
  79. # Concrete collection types.
  80. 'ChainMap',
  81. 'Counter',
  82. 'Deque',
  83. 'Dict',
  84. 'DefaultDict',
  85. 'List',
  86. 'OrderedDict',
  87. 'Set',
  88. 'FrozenSet',
  89. 'NamedTuple', # Not really a type.
  90. 'TypedDict', # Not really a type.
  91. 'Generator',
  92. # Other concrete types.
  93. 'BinaryIO',
  94. 'IO',
  95. 'Match',
  96. 'Pattern',
  97. 'TextIO',
  98. # One-off things.
  99. 'AnyStr',
  100. 'cast',
  101. 'final',
  102. 'get_args',
  103. 'get_origin',
  104. 'get_type_hints',
  105. 'NewType',
  106. 'no_type_check',
  107. 'no_type_check_decorator',
  108. 'NoReturn',
  109. 'overload',
  110. 'runtime_checkable',
  111. 'Text',
  112. 'TYPE_CHECKING',
  113. ]
  114. # The pseudo-submodules 're' and 'io' are part of the public
  115. # namespace, but excluded from __all__ because they might stomp on
  116. # legitimate imports of those modules.
  117. def _type_convert(arg, module=None, *, allow_special_forms=False):
  118. """For converting None to type(None), and strings to ForwardRef."""
  119. if arg is None:
  120. return type(None)
  121. if isinstance(arg, str):
  122. return ForwardRef(arg, module=module, is_class=allow_special_forms)
  123. return arg
  124. def _type_check(arg, msg, is_argument=True, module=None, *, allow_special_forms=False):
  125. """Check that the argument is a type, and return it (internal helper).
  126. As a special case, accept None and return type(None) instead. Also wrap strings
  127. into ForwardRef instances. Consider several corner cases, for example plain
  128. special forms like Union are not valid, while Union[int, str] is OK, etc.
  129. The msg argument is a human-readable error message, e.g::
  130. "Union[arg, ...]: arg should be a type."
  131. We append the repr() of the actual value (truncated to 100 chars).
  132. """
  133. invalid_generic_forms = (Generic, Protocol)
  134. if not allow_special_forms:
  135. invalid_generic_forms += (ClassVar,)
  136. if is_argument:
  137. invalid_generic_forms += (Final,)
  138. arg = _type_convert(arg, module=module, allow_special_forms=allow_special_forms)
  139. if (isinstance(arg, _GenericAlias) and
  140. arg.__origin__ in invalid_generic_forms):
  141. raise TypeError(f"{arg} is not valid as type argument")
  142. if arg in (Any, NoReturn, Final):
  143. return arg
  144. if isinstance(arg, _SpecialForm) or arg in (Generic, Protocol):
  145. raise TypeError(f"Plain {arg} is not valid as type argument")
  146. if isinstance(arg, (type, TypeVar, ForwardRef)):
  147. return arg
  148. if not callable(arg):
  149. raise TypeError(f"{msg} Got {arg!r:.100}.")
  150. return arg
  151. def _type_repr(obj):
  152. """Return the repr() of an object, special-casing types (internal helper).
  153. If obj is a type, we return a shorter version than the default
  154. type.__repr__, based on the module and qualified name, which is
  155. typically enough to uniquely identify a type. For everything
  156. else, we fall back on repr(obj).
  157. """
  158. if isinstance(obj, types.GenericAlias):
  159. return repr(obj)
  160. if isinstance(obj, type):
  161. if obj.__module__ == 'builtins':
  162. return obj.__qualname__
  163. return f'{obj.__module__}.{obj.__qualname__}'
  164. if obj is ...:
  165. return('...')
  166. if isinstance(obj, types.FunctionType):
  167. return obj.__name__
  168. return repr(obj)
  169. def _collect_type_vars(types):
  170. """Collect all type variable contained in types in order of
  171. first appearance (lexicographic order). For example::
  172. _collect_type_vars((T, List[S, T])) == (T, S)
  173. """
  174. tvars = []
  175. for t in types:
  176. if isinstance(t, TypeVar) and t not in tvars:
  177. tvars.append(t)
  178. if isinstance(t, (_GenericAlias, GenericAlias)):
  179. tvars.extend([t for t in t.__parameters__ if t not in tvars])
  180. return tuple(tvars)
  181. def _check_generic(cls, parameters, elen):
  182. """Check correct count for parameters of a generic cls (internal helper).
  183. This gives a nice error message in case of count mismatch.
  184. """
  185. if not elen:
  186. raise TypeError(f"{cls} is not a generic class")
  187. alen = len(parameters)
  188. if alen != elen:
  189. raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};"
  190. f" actual {alen}, expected {elen}")
  191. def _deduplicate(params):
  192. # Weed out strict duplicates, preserving the first of each occurrence.
  193. all_params = set(params)
  194. if len(all_params) < len(params):
  195. new_params = []
  196. for t in params:
  197. if t in all_params:
  198. new_params.append(t)
  199. all_params.remove(t)
  200. params = new_params
  201. assert not all_params, all_params
  202. return params
  203. def _remove_dups_flatten(parameters):
  204. """An internal helper for Union creation and substitution: flatten Unions
  205. among parameters, then remove duplicates.
  206. """
  207. # Flatten out Union[Union[...], ...].
  208. params = []
  209. for p in parameters:
  210. if isinstance(p, _UnionGenericAlias):
  211. params.extend(p.__args__)
  212. elif isinstance(p, tuple) and len(p) > 0 and p[0] is Union:
  213. params.extend(p[1:])
  214. else:
  215. params.append(p)
  216. return tuple(_deduplicate(params))
  217. def _flatten_literal_params(parameters):
  218. """An internal helper for Literal creation: flatten Literals among parameters"""
  219. params = []
  220. for p in parameters:
  221. if isinstance(p, _LiteralGenericAlias):
  222. params.extend(p.__args__)
  223. else:
  224. params.append(p)
  225. return tuple(params)
  226. _cleanups = []
  227. def _tp_cache(func=None, /, *, typed=False):
  228. """Internal wrapper caching __getitem__ of generic types with a fallback to
  229. original function for non-hashable arguments.
  230. """
  231. def decorator(func):
  232. cached = functools.lru_cache(typed=typed)(func)
  233. _cleanups.append(cached.cache_clear)
  234. @functools.wraps(func)
  235. def inner(*args, **kwds):
  236. try:
  237. return cached(*args, **kwds)
  238. except TypeError:
  239. pass # All real errors (not unhashable args) are raised below.
  240. return func(*args, **kwds)
  241. return inner
  242. if func is not None:
  243. return decorator(func)
  244. return decorator
  245. def _eval_type(t, globalns, localns, recursive_guard=frozenset()):
  246. """Evaluate all forward references in the given type t.
  247. For use of globalns and localns see the docstring for get_type_hints().
  248. recursive_guard is used to prevent infinite recursion with a recursive
  249. ForwardRef.
  250. """
  251. if isinstance(t, ForwardRef):
  252. return t._evaluate(globalns, localns, recursive_guard)
  253. if isinstance(t, (_GenericAlias, GenericAlias)):
  254. ev_args = tuple(_eval_type(a, globalns, localns, recursive_guard) for a in t.__args__)
  255. if ev_args == t.__args__:
  256. return t
  257. if isinstance(t, GenericAlias):
  258. return GenericAlias(t.__origin__, ev_args)
  259. else:
  260. return t.copy_with(ev_args)
  261. return t
  262. class _Final:
  263. """Mixin to prohibit subclassing"""
  264. __slots__ = ('__weakref__',)
  265. def __init_subclass__(self, /, *args, **kwds):
  266. if '_root' not in kwds:
  267. raise TypeError("Cannot subclass special typing classes")
  268. class _Immutable:
  269. """Mixin to indicate that object should not be copied."""
  270. __slots__ = ()
  271. def __copy__(self):
  272. return self
  273. def __deepcopy__(self, memo):
  274. return self
  275. # Internal indicator of special typing constructs.
  276. # See __doc__ instance attribute for specific docs.
  277. class _SpecialForm(_Final, _root=True):
  278. __slots__ = ('_name', '__doc__', '_getitem')
  279. def __init__(self, getitem):
  280. self._getitem = getitem
  281. self._name = getitem.__name__
  282. self.__doc__ = getitem.__doc__
  283. def __mro_entries__(self, bases):
  284. raise TypeError(f"Cannot subclass {self!r}")
  285. def __repr__(self):
  286. return 'typing.' + self._name
  287. def __reduce__(self):
  288. return self._name
  289. def __call__(self, *args, **kwds):
  290. raise TypeError(f"Cannot instantiate {self!r}")
  291. def __instancecheck__(self, obj):
  292. raise TypeError(f"{self} cannot be used with isinstance()")
  293. def __subclasscheck__(self, cls):
  294. raise TypeError(f"{self} cannot be used with issubclass()")
  295. @_tp_cache
  296. def __getitem__(self, parameters):
  297. return self._getitem(self, parameters)
  298. class _LiteralSpecialForm(_SpecialForm, _root=True):
  299. def __getitem__(self, parameters):
  300. if not isinstance(parameters, tuple):
  301. parameters = (parameters,)
  302. return self._getitem(self, *parameters)
  303. @_SpecialForm
  304. def Any(self, parameters):
  305. """Special type indicating an unconstrained type.
  306. - Any is compatible with every type.
  307. - Any assumed to have all methods.
  308. - All values assumed to be instances of Any.
  309. Note that all the above statements are true from the point of view of
  310. static type checkers. At runtime, Any should not be used with instance
  311. or class checks.
  312. """
  313. raise TypeError(f"{self} is not subscriptable")
  314. @_SpecialForm
  315. def NoReturn(self, parameters):
  316. """Special type indicating functions that never return.
  317. Example::
  318. from typing import NoReturn
  319. def stop() -> NoReturn:
  320. raise Exception('no way')
  321. This type is invalid in other positions, e.g., ``List[NoReturn]``
  322. will fail in static type checkers.
  323. """
  324. raise TypeError(f"{self} is not subscriptable")
  325. @_SpecialForm
  326. def ClassVar(self, parameters):
  327. """Special type construct to mark class variables.
  328. An annotation wrapped in ClassVar indicates that a given
  329. attribute is intended to be used as a class variable and
  330. should not be set on instances of that class. Usage::
  331. class Starship:
  332. stats: ClassVar[Dict[str, int]] = {} # class variable
  333. damage: int = 10 # instance variable
  334. ClassVar accepts only types and cannot be further subscribed.
  335. Note that ClassVar is not a class itself, and should not
  336. be used with isinstance() or issubclass().
  337. """
  338. item = _type_check(parameters, f'{self} accepts only single type.')
  339. return _GenericAlias(self, (item,))
  340. @_SpecialForm
  341. def Final(self, parameters):
  342. """Special typing construct to indicate final names to type checkers.
  343. A final name cannot be re-assigned or overridden in a subclass.
  344. For example:
  345. MAX_SIZE: Final = 9000
  346. MAX_SIZE += 1 # Error reported by type checker
  347. class Connection:
  348. TIMEOUT: Final[int] = 10
  349. class FastConnector(Connection):
  350. TIMEOUT = 1 # Error reported by type checker
  351. There is no runtime checking of these properties.
  352. """
  353. item = _type_check(parameters, f'{self} accepts only single type.')
  354. return _GenericAlias(self, (item,))
  355. @_SpecialForm
  356. def Union(self, parameters):
  357. """Union type; Union[X, Y] means either X or Y.
  358. To define a union, use e.g. Union[int, str]. Details:
  359. - The arguments must be types and there must be at least one.
  360. - None as an argument is a special case and is replaced by
  361. type(None).
  362. - Unions of unions are flattened, e.g.::
  363. Union[Union[int, str], float] == Union[int, str, float]
  364. - Unions of a single argument vanish, e.g.::
  365. Union[int] == int # The constructor actually returns int
  366. - Redundant arguments are skipped, e.g.::
  367. Union[int, str, int] == Union[int, str]
  368. - When comparing unions, the argument order is ignored, e.g.::
  369. Union[int, str] == Union[str, int]
  370. - You cannot subclass or instantiate a union.
  371. - You can use Optional[X] as a shorthand for Union[X, None].
  372. """
  373. if parameters == ():
  374. raise TypeError("Cannot take a Union of no types.")
  375. if not isinstance(parameters, tuple):
  376. parameters = (parameters,)
  377. msg = "Union[arg, ...]: each arg must be a type."
  378. parameters = tuple(_type_check(p, msg) for p in parameters)
  379. parameters = _remove_dups_flatten(parameters)
  380. if len(parameters) == 1:
  381. return parameters[0]
  382. return _UnionGenericAlias(self, parameters)
  383. @_SpecialForm
  384. def Optional(self, parameters):
  385. """Optional type.
  386. Optional[X] is equivalent to Union[X, None].
  387. """
  388. arg = _type_check(parameters, f"{self} requires a single type.")
  389. return Union[arg, type(None)]
  390. @_LiteralSpecialForm
  391. @_tp_cache(typed=True)
  392. def Literal(self, *parameters):
  393. """Special typing form to define literal types (a.k.a. value types).
  394. This form can be used to indicate to type checkers that the corresponding
  395. variable or function parameter has a value equivalent to the provided
  396. literal (or one of several literals):
  397. def validate_simple(data: Any) -> Literal[True]: # always returns True
  398. ...
  399. MODE = Literal['r', 'rb', 'w', 'wb']
  400. def open_helper(file: str, mode: MODE) -> str:
  401. ...
  402. open_helper('/some/path', 'r') # Passes type check
  403. open_helper('/other/path', 'typo') # Error in type checker
  404. Literal[...] cannot be subclassed. At runtime, an arbitrary value
  405. is allowed as type argument to Literal[...], but type checkers may
  406. impose restrictions.
  407. """
  408. # There is no '_type_check' call because arguments to Literal[...] are
  409. # values, not types.
  410. parameters = _flatten_literal_params(parameters)
  411. try:
  412. parameters = tuple(p for p, _ in _deduplicate(list(_value_and_type_iter(parameters))))
  413. except TypeError: # unhashable parameters
  414. pass
  415. return _LiteralGenericAlias(self, parameters)
  416. class ForwardRef(_Final, _root=True):
  417. """Internal wrapper to hold a forward reference."""
  418. __slots__ = ('__forward_arg__', '__forward_code__',
  419. '__forward_evaluated__', '__forward_value__',
  420. '__forward_is_argument__', '__forward_is_class__',
  421. '__forward_module__')
  422. def __init__(self, arg, is_argument=True, module=None, *, is_class=False):
  423. if not isinstance(arg, str):
  424. raise TypeError(f"Forward reference must be a string -- got {arg!r}")
  425. try:
  426. code = compile(arg, '<string>', 'eval')
  427. except SyntaxError:
  428. raise SyntaxError(f"Forward reference must be an expression -- got {arg!r}")
  429. self.__forward_arg__ = arg
  430. self.__forward_code__ = code
  431. self.__forward_evaluated__ = False
  432. self.__forward_value__ = None
  433. self.__forward_is_argument__ = is_argument
  434. self.__forward_is_class__ = is_class
  435. self.__forward_module__ = module
  436. def _evaluate(self, globalns, localns, recursive_guard):
  437. if self.__forward_arg__ in recursive_guard:
  438. return self
  439. if not self.__forward_evaluated__ or localns is not globalns:
  440. if globalns is None and localns is None:
  441. globalns = localns = {}
  442. elif globalns is None:
  443. globalns = localns
  444. elif localns is None:
  445. localns = globalns
  446. if self.__forward_module__ is not None:
  447. globalns = getattr(
  448. sys.modules.get(self.__forward_module__, None), '__dict__', globalns
  449. )
  450. type_ = _type_check(
  451. eval(self.__forward_code__, globalns, localns),
  452. "Forward references must evaluate to types.",
  453. is_argument=self.__forward_is_argument__,
  454. allow_special_forms=self.__forward_is_class__,
  455. )
  456. self.__forward_value__ = _eval_type(
  457. type_, globalns, localns, recursive_guard | {self.__forward_arg__}
  458. )
  459. self.__forward_evaluated__ = True
  460. return self.__forward_value__
  461. def __eq__(self, other):
  462. if not isinstance(other, ForwardRef):
  463. return NotImplemented
  464. if self.__forward_evaluated__ and other.__forward_evaluated__:
  465. return (self.__forward_arg__ == other.__forward_arg__ and
  466. self.__forward_value__ == other.__forward_value__)
  467. return (self.__forward_arg__ == other.__forward_arg__ and
  468. self.__forward_module__ == other.__forward_module__)
  469. def __hash__(self):
  470. return hash((self.__forward_arg__, self.__forward_module__))
  471. def __repr__(self):
  472. return f'ForwardRef({self.__forward_arg__!r})'
  473. class TypeVar(_Final, _Immutable, _root=True):
  474. """Type variable.
  475. Usage::
  476. T = TypeVar('T') # Can be anything
  477. A = TypeVar('A', str, bytes) # Must be str or bytes
  478. Type variables exist primarily for the benefit of static type
  479. checkers. They serve as the parameters for generic types as well
  480. as for generic function definitions. See class Generic for more
  481. information on generic types. Generic functions work as follows:
  482. def repeat(x: T, n: int) -> List[T]:
  483. '''Return a list containing n references to x.'''
  484. return [x]*n
  485. def longest(x: A, y: A) -> A:
  486. '''Return the longest of two strings.'''
  487. return x if len(x) >= len(y) else y
  488. The latter example's signature is essentially the overloading
  489. of (str, str) -> str and (bytes, bytes) -> bytes. Also note
  490. that if the arguments are instances of some subclass of str,
  491. the return type is still plain str.
  492. At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.
  493. Type variables defined with covariant=True or contravariant=True
  494. can be used to declare covariant or contravariant generic types.
  495. See PEP 484 for more details. By default generic types are invariant
  496. in all type variables.
  497. Type variables can be introspected. e.g.:
  498. T.__name__ == 'T'
  499. T.__constraints__ == ()
  500. T.__covariant__ == False
  501. T.__contravariant__ = False
  502. A.__constraints__ == (str, bytes)
  503. Note that only type variables defined in global scope can be pickled.
  504. """
  505. __slots__ = ('__name__', '__bound__', '__constraints__',
  506. '__covariant__', '__contravariant__', '__dict__')
  507. def __init__(self, name, *constraints, bound=None,
  508. covariant=False, contravariant=False):
  509. self.__name__ = name
  510. if covariant and contravariant:
  511. raise ValueError("Bivariant types are not supported.")
  512. self.__covariant__ = bool(covariant)
  513. self.__contravariant__ = bool(contravariant)
  514. if constraints and bound is not None:
  515. raise TypeError("Constraints cannot be combined with bound=...")
  516. if constraints and len(constraints) == 1:
  517. raise TypeError("A single constraint is not allowed")
  518. msg = "TypeVar(name, constraint, ...): constraints must be types."
  519. self.__constraints__ = tuple(_type_check(t, msg) for t in constraints)
  520. if bound:
  521. self.__bound__ = _type_check(bound, "Bound must be a type.")
  522. else:
  523. self.__bound__ = None
  524. try:
  525. def_mod = sys._getframe(1).f_globals.get('__name__', '__main__') # for pickling
  526. except (AttributeError, ValueError):
  527. def_mod = None
  528. if def_mod != 'typing':
  529. self.__module__ = def_mod
  530. def __repr__(self):
  531. if self.__covariant__:
  532. prefix = '+'
  533. elif self.__contravariant__:
  534. prefix = '-'
  535. else:
  536. prefix = '~'
  537. return prefix + self.__name__
  538. def __reduce__(self):
  539. return self.__name__
  540. def _is_dunder(attr):
  541. return attr.startswith('__') and attr.endswith('__')
  542. class _BaseGenericAlias(_Final, _root=True):
  543. """The central part of internal API.
  544. This represents a generic version of type 'origin' with type arguments 'params'.
  545. There are two kind of these aliases: user defined and special. The special ones
  546. are wrappers around builtin collections and ABCs in collections.abc. These must
  547. have 'name' always set. If 'inst' is False, then the alias can't be instantiated,
  548. this is used by e.g. typing.List and typing.Dict.
  549. """
  550. def __init__(self, origin, *, inst=True, name=None):
  551. self._inst = inst
  552. self._name = name
  553. self.__origin__ = origin
  554. self.__slots__ = None # This is not documented.
  555. def __call__(self, *args, **kwargs):
  556. if not self._inst:
  557. raise TypeError(f"Type {self._name} cannot be instantiated; "
  558. f"use {self.__origin__.__name__}() instead")
  559. result = self.__origin__(*args, **kwargs)
  560. try:
  561. result.__orig_class__ = self
  562. except AttributeError:
  563. pass
  564. return result
  565. def __mro_entries__(self, bases):
  566. res = []
  567. if self.__origin__ not in bases:
  568. res.append(self.__origin__)
  569. i = bases.index(self)
  570. for b in bases[i+1:]:
  571. if isinstance(b, _BaseGenericAlias) or issubclass(b, Generic):
  572. break
  573. else:
  574. res.append(Generic)
  575. return tuple(res)
  576. def __getattr__(self, attr):
  577. # We are careful for copy and pickle.
  578. # Also for simplicity we don't relay any dunder names
  579. if '__origin__' in self.__dict__ and not _is_dunder(attr):
  580. return getattr(self.__origin__, attr)
  581. raise AttributeError(attr)
  582. def __setattr__(self, attr, val):
  583. if _is_dunder(attr) or attr in ('_name', '_inst', '_nparams'):
  584. super().__setattr__(attr, val)
  585. else:
  586. setattr(self.__origin__, attr, val)
  587. def __instancecheck__(self, obj):
  588. return self.__subclasscheck__(type(obj))
  589. def __subclasscheck__(self, cls):
  590. raise TypeError("Subscripted generics cannot be used with"
  591. " class and instance checks")
  592. # Special typing constructs Union, Optional, Generic, Callable and Tuple
  593. # use three special attributes for internal bookkeeping of generic types:
  594. # * __parameters__ is a tuple of unique free type parameters of a generic
  595. # type, for example, Dict[T, T].__parameters__ == (T,);
  596. # * __origin__ keeps a reference to a type that was subscripted,
  597. # e.g., Union[T, int].__origin__ == Union, or the non-generic version of
  598. # the type.
  599. # * __args__ is a tuple of all arguments used in subscripting,
  600. # e.g., Dict[T, int].__args__ == (T, int).
  601. class _GenericAlias(_BaseGenericAlias, _root=True):
  602. def __init__(self, origin, params, *, inst=True, name=None):
  603. super().__init__(origin, inst=inst, name=name)
  604. if not isinstance(params, tuple):
  605. params = (params,)
  606. self.__args__ = tuple(... if a is _TypingEllipsis else
  607. () if a is _TypingEmpty else
  608. a for a in params)
  609. self.__parameters__ = _collect_type_vars(params)
  610. if not name:
  611. self.__module__ = origin.__module__
  612. def __eq__(self, other):
  613. if not isinstance(other, _GenericAlias):
  614. return NotImplemented
  615. return (self.__origin__ == other.__origin__
  616. and self.__args__ == other.__args__)
  617. def __hash__(self):
  618. return hash((self.__origin__, self.__args__))
  619. @_tp_cache
  620. def __getitem__(self, params):
  621. if self.__origin__ in (Generic, Protocol):
  622. # Can't subscript Generic[...] or Protocol[...].
  623. raise TypeError(f"Cannot subscript already-subscripted {self}")
  624. if not isinstance(params, tuple):
  625. params = (params,)
  626. msg = "Parameters to generic types must be types."
  627. params = tuple(_type_check(p, msg) for p in params)
  628. _check_generic(self, params, len(self.__parameters__))
  629. subst = dict(zip(self.__parameters__, params))
  630. new_args = []
  631. for arg in self.__args__:
  632. if isinstance(arg, TypeVar):
  633. arg = subst[arg]
  634. elif isinstance(arg, (_GenericAlias, GenericAlias)):
  635. subparams = arg.__parameters__
  636. if subparams:
  637. subargs = tuple(subst[x] for x in subparams)
  638. arg = arg[subargs]
  639. new_args.append(arg)
  640. return self.copy_with(tuple(new_args))
  641. def copy_with(self, params):
  642. return self.__class__(self.__origin__, params, name=self._name, inst=self._inst)
  643. def __repr__(self):
  644. if self._name:
  645. name = 'typing.' + self._name
  646. else:
  647. name = _type_repr(self.__origin__)
  648. args = ", ".join([_type_repr(a) for a in self.__args__])
  649. return f'{name}[{args}]'
  650. def __reduce__(self):
  651. if self._name:
  652. origin = globals()[self._name]
  653. else:
  654. origin = self.__origin__
  655. args = tuple(self.__args__)
  656. if len(args) == 1 and not isinstance(args[0], tuple):
  657. args, = args
  658. return operator.getitem, (origin, args)
  659. def __mro_entries__(self, bases):
  660. if self._name: # generic version of an ABC or built-in class
  661. return super().__mro_entries__(bases)
  662. if self.__origin__ is Generic:
  663. if Protocol in bases:
  664. return ()
  665. i = bases.index(self)
  666. for b in bases[i+1:]:
  667. if isinstance(b, _BaseGenericAlias) and b is not self:
  668. return ()
  669. return (self.__origin__,)
  670. # _nparams is the number of accepted parameters, e.g. 0 for Hashable,
  671. # 1 for List and 2 for Dict. It may be -1 if variable number of
  672. # parameters are accepted (needs custom __getitem__).
  673. class _SpecialGenericAlias(_BaseGenericAlias, _root=True):
  674. def __init__(self, origin, nparams, *, inst=True, name=None):
  675. if name is None:
  676. name = origin.__name__
  677. super().__init__(origin, inst=inst, name=name)
  678. self._nparams = nparams
  679. if origin.__module__ == 'builtins':
  680. self.__doc__ = f'A generic version of {origin.__qualname__}.'
  681. else:
  682. self.__doc__ = f'A generic version of {origin.__module__}.{origin.__qualname__}.'
  683. @_tp_cache
  684. def __getitem__(self, params):
  685. if not isinstance(params, tuple):
  686. params = (params,)
  687. msg = "Parameters to generic types must be types."
  688. params = tuple(_type_check(p, msg) for p in params)
  689. _check_generic(self, params, self._nparams)
  690. return self.copy_with(params)
  691. def copy_with(self, params):
  692. return _GenericAlias(self.__origin__, params,
  693. name=self._name, inst=self._inst)
  694. def __repr__(self):
  695. return 'typing.' + self._name
  696. def __subclasscheck__(self, cls):
  697. if isinstance(cls, _SpecialGenericAlias):
  698. return issubclass(cls.__origin__, self.__origin__)
  699. if not isinstance(cls, _GenericAlias):
  700. return issubclass(cls, self.__origin__)
  701. return super().__subclasscheck__(cls)
  702. def __reduce__(self):
  703. return self._name
  704. class _CallableGenericAlias(_GenericAlias, _root=True):
  705. def __repr__(self):
  706. assert self._name == 'Callable'
  707. if len(self.__args__) == 2 and self.__args__[0] is Ellipsis:
  708. return super().__repr__()
  709. return (f'typing.Callable'
  710. f'[[{", ".join([_type_repr(a) for a in self.__args__[:-1]])}], '
  711. f'{_type_repr(self.__args__[-1])}]')
  712. def __reduce__(self):
  713. args = self.__args__
  714. if not (len(args) == 2 and args[0] is ...):
  715. args = list(args[:-1]), args[-1]
  716. return operator.getitem, (Callable, args)
  717. class _CallableType(_SpecialGenericAlias, _root=True):
  718. def copy_with(self, params):
  719. return _CallableGenericAlias(self.__origin__, params,
  720. name=self._name, inst=self._inst)
  721. def __getitem__(self, params):
  722. if not isinstance(params, tuple) or len(params) != 2:
  723. raise TypeError("Callable must be used as "
  724. "Callable[[arg, ...], result].")
  725. args, result = params
  726. # This relaxes what args can be on purpose to allow things like
  727. # PEP 612 ParamSpec. Responsibility for whether a user is using
  728. # Callable[...] properly is deferred to static type checkers.
  729. if isinstance(args, list):
  730. params = (tuple(args), result)
  731. else:
  732. params = (args, result)
  733. return self.__getitem_inner__(params)
  734. @_tp_cache
  735. def __getitem_inner__(self, params):
  736. args, result = params
  737. msg = "Callable[args, result]: result must be a type."
  738. result = _type_check(result, msg)
  739. if args is Ellipsis:
  740. return self.copy_with((_TypingEllipsis, result))
  741. if not isinstance(args, tuple):
  742. args = (args,)
  743. args = tuple(_type_convert(arg) for arg in args)
  744. params = args + (result,)
  745. return self.copy_with(params)
  746. class _TupleType(_SpecialGenericAlias, _root=True):
  747. @_tp_cache
  748. def __getitem__(self, params):
  749. if params == ():
  750. return self.copy_with((_TypingEmpty,))
  751. if not isinstance(params, tuple):
  752. params = (params,)
  753. if len(params) == 2 and params[1] is ...:
  754. msg = "Tuple[t, ...]: t must be a type."
  755. p = _type_check(params[0], msg)
  756. return self.copy_with((p, _TypingEllipsis))
  757. msg = "Tuple[t0, t1, ...]: each t must be a type."
  758. params = tuple(_type_check(p, msg) for p in params)
  759. return self.copy_with(params)
  760. class _UnionGenericAlias(_GenericAlias, _root=True):
  761. def copy_with(self, params):
  762. return Union[params]
  763. def __eq__(self, other):
  764. if not isinstance(other, _UnionGenericAlias):
  765. return NotImplemented
  766. return set(self.__args__) == set(other.__args__)
  767. def __hash__(self):
  768. return hash(frozenset(self.__args__))
  769. def __repr__(self):
  770. args = self.__args__
  771. if len(args) == 2:
  772. if args[0] is type(None):
  773. return f'typing.Optional[{_type_repr(args[1])}]'
  774. elif args[1] is type(None):
  775. return f'typing.Optional[{_type_repr(args[0])}]'
  776. return super().__repr__()
  777. def _value_and_type_iter(parameters):
  778. return ((p, type(p)) for p in parameters)
  779. class _LiteralGenericAlias(_GenericAlias, _root=True):
  780. def __eq__(self, other):
  781. if not isinstance(other, _LiteralGenericAlias):
  782. return NotImplemented
  783. return set(_value_and_type_iter(self.__args__)) == set(_value_and_type_iter(other.__args__))
  784. def __hash__(self):
  785. return hash(frozenset(_value_and_type_iter(self.__args__)))
  786. class Generic:
  787. """Abstract base class for generic types.
  788. A generic type is typically declared by inheriting from
  789. this class parameterized with one or more type variables.
  790. For example, a generic mapping type might be defined as::
  791. class Mapping(Generic[KT, VT]):
  792. def __getitem__(self, key: KT) -> VT:
  793. ...
  794. # Etc.
  795. This class can then be used as follows::
  796. def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
  797. try:
  798. return mapping[key]
  799. except KeyError:
  800. return default
  801. """
  802. __slots__ = ()
  803. _is_protocol = False
  804. @_tp_cache
  805. def __class_getitem__(cls, params):
  806. if not isinstance(params, tuple):
  807. params = (params,)
  808. if not params and cls is not Tuple:
  809. raise TypeError(
  810. f"Parameter list to {cls.__qualname__}[...] cannot be empty")
  811. msg = "Parameters to generic types must be types."
  812. params = tuple(_type_check(p, msg) for p in params)
  813. if cls in (Generic, Protocol):
  814. # Generic and Protocol can only be subscripted with unique type variables.
  815. if not all(isinstance(p, TypeVar) for p in params):
  816. raise TypeError(
  817. f"Parameters to {cls.__name__}[...] must all be type variables")
  818. if len(set(params)) != len(params):
  819. raise TypeError(
  820. f"Parameters to {cls.__name__}[...] must all be unique")
  821. else:
  822. # Subscripting a regular Generic subclass.
  823. _check_generic(cls, params, len(cls.__parameters__))
  824. return _GenericAlias(cls, params)
  825. def __init_subclass__(cls, *args, **kwargs):
  826. super().__init_subclass__(*args, **kwargs)
  827. tvars = []
  828. if '__orig_bases__' in cls.__dict__:
  829. error = Generic in cls.__orig_bases__
  830. else:
  831. error = Generic in cls.__bases__ and cls.__name__ != 'Protocol'
  832. if error:
  833. raise TypeError("Cannot inherit from plain Generic")
  834. if '__orig_bases__' in cls.__dict__:
  835. tvars = _collect_type_vars(cls.__orig_bases__)
  836. # Look for Generic[T1, ..., Tn].
  837. # If found, tvars must be a subset of it.
  838. # If not found, tvars is it.
  839. # Also check for and reject plain Generic,
  840. # and reject multiple Generic[...].
  841. gvars = None
  842. for base in cls.__orig_bases__:
  843. if (isinstance(base, _GenericAlias) and
  844. base.__origin__ is Generic):
  845. if gvars is not None:
  846. raise TypeError(
  847. "Cannot inherit from Generic[...] multiple types.")
  848. gvars = base.__parameters__
  849. if gvars is not None:
  850. tvarset = set(tvars)
  851. gvarset = set(gvars)
  852. if not tvarset <= gvarset:
  853. s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)
  854. s_args = ', '.join(str(g) for g in gvars)
  855. raise TypeError(f"Some type variables ({s_vars}) are"
  856. f" not listed in Generic[{s_args}]")
  857. tvars = gvars
  858. cls.__parameters__ = tuple(tvars)
  859. class _TypingEmpty:
  860. """Internal placeholder for () or []. Used by TupleMeta and CallableMeta
  861. to allow empty list/tuple in specific places, without allowing them
  862. to sneak in where prohibited.
  863. """
  864. class _TypingEllipsis:
  865. """Internal placeholder for ... (ellipsis)."""
  866. _TYPING_INTERNALS = ['__parameters__', '__orig_bases__', '__orig_class__',
  867. '_is_protocol', '_is_runtime_protocol']
  868. _SPECIAL_NAMES = ['__abstractmethods__', '__annotations__', '__dict__', '__doc__',
  869. '__init__', '__module__', '__new__', '__slots__',
  870. '__subclasshook__', '__weakref__', '__class_getitem__']
  871. # These special attributes will be not collected as protocol members.
  872. EXCLUDED_ATTRIBUTES = _TYPING_INTERNALS + _SPECIAL_NAMES + ['_MutableMapping__marker']
  873. def _get_protocol_attrs(cls):
  874. """Collect protocol members from a protocol class objects.
  875. This includes names actually defined in the class dictionary, as well
  876. as names that appear in annotations. Special names (above) are skipped.
  877. """
  878. attrs = set()
  879. for base in cls.__mro__[:-1]: # without object
  880. if base.__name__ in ('Protocol', 'Generic'):
  881. continue
  882. annotations = getattr(base, '__annotations__', {})
  883. for attr in list(base.__dict__.keys()) + list(annotations.keys()):
  884. if not attr.startswith('_abc_') and attr not in EXCLUDED_ATTRIBUTES:
  885. attrs.add(attr)
  886. return attrs
  887. def _is_callable_members_only(cls):
  888. # PEP 544 prohibits using issubclass() with protocols that have non-method members.
  889. return all(callable(getattr(cls, attr, None)) for attr in _get_protocol_attrs(cls))
  890. def _no_init_or_replace_init(self, *args, **kwargs):
  891. cls = type(self)
  892. if cls._is_protocol:
  893. raise TypeError('Protocols cannot be instantiated')
  894. # Already using a custom `__init__`. No need to calculate correct
  895. # `__init__` to call. This can lead to RecursionError. See bpo-45121.
  896. if cls.__init__ is not _no_init_or_replace_init:
  897. return
  898. # Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`.
  899. # The first instantiation of the subclass will call `_no_init_or_replace_init` which
  900. # searches for a proper new `__init__` in the MRO. The new `__init__`
  901. # replaces the subclass' old `__init__` (ie `_no_init_or_replace_init`). Subsequent
  902. # instantiation of the protocol subclass will thus use the new
  903. # `__init__` and no longer call `_no_init_or_replace_init`.
  904. for base in cls.__mro__:
  905. init = base.__dict__.get('__init__', _no_init_or_replace_init)
  906. if init is not _no_init_or_replace_init:
  907. cls.__init__ = init
  908. break
  909. else:
  910. # should not happen
  911. cls.__init__ = object.__init__
  912. cls.__init__(self, *args, **kwargs)
  913. def _allow_reckless_class_cheks():
  914. """Allow instance and class checks for special stdlib modules.
  915. The abc and functools modules indiscriminately call isinstance() and
  916. issubclass() on the whole MRO of a user class, which may contain protocols.
  917. """
  918. try:
  919. return sys._getframe(3).f_globals['__name__'] in ['abc', 'functools']
  920. except (AttributeError, ValueError): # For platforms without _getframe().
  921. return True
  922. _PROTO_WHITELIST = {
  923. 'collections.abc': [
  924. 'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable',
  925. 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible',
  926. ],
  927. 'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'],
  928. }
  929. class _ProtocolMeta(ABCMeta):
  930. # This metaclass is really unfortunate and exists only because of
  931. # the lack of __instancehook__.
  932. def __instancecheck__(cls, instance):
  933. # We need this method for situations where attributes are
  934. # assigned in __init__.
  935. if ((not getattr(cls, '_is_protocol', False) or
  936. _is_callable_members_only(cls)) and
  937. issubclass(instance.__class__, cls)):
  938. return True
  939. if cls._is_protocol:
  940. if all(hasattr(instance, attr) and
  941. # All *methods* can be blocked by setting them to None.
  942. (not callable(getattr(cls, attr, None)) or
  943. getattr(instance, attr) is not None)
  944. for attr in _get_protocol_attrs(cls)):
  945. return True
  946. return super().__instancecheck__(instance)
  947. class Protocol(Generic, metaclass=_ProtocolMeta):
  948. """Base class for protocol classes.
  949. Protocol classes are defined as::
  950. class Proto(Protocol):
  951. def meth(self) -> int:
  952. ...
  953. Such classes are primarily used with static type checkers that recognize
  954. structural subtyping (static duck-typing), for example::
  955. class C:
  956. def meth(self) -> int:
  957. return 0
  958. def func(x: Proto) -> int:
  959. return x.meth()
  960. func(C()) # Passes static type check
  961. See PEP 544 for details. Protocol classes decorated with
  962. @typing.runtime_checkable act as simple-minded runtime protocols that check
  963. only the presence of given attributes, ignoring their type signatures.
  964. Protocol classes can be generic, they are defined as::
  965. class GenProto(Protocol[T]):
  966. def meth(self) -> T:
  967. ...
  968. """
  969. __slots__ = ()
  970. _is_protocol = True
  971. _is_runtime_protocol = False
  972. def __init_subclass__(cls, *args, **kwargs):
  973. super().__init_subclass__(*args, **kwargs)
  974. # Determine if this is a protocol or a concrete subclass.
  975. if not cls.__dict__.get('_is_protocol', False):
  976. cls._is_protocol = any(b is Protocol for b in cls.__bases__)
  977. # Set (or override) the protocol subclass hook.
  978. def _proto_hook(other):
  979. if not cls.__dict__.get('_is_protocol', False):
  980. return NotImplemented
  981. # First, perform various sanity checks.
  982. if not getattr(cls, '_is_runtime_protocol', False):
  983. if _allow_reckless_class_cheks():
  984. return NotImplemented
  985. raise TypeError("Instance and class checks can only be used with"
  986. " @runtime_checkable protocols")
  987. if not _is_callable_members_only(cls):
  988. if _allow_reckless_class_cheks():
  989. return NotImplemented
  990. raise TypeError("Protocols with non-method members"
  991. " don't support issubclass()")
  992. if not isinstance(other, type):
  993. # Same error message as for issubclass(1, int).
  994. raise TypeError('issubclass() arg 1 must be a class')
  995. # Second, perform the actual structural compatibility check.
  996. for attr in _get_protocol_attrs(cls):
  997. for base in other.__mro__:
  998. # Check if the members appears in the class dictionary...
  999. if attr in base.__dict__:
  1000. if base.__dict__[attr] is None:
  1001. return NotImplemented
  1002. break
  1003. # ...or in annotations, if it is a sub-protocol.
  1004. annotations = getattr(base, '__annotations__', {})
  1005. if (isinstance(annotations, collections.abc.Mapping) and
  1006. attr in annotations and
  1007. issubclass(other, Generic) and other._is_protocol):
  1008. break
  1009. else:
  1010. return NotImplemented
  1011. return True
  1012. if '__subclasshook__' not in cls.__dict__:
  1013. cls.__subclasshook__ = _proto_hook
  1014. # We have nothing more to do for non-protocols...
  1015. if not cls._is_protocol:
  1016. return
  1017. # ... otherwise check consistency of bases, and prohibit instantiation.
  1018. for base in cls.__bases__:
  1019. if not (base in (object, Generic) or
  1020. base.__module__ in _PROTO_WHITELIST and
  1021. base.__name__ in _PROTO_WHITELIST[base.__module__] or
  1022. issubclass(base, Generic) and base._is_protocol):
  1023. raise TypeError('Protocols can only inherit from other'
  1024. ' protocols, got %r' % base)
  1025. cls.__init__ = _no_init_or_replace_init
  1026. class _AnnotatedAlias(_GenericAlias, _root=True):
  1027. """Runtime representation of an annotated type.
  1028. At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
  1029. with extra annotations. The alias behaves like a normal typing alias,
  1030. instantiating is the same as instantiating the underlying type, binding
  1031. it to types is also the same.
  1032. """
  1033. def __init__(self, origin, metadata):
  1034. if isinstance(origin, _AnnotatedAlias):
  1035. metadata = origin.__metadata__ + metadata
  1036. origin = origin.__origin__
  1037. super().__init__(origin, origin)
  1038. self.__metadata__ = metadata
  1039. def copy_with(self, params):
  1040. assert len(params) == 1
  1041. new_type = params[0]
  1042. return _AnnotatedAlias(new_type, self.__metadata__)
  1043. def __repr__(self):
  1044. return "typing.Annotated[{}, {}]".format(
  1045. _type_repr(self.__origin__),
  1046. ", ".join(repr(a) for a in self.__metadata__)
  1047. )
  1048. def __reduce__(self):
  1049. return operator.getitem, (
  1050. Annotated, (self.__origin__,) + self.__metadata__
  1051. )
  1052. def __eq__(self, other):
  1053. if not isinstance(other, _AnnotatedAlias):
  1054. return NotImplemented
  1055. return (self.__origin__ == other.__origin__
  1056. and self.__metadata__ == other.__metadata__)
  1057. def __hash__(self):
  1058. return hash((self.__origin__, self.__metadata__))
  1059. class Annotated:
  1060. """Add context specific metadata to a type.
  1061. Example: Annotated[int, runtime_check.Unsigned] indicates to the
  1062. hypothetical runtime_check module that this type is an unsigned int.
  1063. Every other consumer of this type can ignore this metadata and treat
  1064. this type as int.
  1065. The first argument to Annotated must be a valid type.
  1066. Details:
  1067. - It's an error to call `Annotated` with less than two arguments.
  1068. - Nested Annotated are flattened::
  1069. Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
  1070. - Instantiating an annotated type is equivalent to instantiating the
  1071. underlying type::
  1072. Annotated[C, Ann1](5) == C(5)
  1073. - Annotated can be used as a generic type alias::
  1074. Optimized = Annotated[T, runtime.Optimize()]
  1075. Optimized[int] == Annotated[int, runtime.Optimize()]
  1076. OptimizedList = Annotated[List[T], runtime.Optimize()]
  1077. OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
  1078. """
  1079. __slots__ = ()
  1080. def __new__(cls, *args, **kwargs):
  1081. raise TypeError("Type Annotated cannot be instantiated.")
  1082. @_tp_cache
  1083. def __class_getitem__(cls, params):
  1084. if not isinstance(params, tuple) or len(params) < 2:
  1085. raise TypeError("Annotated[...] should be used "
  1086. "with at least two arguments (a type and an "
  1087. "annotation).")
  1088. msg = "Annotated[t, ...]: t must be a type."
  1089. origin = _type_check(params[0], msg, allow_special_forms=True)
  1090. metadata = tuple(params[1:])
  1091. return _AnnotatedAlias(origin, metadata)
  1092. def __init_subclass__(cls, *args, **kwargs):
  1093. raise TypeError(
  1094. "Cannot subclass {}.Annotated".format(cls.__module__)
  1095. )
  1096. def runtime_checkable(cls):
  1097. """Mark a protocol class as a runtime protocol.
  1098. Such protocol can be used with isinstance() and issubclass().
  1099. Raise TypeError if applied to a non-protocol class.
  1100. This allows a simple-minded structural check very similar to
  1101. one trick ponies in collections.abc such as Iterable.
  1102. For example::
  1103. @runtime_checkable
  1104. class Closable(Protocol):
  1105. def close(self): ...
  1106. assert isinstance(open('/some/file'), Closable)
  1107. Warning: this will check only the presence of the required methods,
  1108. not their type signatures!
  1109. """
  1110. if not issubclass(cls, Generic) or not cls._is_protocol:
  1111. raise TypeError('@runtime_checkable can be only applied to protocol classes,'
  1112. ' got %r' % cls)
  1113. cls._is_runtime_protocol = True
  1114. return cls
  1115. def cast(typ, val):
  1116. """Cast a value to a type.
  1117. This returns the value unchanged. To the type checker this
  1118. signals that the return value has the designated type, but at
  1119. runtime we intentionally don't check anything (we want this
  1120. to be as fast as possible).
  1121. """
  1122. return val
  1123. def _get_defaults(func):
  1124. """Internal helper to extract the default arguments, by name."""
  1125. try:
  1126. code = func.__code__
  1127. except AttributeError:
  1128. # Some built-in functions don't have __code__, __defaults__, etc.
  1129. return {}
  1130. pos_count = code.co_argcount
  1131. arg_names = code.co_varnames
  1132. arg_names = arg_names[:pos_count]
  1133. defaults = func.__defaults__ or ()
  1134. kwdefaults = func.__kwdefaults__
  1135. res = dict(kwdefaults) if kwdefaults else {}
  1136. pos_offset = pos_count - len(defaults)
  1137. for name, value in zip(arg_names[pos_offset:], defaults):
  1138. assert name not in res
  1139. res[name] = value
  1140. return res
  1141. _allowed_types = (types.FunctionType, types.BuiltinFunctionType,
  1142. types.MethodType, types.ModuleType,
  1143. WrapperDescriptorType, MethodWrapperType, MethodDescriptorType)
  1144. def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
  1145. """Return type hints for an object.
  1146. This is often the same as obj.__annotations__, but it handles
  1147. forward references encoded as string literals, adds Optional[t] if a
  1148. default value equal to None is set and recursively replaces all
  1149. 'Annotated[T, ...]' with 'T' (unless 'include_extras=True').
  1150. The argument may be a module, class, method, or function. The annotations
  1151. are returned as a dictionary. For classes, annotations include also
  1152. inherited members.
  1153. TypeError is raised if the argument is not of a type that can contain
  1154. annotations, and an empty dictionary is returned if no annotations are
  1155. present.
  1156. BEWARE -- the behavior of globalns and localns is counterintuitive
  1157. (unless you are familiar with how eval() and exec() work). The
  1158. search order is locals first, then globals.
  1159. - If no dict arguments are passed, an attempt is made to use the
  1160. globals from obj (or the respective module's globals for classes),
  1161. and these are also used as the locals. If the object does not appear
  1162. to have globals, an empty dictionary is used.
  1163. - If one dict argument is passed, it is used for both globals and
  1164. locals.
  1165. - If two dict arguments are passed, they specify globals and
  1166. locals, respectively.
  1167. """
  1168. if getattr(obj, '__no_type_check__', None):
  1169. return {}
  1170. # Classes require a special treatment.
  1171. if isinstance(obj, type):
  1172. hints = {}
  1173. for base in reversed(obj.__mro__):
  1174. if globalns is None:
  1175. base_globals = sys.modules[base.__module__].__dict__
  1176. else:
  1177. base_globals = globalns
  1178. ann = base.__dict__.get('__annotations__', {})
  1179. for name, value in ann.items():
  1180. if value is None:
  1181. value = type(None)
  1182. if isinstance(value, str):
  1183. value = ForwardRef(value, is_argument=False, is_class=True)
  1184. value = _eval_type(value, base_globals, localns)
  1185. hints[name] = value
  1186. return hints if include_extras else {k: _strip_annotations(t) for k, t in hints.items()}
  1187. if globalns is None:
  1188. if isinstance(obj, types.ModuleType):
  1189. globalns = obj.__dict__
  1190. else:
  1191. nsobj = obj
  1192. # Find globalns for the unwrapped object.
  1193. while hasattr(nsobj, '__wrapped__'):
  1194. nsobj = nsobj.__wrapped__
  1195. globalns = getattr(nsobj, '__globals__', {})
  1196. if localns is None:
  1197. localns = globalns
  1198. elif localns is None:
  1199. localns = globalns
  1200. hints = getattr(obj, '__annotations__', None)
  1201. if hints is None:
  1202. # Return empty annotations for something that _could_ have them.
  1203. if isinstance(obj, _allowed_types):
  1204. return {}
  1205. else:
  1206. raise TypeError('{!r} is not a module, class, method, '
  1207. 'or function.'.format(obj))
  1208. defaults = _get_defaults(obj)
  1209. hints = dict(hints)
  1210. for name, value in hints.items():
  1211. if value is None:
  1212. value = type(None)
  1213. if isinstance(value, str):
  1214. # class-level forward refs were handled above, this must be either
  1215. # a module-level annotation or a function argument annotation
  1216. value = ForwardRef(
  1217. value,
  1218. is_argument=not isinstance(obj, types.ModuleType),
  1219. is_class=False,
  1220. )
  1221. value = _eval_type(value, globalns, localns)
  1222. if name in defaults and defaults[name] is None:
  1223. value = Optional[value]
  1224. hints[name] = value
  1225. return hints if include_extras else {k: _strip_annotations(t) for k, t in hints.items()}
  1226. def _strip_annotations(t):
  1227. """Strips the annotations from a given type.
  1228. """
  1229. if isinstance(t, _AnnotatedAlias):
  1230. return _strip_annotations(t.__origin__)
  1231. if isinstance(t, _GenericAlias):
  1232. stripped_args = tuple(_strip_annotations(a) for a in t.__args__)
  1233. if stripped_args == t.__args__:
  1234. return t
  1235. return t.copy_with(stripped_args)
  1236. if isinstance(t, GenericAlias):
  1237. stripped_args = tuple(_strip_annotations(a) for a in t.__args__)
  1238. if stripped_args == t.__args__:
  1239. return t
  1240. return GenericAlias(t.__origin__, stripped_args)
  1241. return t
  1242. def get_origin(tp):
  1243. """Get the unsubscripted version of a type.
  1244. This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
  1245. and Annotated. Return None for unsupported types. Examples::
  1246. get_origin(Literal[42]) is Literal
  1247. get_origin(int) is None
  1248. get_origin(ClassVar[int]) is ClassVar
  1249. get_origin(Generic) is Generic
  1250. get_origin(Generic[T]) is Generic
  1251. get_origin(Union[T, int]) is Union
  1252. get_origin(List[Tuple[T, T]][int]) == list
  1253. """
  1254. if isinstance(tp, _AnnotatedAlias):
  1255. return Annotated
  1256. if isinstance(tp, (_BaseGenericAlias, GenericAlias)):
  1257. return tp.__origin__
  1258. if tp is Generic:
  1259. return Generic
  1260. return None
  1261. def get_args(tp):
  1262. """Get type arguments with all substitutions performed.
  1263. For unions, basic simplifications used by Union constructor are performed.
  1264. Examples::
  1265. get_args(Dict[str, int]) == (str, int)
  1266. get_args(int) == ()
  1267. get_args(Union[int, Union[T, int], str][int]) == (int, str)
  1268. get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
  1269. get_args(Callable[[], T][int]) == ([], int)
  1270. """
  1271. if isinstance(tp, _AnnotatedAlias):
  1272. return (tp.__origin__,) + tp.__metadata__
  1273. if isinstance(tp, (_GenericAlias, GenericAlias)):
  1274. res = tp.__args__
  1275. if tp.__origin__ is collections.abc.Callable and res[0] is not Ellipsis:
  1276. res = (list(res[:-1]), res[-1])
  1277. return res
  1278. return ()
  1279. def no_type_check(arg):
  1280. """Decorator to indicate that annotations are not type hints.
  1281. The argument must be a class or function; if it is a class, it
  1282. applies recursively to all methods and classes defined in that class
  1283. (but not to methods defined in its superclasses or subclasses).
  1284. This mutates the function(s) or class(es) in place.
  1285. """
  1286. if isinstance(arg, type):
  1287. arg_attrs = arg.__dict__.copy()
  1288. for attr, val in arg.__dict__.items():
  1289. if val in arg.__bases__ + (arg,):
  1290. arg_attrs.pop(attr)
  1291. for obj in arg_attrs.values():
  1292. if isinstance(obj, types.FunctionType):
  1293. obj.__no_type_check__ = True
  1294. if isinstance(obj, type):
  1295. no_type_check(obj)
  1296. try:
  1297. arg.__no_type_check__ = True
  1298. except TypeError: # built-in classes
  1299. pass
  1300. return arg
  1301. def no_type_check_decorator(decorator):
  1302. """Decorator to give another decorator the @no_type_check effect.
  1303. This wraps the decorator with something that wraps the decorated
  1304. function in @no_type_check.
  1305. """
  1306. @functools.wraps(decorator)
  1307. def wrapped_decorator(*args, **kwds):
  1308. func = decorator(*args, **kwds)
  1309. func = no_type_check(func)
  1310. return func
  1311. return wrapped_decorator
  1312. def _overload_dummy(*args, **kwds):
  1313. """Helper for @overload to raise when called."""
  1314. raise NotImplementedError(
  1315. "You should not call an overloaded function. "
  1316. "A series of @overload-decorated functions "
  1317. "outside a stub module should always be followed "
  1318. "by an implementation that is not @overload-ed.")
  1319. def overload(func):
  1320. """Decorator for overloaded functions/methods.
  1321. In a stub file, place two or more stub definitions for the same
  1322. function in a row, each decorated with @overload. For example:
  1323. @overload
  1324. def utf8(value: None) -> None: ...
  1325. @overload
  1326. def utf8(value: bytes) -> bytes: ...
  1327. @overload
  1328. def utf8(value: str) -> bytes: ...
  1329. In a non-stub file (i.e. a regular .py file), do the same but
  1330. follow it with an implementation. The implementation should *not*
  1331. be decorated with @overload. For example:
  1332. @overload
  1333. def utf8(value: None) -> None: ...
  1334. @overload
  1335. def utf8(value: bytes) -> bytes: ...
  1336. @overload
  1337. def utf8(value: str) -> bytes: ...
  1338. def utf8(value):
  1339. # implementation goes here
  1340. """
  1341. return _overload_dummy
  1342. def final(f):
  1343. """A decorator to indicate final methods and final classes.
  1344. Use this decorator to indicate to type checkers that the decorated
  1345. method cannot be overridden, and decorated class cannot be subclassed.
  1346. For example:
  1347. class Base:
  1348. @final
  1349. def done(self) -> None:
  1350. ...
  1351. class Sub(Base):
  1352. def done(self) -> None: # Error reported by type checker
  1353. ...
  1354. @final
  1355. class Leaf:
  1356. ...
  1357. class Other(Leaf): # Error reported by type checker
  1358. ...
  1359. There is no runtime checking of these properties.
  1360. """
  1361. return f
  1362. # Some unconstrained type variables. These are used by the container types.
  1363. # (These are not for export.)
  1364. T = TypeVar('T') # Any type.
  1365. KT = TypeVar('KT') # Key type.
  1366. VT = TypeVar('VT') # Value type.
  1367. T_co = TypeVar('T_co', covariant=True) # Any type covariant containers.
  1368. V_co = TypeVar('V_co', covariant=True) # Any type covariant containers.
  1369. VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
  1370. T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
  1371. # Internal type variable used for Type[].
  1372. CT_co = TypeVar('CT_co', covariant=True, bound=type)
  1373. # A useful type variable with constraints. This represents string types.
  1374. # (This one *is* for export!)
  1375. AnyStr = TypeVar('AnyStr', bytes, str)
  1376. # Various ABCs mimicking those in collections.abc.
  1377. _alias = _SpecialGenericAlias
  1378. Hashable = _alias(collections.abc.Hashable, 0) # Not generic.
  1379. Awaitable = _alias(collections.abc.Awaitable, 1)
  1380. Coroutine = _alias(collections.abc.Coroutine, 3)
  1381. AsyncIterable = _alias(collections.abc.AsyncIterable, 1)
  1382. AsyncIterator = _alias(collections.abc.AsyncIterator, 1)
  1383. Iterable = _alias(collections.abc.Iterable, 1)
  1384. Iterator = _alias(collections.abc.Iterator, 1)
  1385. Reversible = _alias(collections.abc.Reversible, 1)
  1386. Sized = _alias(collections.abc.Sized, 0) # Not generic.
  1387. Container = _alias(collections.abc.Container, 1)
  1388. Collection = _alias(collections.abc.Collection, 1)
  1389. Callable = _CallableType(collections.abc.Callable, 2)
  1390. Callable.__doc__ = \
  1391. """Callable type; Callable[[int], str] is a function of (int) -> str.
  1392. The subscription syntax must always be used with exactly two
  1393. values: the argument list and the return type. The argument list
  1394. must be a list of types or ellipsis; the return type must be a single type.
  1395. There is no syntax to indicate optional or keyword arguments,
  1396. such function types are rarely used as callback types.
  1397. """
  1398. AbstractSet = _alias(collections.abc.Set, 1, name='AbstractSet')
  1399. MutableSet = _alias(collections.abc.MutableSet, 1)
  1400. # NOTE: Mapping is only covariant in the value type.
  1401. Mapping = _alias(collections.abc.Mapping, 2)
  1402. MutableMapping = _alias(collections.abc.MutableMapping, 2)
  1403. Sequence = _alias(collections.abc.Sequence, 1)
  1404. MutableSequence = _alias(collections.abc.MutableSequence, 1)
  1405. ByteString = _alias(collections.abc.ByteString, 0) # Not generic
  1406. # Tuple accepts variable number of parameters.
  1407. Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
  1408. Tuple.__doc__ = \
  1409. """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
  1410. Example: Tuple[T1, T2] is a tuple of two elements corresponding
  1411. to type variables T1 and T2. Tuple[int, float, str] is a tuple
  1412. of an int, a float and a string.
  1413. To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
  1414. """
  1415. List = _alias(list, 1, inst=False, name='List')
  1416. Deque = _alias(collections.deque, 1, name='Deque')
  1417. Set = _alias(set, 1, inst=False, name='Set')
  1418. FrozenSet = _alias(frozenset, 1, inst=False, name='FrozenSet')
  1419. MappingView = _alias(collections.abc.MappingView, 1)
  1420. KeysView = _alias(collections.abc.KeysView, 1)
  1421. ItemsView = _alias(collections.abc.ItemsView, 2)
  1422. ValuesView = _alias(collections.abc.ValuesView, 1)
  1423. ContextManager = _alias(contextlib.AbstractContextManager, 1, name='ContextManager')
  1424. AsyncContextManager = _alias(contextlib.AbstractAsyncContextManager, 1, name='AsyncContextManager')
  1425. Dict = _alias(dict, 2, inst=False, name='Dict')
  1426. DefaultDict = _alias(collections.defaultdict, 2, name='DefaultDict')
  1427. OrderedDict = _alias(collections.OrderedDict, 2)
  1428. Counter = _alias(collections.Counter, 1)
  1429. ChainMap = _alias(collections.ChainMap, 2)
  1430. Generator = _alias(collections.abc.Generator, 3)
  1431. AsyncGenerator = _alias(collections.abc.AsyncGenerator, 2)
  1432. Type = _alias(type, 1, inst=False, name='Type')
  1433. Type.__doc__ = \
  1434. """A special construct usable to annotate class objects.
  1435. For example, suppose we have the following classes::
  1436. class User: ... # Abstract base for User classes
  1437. class BasicUser(User): ...
  1438. class ProUser(User): ...
  1439. class TeamUser(User): ...
  1440. And a function that takes a class argument that's a subclass of
  1441. User and returns an instance of the corresponding class::
  1442. U = TypeVar('U', bound=User)
  1443. def new_user(user_class: Type[U]) -> U:
  1444. user = user_class()
  1445. # (Here we could write the user object to a database)
  1446. return user
  1447. joe = new_user(BasicUser)
  1448. At this point the type checker knows that joe has type BasicUser.
  1449. """
  1450. @runtime_checkable
  1451. class SupportsInt(Protocol):
  1452. """An ABC with one abstract method __int__."""
  1453. __slots__ = ()
  1454. @abstractmethod
  1455. def __int__(self) -> int:
  1456. pass
  1457. @runtime_checkable
  1458. class SupportsFloat(Protocol):
  1459. """An ABC with one abstract method __float__."""
  1460. __slots__ = ()
  1461. @abstractmethod
  1462. def __float__(self) -> float:
  1463. pass
  1464. @runtime_checkable
  1465. class SupportsComplex(Protocol):
  1466. """An ABC with one abstract method __complex__."""
  1467. __slots__ = ()
  1468. @abstractmethod
  1469. def __complex__(self) -> complex:
  1470. pass
  1471. @runtime_checkable
  1472. class SupportsBytes(Protocol):
  1473. """An ABC with one abstract method __bytes__."""
  1474. __slots__ = ()
  1475. @abstractmethod
  1476. def __bytes__(self) -> bytes:
  1477. pass
  1478. @runtime_checkable
  1479. class SupportsIndex(Protocol):
  1480. """An ABC with one abstract method __index__."""
  1481. __slots__ = ()
  1482. @abstractmethod
  1483. def __index__(self) -> int:
  1484. pass
  1485. @runtime_checkable
  1486. class SupportsAbs(Protocol[T_co]):
  1487. """An ABC with one abstract method __abs__ that is covariant in its return type."""
  1488. __slots__ = ()
  1489. @abstractmethod
  1490. def __abs__(self) -> T_co:
  1491. pass
  1492. @runtime_checkable
  1493. class SupportsRound(Protocol[T_co]):
  1494. """An ABC with one abstract method __round__ that is covariant in its return type."""
  1495. __slots__ = ()
  1496. @abstractmethod
  1497. def __round__(self, ndigits: int = 0) -> T_co:
  1498. pass
  1499. def _make_nmtuple(name, types, module, defaults = ()):
  1500. fields = [n for n, t in types]
  1501. types = {n: _type_check(t, f"field {n} annotation must be a type")
  1502. for n, t in types}
  1503. nm_tpl = collections.namedtuple(name, fields,
  1504. defaults=defaults, module=module)
  1505. nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = types
  1506. return nm_tpl
  1507. # attributes prohibited to set in NamedTuple class syntax
  1508. _prohibited = frozenset({'__new__', '__init__', '__slots__', '__getnewargs__',
  1509. '_fields', '_field_defaults',
  1510. '_make', '_replace', '_asdict', '_source'})
  1511. _special = frozenset({'__module__', '__name__', '__annotations__'})
  1512. class NamedTupleMeta(type):
  1513. def __new__(cls, typename, bases, ns):
  1514. assert bases[0] is _NamedTuple
  1515. types = ns.get('__annotations__', {})
  1516. default_names = []
  1517. for field_name in types:
  1518. if field_name in ns:
  1519. default_names.append(field_name)
  1520. elif default_names:
  1521. raise TypeError(f"Non-default namedtuple field {field_name} "
  1522. f"cannot follow default field"
  1523. f"{'s' if len(default_names) > 1 else ''} "
  1524. f"{', '.join(default_names)}")
  1525. nm_tpl = _make_nmtuple(typename, types.items(),
  1526. defaults=[ns[n] for n in default_names],
  1527. module=ns['__module__'])
  1528. # update from user namespace without overriding special namedtuple attributes
  1529. for key in ns:
  1530. if key in _prohibited:
  1531. raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
  1532. elif key not in _special and key not in nm_tpl._fields:
  1533. setattr(nm_tpl, key, ns[key])
  1534. return nm_tpl
  1535. def NamedTuple(typename, fields=None, /, **kwargs):
  1536. """Typed version of namedtuple.
  1537. Usage in Python versions >= 3.6::
  1538. class Employee(NamedTuple):
  1539. name: str
  1540. id: int
  1541. This is equivalent to::
  1542. Employee = collections.namedtuple('Employee', ['name', 'id'])
  1543. The resulting class has an extra __annotations__ attribute, giving a
  1544. dict that maps field names to types. (The field names are also in
  1545. the _fields attribute, which is part of the namedtuple API.)
  1546. Alternative equivalent keyword syntax is also accepted::
  1547. Employee = NamedTuple('Employee', name=str, id=int)
  1548. In Python versions <= 3.5 use::
  1549. Employee = NamedTuple('Employee', [('name', str), ('id', int)])
  1550. """
  1551. if fields is None:
  1552. fields = kwargs.items()
  1553. elif kwargs:
  1554. raise TypeError("Either list of fields or keywords"
  1555. " can be provided to NamedTuple, not both")
  1556. try:
  1557. module = sys._getframe(1).f_globals.get('__name__', '__main__')
  1558. except (AttributeError, ValueError):
  1559. module = None
  1560. return _make_nmtuple(typename, fields, module=module)
  1561. _NamedTuple = type.__new__(NamedTupleMeta, 'NamedTuple', (), {})
  1562. def _namedtuple_mro_entries(bases):
  1563. if len(bases) > 1:
  1564. raise TypeError("Multiple inheritance with NamedTuple is not supported")
  1565. assert bases[0] is NamedTuple
  1566. return (_NamedTuple,)
  1567. NamedTuple.__mro_entries__ = _namedtuple_mro_entries
  1568. class _TypedDictMeta(type):
  1569. def __new__(cls, name, bases, ns, total=True):
  1570. """Create new typed dict class object.
  1571. This method is called when TypedDict is subclassed,
  1572. or when TypedDict is instantiated. This way
  1573. TypedDict supports all three syntax forms described in its docstring.
  1574. Subclasses and instances of TypedDict return actual dictionaries.
  1575. """
  1576. for base in bases:
  1577. if type(base) is not _TypedDictMeta:
  1578. raise TypeError('cannot inherit from both a TypedDict type '
  1579. 'and a non-TypedDict base class')
  1580. tp_dict = type.__new__(_TypedDictMeta, name, (dict,), ns)
  1581. annotations = {}
  1582. own_annotations = ns.get('__annotations__', {})
  1583. own_annotation_keys = set(own_annotations.keys())
  1584. msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
  1585. own_annotations = {
  1586. n: _type_check(tp, msg, module=tp_dict.__module__)
  1587. for n, tp in own_annotations.items()
  1588. }
  1589. required_keys = set()
  1590. optional_keys = set()
  1591. for base in bases:
  1592. annotations.update(base.__dict__.get('__annotations__', {}))
  1593. required_keys.update(base.__dict__.get('__required_keys__', ()))
  1594. optional_keys.update(base.__dict__.get('__optional_keys__', ()))
  1595. annotations.update(own_annotations)
  1596. if total:
  1597. required_keys.update(own_annotation_keys)
  1598. else:
  1599. optional_keys.update(own_annotation_keys)
  1600. tp_dict.__annotations__ = annotations
  1601. tp_dict.__required_keys__ = frozenset(required_keys)
  1602. tp_dict.__optional_keys__ = frozenset(optional_keys)
  1603. if not hasattr(tp_dict, '__total__'):
  1604. tp_dict.__total__ = total
  1605. return tp_dict
  1606. __call__ = dict # static method
  1607. def __subclasscheck__(cls, other):
  1608. # Typed dicts are only for static structural subtyping.
  1609. raise TypeError('TypedDict does not support instance and class checks')
  1610. __instancecheck__ = __subclasscheck__
  1611. def TypedDict(typename, fields=None, /, *, total=True, **kwargs):
  1612. """A simple typed namespace. At runtime it is equivalent to a plain dict.
  1613. TypedDict creates a dictionary type that expects all of its
  1614. instances to have a certain set of keys, where each key is
  1615. associated with a value of a consistent type. This expectation
  1616. is not checked at runtime but is only enforced by type checkers.
  1617. Usage::
  1618. class Point2D(TypedDict):
  1619. x: int
  1620. y: int
  1621. label: str
  1622. a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
  1623. b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
  1624. assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
  1625. The type info can be accessed via the Point2D.__annotations__ dict, and
  1626. the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
  1627. TypedDict supports two additional equivalent forms::
  1628. Point2D = TypedDict('Point2D', x=int, y=int, label=str)
  1629. Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
  1630. By default, all keys must be present in a TypedDict. It is possible
  1631. to override this by specifying totality.
  1632. Usage::
  1633. class point2D(TypedDict, total=False):
  1634. x: int
  1635. y: int
  1636. This means that a point2D TypedDict can have any of the keys omitted.A type
  1637. checker is only expected to support a literal False or True as the value of
  1638. the total argument. True is the default, and makes all items defined in the
  1639. class body be required.
  1640. The class syntax is only supported in Python 3.6+, while two other
  1641. syntax forms work for Python 2.7 and 3.2+
  1642. """
  1643. if fields is None:
  1644. fields = kwargs
  1645. elif kwargs:
  1646. raise TypeError("TypedDict takes either a dict or keyword arguments,"
  1647. " but not both")
  1648. ns = {'__annotations__': dict(fields)}
  1649. try:
  1650. # Setting correct module is necessary to make typed dict classes pickleable.
  1651. ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__')
  1652. except (AttributeError, ValueError):
  1653. pass
  1654. return _TypedDictMeta(typename, (), ns, total=total)
  1655. _TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {})
  1656. TypedDict.__mro_entries__ = lambda bases: (_TypedDict,)
  1657. def NewType(name, tp):
  1658. """NewType creates simple unique types with almost zero
  1659. runtime overhead. NewType(name, tp) is considered a subtype of tp
  1660. by static type checkers. At runtime, NewType(name, tp) returns
  1661. a dummy function that simply returns its argument. Usage::
  1662. UserId = NewType('UserId', int)
  1663. def name_by_id(user_id: UserId) -> str:
  1664. ...
  1665. UserId('user') # Fails type check
  1666. name_by_id(42) # Fails type check
  1667. name_by_id(UserId(42)) # OK
  1668. num = UserId(5) + 1 # type: int
  1669. """
  1670. def new_type(x):
  1671. return x
  1672. new_type.__name__ = name
  1673. new_type.__supertype__ = tp
  1674. return new_type
  1675. # Python-version-specific alias (Python 2: unicode; Python 3: str)
  1676. Text = str
  1677. # Constant that's True when type checking, but False here.
  1678. TYPE_CHECKING = False
  1679. class IO(Generic[AnyStr]):
  1680. """Generic base class for TextIO and BinaryIO.
  1681. This is an abstract, generic version of the return of open().
  1682. NOTE: This does not distinguish between the different possible
  1683. classes (text vs. binary, read vs. write vs. read/write,
  1684. append-only, unbuffered). The TextIO and BinaryIO subclasses
  1685. below capture the distinctions between text vs. binary, which is
  1686. pervasive in the interface; however we currently do not offer a
  1687. way to track the other distinctions in the type system.
  1688. """
  1689. __slots__ = ()
  1690. @property
  1691. @abstractmethod
  1692. def mode(self) -> str:
  1693. pass
  1694. @property
  1695. @abstractmethod
  1696. def name(self) -> str:
  1697. pass
  1698. @abstractmethod
  1699. def close(self) -> None:
  1700. pass
  1701. @property
  1702. @abstractmethod
  1703. def closed(self) -> bool:
  1704. pass
  1705. @abstractmethod
  1706. def fileno(self) -> int:
  1707. pass
  1708. @abstractmethod
  1709. def flush(self) -> None:
  1710. pass
  1711. @abstractmethod
  1712. def isatty(self) -> bool:
  1713. pass
  1714. @abstractmethod
  1715. def read(self, n: int = -1) -> AnyStr:
  1716. pass
  1717. @abstractmethod
  1718. def readable(self) -> bool:
  1719. pass
  1720. @abstractmethod
  1721. def readline(self, limit: int = -1) -> AnyStr:
  1722. pass
  1723. @abstractmethod
  1724. def readlines(self, hint: int = -1) -> List[AnyStr]:
  1725. pass
  1726. @abstractmethod
  1727. def seek(self, offset: int, whence: int = 0) -> int:
  1728. pass
  1729. @abstractmethod
  1730. def seekable(self) -> bool:
  1731. pass
  1732. @abstractmethod
  1733. def tell(self) -> int:
  1734. pass
  1735. @abstractmethod
  1736. def truncate(self, size: int = None) -> int:
  1737. pass
  1738. @abstractmethod
  1739. def writable(self) -> bool:
  1740. pass
  1741. @abstractmethod
  1742. def write(self, s: AnyStr) -> int:
  1743. pass
  1744. @abstractmethod
  1745. def writelines(self, lines: List[AnyStr]) -> None:
  1746. pass
  1747. @abstractmethod
  1748. def __enter__(self) -> 'IO[AnyStr]':
  1749. pass
  1750. @abstractmethod
  1751. def __exit__(self, type, value, traceback) -> None:
  1752. pass
  1753. class BinaryIO(IO[bytes]):
  1754. """Typed version of the return of open() in binary mode."""
  1755. __slots__ = ()
  1756. @abstractmethod
  1757. def write(self, s: Union[bytes, bytearray]) -> int:
  1758. pass
  1759. @abstractmethod
  1760. def __enter__(self) -> 'BinaryIO':
  1761. pass
  1762. class TextIO(IO[str]):
  1763. """Typed version of the return of open() in text mode."""
  1764. __slots__ = ()
  1765. @property
  1766. @abstractmethod
  1767. def buffer(self) -> BinaryIO:
  1768. pass
  1769. @property
  1770. @abstractmethod
  1771. def encoding(self) -> str:
  1772. pass
  1773. @property
  1774. @abstractmethod
  1775. def errors(self) -> Optional[str]:
  1776. pass
  1777. @property
  1778. @abstractmethod
  1779. def line_buffering(self) -> bool:
  1780. pass
  1781. @property
  1782. @abstractmethod
  1783. def newlines(self) -> Any:
  1784. pass
  1785. @abstractmethod
  1786. def __enter__(self) -> 'TextIO':
  1787. pass
  1788. class io:
  1789. """Wrapper namespace for IO generic classes."""
  1790. __all__ = ['IO', 'TextIO', 'BinaryIO']
  1791. IO = IO
  1792. TextIO = TextIO
  1793. BinaryIO = BinaryIO
  1794. io.__name__ = __name__ + '.io'
  1795. sys.modules[io.__name__] = io
  1796. Pattern = _alias(stdlib_re.Pattern, 1)
  1797. Match = _alias(stdlib_re.Match, 1)
  1798. class re:
  1799. """Wrapper namespace for re type aliases."""
  1800. __all__ = ['Pattern', 'Match']
  1801. Pattern = Pattern
  1802. Match = Match
  1803. re.__name__ = __name__ + '.re'
  1804. sys.modules[re.__name__] = re