typing.py 73 KB

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