typing.py 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654
  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. (the latter is currently private, but will be made public after PEP 544 acceptance).
  13. * Public helper functions: get_type_hints, overload, cast, no_type_check,
  14. no_type_check_decorator.
  15. * Generic aliases for collections.abc ABCs and few additional protocols.
  16. * Special types: NewType, NamedTuple, TypedDict (may be added soon).
  17. * Wrapper submodules for re and io related types.
  18. """
  19. import abc
  20. from abc import abstractmethod, abstractproperty
  21. import collections
  22. import collections.abc
  23. import contextlib
  24. import functools
  25. import operator
  26. import re as stdlib_re # Avoid confusion with the re we export.
  27. import sys
  28. import types
  29. from types import WrapperDescriptorType, MethodWrapperType, MethodDescriptorType
  30. # Please keep __all__ alphabetized within each category.
  31. __all__ = [
  32. # Super-special typing primitives.
  33. 'Any',
  34. 'Callable',
  35. 'ClassVar',
  36. 'ForwardRef',
  37. 'Generic',
  38. 'Optional',
  39. 'Tuple',
  40. 'Type',
  41. 'TypeVar',
  42. 'Union',
  43. # ABCs (from collections.abc).
  44. 'AbstractSet', # collections.abc.Set.
  45. 'ByteString',
  46. 'Container',
  47. 'ContextManager',
  48. 'Hashable',
  49. 'ItemsView',
  50. 'Iterable',
  51. 'Iterator',
  52. 'KeysView',
  53. 'Mapping',
  54. 'MappingView',
  55. 'MutableMapping',
  56. 'MutableSequence',
  57. 'MutableSet',
  58. 'Sequence',
  59. 'Sized',
  60. 'ValuesView',
  61. 'Awaitable',
  62. 'AsyncIterator',
  63. 'AsyncIterable',
  64. 'Coroutine',
  65. 'Collection',
  66. 'AsyncGenerator',
  67. 'AsyncContextManager',
  68. # Structural checks, a.k.a. protocols.
  69. 'Reversible',
  70. 'SupportsAbs',
  71. 'SupportsBytes',
  72. 'SupportsComplex',
  73. 'SupportsFloat',
  74. 'SupportsInt',
  75. 'SupportsRound',
  76. # Concrete collection types.
  77. 'ChainMap',
  78. 'Counter',
  79. 'Deque',
  80. 'Dict',
  81. 'DefaultDict',
  82. 'List',
  83. 'OrderedDict',
  84. 'Set',
  85. 'FrozenSet',
  86. 'NamedTuple', # Not really a type.
  87. 'Generator',
  88. # One-off things.
  89. 'AnyStr',
  90. 'cast',
  91. 'get_type_hints',
  92. 'NewType',
  93. 'no_type_check',
  94. 'no_type_check_decorator',
  95. 'NoReturn',
  96. 'overload',
  97. 'Text',
  98. 'TYPE_CHECKING',
  99. ]
  100. # The pseudo-submodules 're' and 'io' are part of the public
  101. # namespace, but excluded from __all__ because they might stomp on
  102. # legitimate imports of those modules.
  103. def _type_check(arg, msg, is_argument=True):
  104. """Check that the argument is a type, and return it (internal helper).
  105. As a special case, accept None and return type(None) instead. Also wrap strings
  106. into ForwardRef instances. Consider several corner cases, for example plain
  107. special forms like Union are not valid, while Union[int, str] is OK, etc.
  108. The msg argument is a human-readable error message, e.g::
  109. "Union[arg, ...]: arg should be a type."
  110. We append the repr() of the actual value (truncated to 100 chars).
  111. """
  112. invalid_generic_forms = (Generic, _Protocol)
  113. if is_argument:
  114. invalid_generic_forms = invalid_generic_forms + (ClassVar, )
  115. if arg is None:
  116. return type(None)
  117. if isinstance(arg, str):
  118. return ForwardRef(arg)
  119. if (isinstance(arg, _GenericAlias) and
  120. arg.__origin__ in invalid_generic_forms):
  121. raise TypeError(f"{arg} is not valid as type argument")
  122. if (isinstance(arg, _SpecialForm) and arg not in (Any, NoReturn) or
  123. arg in (Generic, _Protocol)):
  124. raise TypeError(f"Plain {arg} is not valid as type argument")
  125. if isinstance(arg, (type, TypeVar, ForwardRef)):
  126. return arg
  127. if not callable(arg):
  128. raise TypeError(f"{msg} Got {arg!r:.100}.")
  129. return arg
  130. def _type_repr(obj):
  131. """Return the repr() of an object, special-casing types (internal helper).
  132. If obj is a type, we return a shorter version than the default
  133. type.__repr__, based on the module and qualified name, which is
  134. typically enough to uniquely identify a type. For everything
  135. else, we fall back on repr(obj).
  136. """
  137. if isinstance(obj, type):
  138. if obj.__module__ == 'builtins':
  139. return obj.__qualname__
  140. return f'{obj.__module__}.{obj.__qualname__}'
  141. if obj is ...:
  142. return('...')
  143. if isinstance(obj, types.FunctionType):
  144. return obj.__name__
  145. return repr(obj)
  146. def _collect_type_vars(types):
  147. """Collect all type variable contained in types in order of
  148. first appearance (lexicographic order). For example::
  149. _collect_type_vars((T, List[S, T])) == (T, S)
  150. """
  151. tvars = []
  152. for t in types:
  153. if isinstance(t, TypeVar) and t not in tvars:
  154. tvars.append(t)
  155. if isinstance(t, _GenericAlias) and not t._special:
  156. tvars.extend([t for t in t.__parameters__ if t not in tvars])
  157. return tuple(tvars)
  158. def _subs_tvars(tp, tvars, subs):
  159. """Substitute type variables 'tvars' with substitutions 'subs'.
  160. These two must have the same length.
  161. """
  162. if not isinstance(tp, _GenericAlias):
  163. return tp
  164. new_args = list(tp.__args__)
  165. for a, arg in enumerate(tp.__args__):
  166. if isinstance(arg, TypeVar):
  167. for i, tvar in enumerate(tvars):
  168. if arg == tvar:
  169. new_args[a] = subs[i]
  170. else:
  171. new_args[a] = _subs_tvars(arg, tvars, subs)
  172. if tp.__origin__ is Union:
  173. return Union[tuple(new_args)]
  174. return tp.copy_with(tuple(new_args))
  175. def _check_generic(cls, parameters):
  176. """Check correct count for parameters of a generic cls (internal helper).
  177. This gives a nice error message in case of count mismatch.
  178. """
  179. if not cls.__parameters__:
  180. raise TypeError(f"{cls} is not a generic class")
  181. alen = len(parameters)
  182. elen = len(cls.__parameters__)
  183. if alen != elen:
  184. raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};"
  185. f" actual {alen}, expected {elen}")
  186. def _remove_dups_flatten(parameters):
  187. """An internal helper for Union creation and substitution: flatten Unions
  188. among parameters, then remove duplicates.
  189. """
  190. # Flatten out Union[Union[...], ...].
  191. params = []
  192. for p in parameters:
  193. if isinstance(p, _GenericAlias) and p.__origin__ is Union:
  194. params.extend(p.__args__)
  195. elif isinstance(p, tuple) and len(p) > 0 and p[0] is Union:
  196. params.extend(p[1:])
  197. else:
  198. params.append(p)
  199. # Weed out strict duplicates, preserving the first of each occurrence.
  200. all_params = set(params)
  201. if len(all_params) < len(params):
  202. new_params = []
  203. for t in params:
  204. if t in all_params:
  205. new_params.append(t)
  206. all_params.remove(t)
  207. params = new_params
  208. assert not all_params, all_params
  209. return tuple(params)
  210. _cleanups = []
  211. def _tp_cache(func):
  212. """Internal wrapper caching __getitem__ of generic types with a fallback to
  213. original function for non-hashable arguments.
  214. """
  215. cached = functools.lru_cache()(func)
  216. _cleanups.append(cached.cache_clear)
  217. @functools.wraps(func)
  218. def inner(*args, **kwds):
  219. try:
  220. return cached(*args, **kwds)
  221. except TypeError:
  222. pass # All real errors (not unhashable args) are raised below.
  223. return func(*args, **kwds)
  224. return inner
  225. def _eval_type(t, globalns, localns):
  226. """Evaluate all forward reverences in the given type t.
  227. For use of globalns and localns see the docstring for get_type_hints().
  228. """
  229. if isinstance(t, ForwardRef):
  230. return t._evaluate(globalns, localns)
  231. if isinstance(t, _GenericAlias):
  232. ev_args = tuple(_eval_type(a, globalns, localns) for a in t.__args__)
  233. if ev_args == t.__args__:
  234. return t
  235. res = t.copy_with(ev_args)
  236. res._special = t._special
  237. return res
  238. return t
  239. class _Final:
  240. """Mixin to prohibit subclassing"""
  241. __slots__ = ('__weakref__',)
  242. def __init_subclass__(self, *args, **kwds):
  243. if '_root' not in kwds:
  244. raise TypeError("Cannot subclass special typing classes")
  245. class _Immutable:
  246. """Mixin to indicate that object should not be copied."""
  247. def __copy__(self):
  248. return self
  249. def __deepcopy__(self, memo):
  250. return self
  251. class _SpecialForm(_Final, _Immutable, _root=True):
  252. """Internal indicator of special typing constructs.
  253. See _doc instance attribute for specific docs.
  254. """
  255. __slots__ = ('_name', '_doc')
  256. def __new__(cls, *args, **kwds):
  257. """Constructor.
  258. This only exists to give a better error message in case
  259. someone tries to subclass a special typing object (not a good idea).
  260. """
  261. if (len(args) == 3 and
  262. isinstance(args[0], str) and
  263. isinstance(args[1], tuple)):
  264. # Close enough.
  265. raise TypeError(f"Cannot subclass {cls!r}")
  266. return super().__new__(cls)
  267. def __init__(self, name, doc):
  268. self._name = name
  269. self._doc = doc
  270. def __eq__(self, other):
  271. if not isinstance(other, _SpecialForm):
  272. return NotImplemented
  273. return self._name == other._name
  274. def __hash__(self):
  275. return hash((self._name,))
  276. def __repr__(self):
  277. return 'typing.' + self._name
  278. def __reduce__(self):
  279. return self._name
  280. def __call__(self, *args, **kwds):
  281. raise TypeError(f"Cannot instantiate {self!r}")
  282. def __instancecheck__(self, obj):
  283. raise TypeError(f"{self} cannot be used with isinstance()")
  284. def __subclasscheck__(self, cls):
  285. raise TypeError(f"{self} cannot be used with issubclass()")
  286. @_tp_cache
  287. def __getitem__(self, parameters):
  288. if self._name == 'ClassVar':
  289. item = _type_check(parameters, 'ClassVar accepts only single type.')
  290. return _GenericAlias(self, (item,))
  291. if self._name == 'Union':
  292. if parameters == ():
  293. raise TypeError("Cannot take a Union of no types.")
  294. if not isinstance(parameters, tuple):
  295. parameters = (parameters,)
  296. msg = "Union[arg, ...]: each arg must be a type."
  297. parameters = tuple(_type_check(p, msg) for p in parameters)
  298. parameters = _remove_dups_flatten(parameters)
  299. if len(parameters) == 1:
  300. return parameters[0]
  301. return _GenericAlias(self, parameters)
  302. if self._name == 'Optional':
  303. arg = _type_check(parameters, "Optional[t] requires a single type.")
  304. return Union[arg, type(None)]
  305. raise TypeError(f"{self} is not subscriptable")
  306. Any = _SpecialForm('Any', doc=
  307. """Special type indicating an unconstrained type.
  308. - Any is compatible with every type.
  309. - Any assumed to have all methods.
  310. - All values assumed to be instances of Any.
  311. Note that all the above statements are true from the point of view of
  312. static type checkers. At runtime, Any should not be used with instance
  313. or class checks.
  314. """)
  315. NoReturn = _SpecialForm('NoReturn', doc=
  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. ClassVar = _SpecialForm('ClassVar', doc=
  325. """Special type construct to mark class variables.
  326. An annotation wrapped in ClassVar indicates that a given
  327. attribute is intended to be used as a class variable and
  328. should not be set on instances of that class. Usage::
  329. class Starship:
  330. stats: ClassVar[Dict[str, int]] = {} # class variable
  331. damage: int = 10 # instance variable
  332. ClassVar accepts only types and cannot be further subscribed.
  333. Note that ClassVar is not a class itself, and should not
  334. be used with isinstance() or issubclass().
  335. """)
  336. Union = _SpecialForm('Union', doc=
  337. """Union type; Union[X, Y] means either X or Y.
  338. To define a union, use e.g. Union[int, str]. Details:
  339. - The arguments must be types and there must be at least one.
  340. - None as an argument is a special case and is replaced by
  341. type(None).
  342. - Unions of unions are flattened, e.g.::
  343. Union[Union[int, str], float] == Union[int, str, float]
  344. - Unions of a single argument vanish, e.g.::
  345. Union[int] == int # The constructor actually returns int
  346. - Redundant arguments are skipped, e.g.::
  347. Union[int, str, int] == Union[int, str]
  348. - When comparing unions, the argument order is ignored, e.g.::
  349. Union[int, str] == Union[str, int]
  350. - You cannot subclass or instantiate a union.
  351. - You can use Optional[X] as a shorthand for Union[X, None].
  352. """)
  353. Optional = _SpecialForm('Optional', doc=
  354. """Optional type.
  355. Optional[X] is equivalent to Union[X, None].
  356. """)
  357. class ForwardRef(_Final, _root=True):
  358. """Internal wrapper to hold a forward reference."""
  359. __slots__ = ('__forward_arg__', '__forward_code__',
  360. '__forward_evaluated__', '__forward_value__',
  361. '__forward_is_argument__')
  362. def __init__(self, arg, is_argument=True):
  363. if not isinstance(arg, str):
  364. raise TypeError(f"Forward reference must be a string -- got {arg!r}")
  365. try:
  366. code = compile(arg, '<string>', 'eval')
  367. except SyntaxError:
  368. raise SyntaxError(f"Forward reference must be an expression -- got {arg!r}")
  369. self.__forward_arg__ = arg
  370. self.__forward_code__ = code
  371. self.__forward_evaluated__ = False
  372. self.__forward_value__ = None
  373. self.__forward_is_argument__ = is_argument
  374. def _evaluate(self, globalns, localns):
  375. if not self.__forward_evaluated__ or localns is not globalns:
  376. if globalns is None and localns is None:
  377. globalns = localns = {}
  378. elif globalns is None:
  379. globalns = localns
  380. elif localns is None:
  381. localns = globalns
  382. self.__forward_value__ = _type_check(
  383. eval(self.__forward_code__, globalns, localns),
  384. "Forward references must evaluate to types.",
  385. is_argument=self.__forward_is_argument__)
  386. self.__forward_evaluated__ = True
  387. return self.__forward_value__
  388. def __eq__(self, other):
  389. if not isinstance(other, ForwardRef):
  390. return NotImplemented
  391. if self.__forward_evaluated__ and other.__forward_evaluated__:
  392. return (self.__forward_arg__ == other.__forward_arg__ and
  393. self.__forward_value__ == other.__forward_value__)
  394. return self.__forward_arg__ == other.__forward_arg__
  395. def __hash__(self):
  396. return hash(self.__forward_arg__)
  397. def __repr__(self):
  398. return f'ForwardRef({self.__forward_arg__!r})'
  399. class TypeVar(_Final, _Immutable, _root=True):
  400. """Type variable.
  401. Usage::
  402. T = TypeVar('T') # Can be anything
  403. A = TypeVar('A', str, bytes) # Must be str or bytes
  404. Type variables exist primarily for the benefit of static type
  405. checkers. They serve as the parameters for generic types as well
  406. as for generic function definitions. See class Generic for more
  407. information on generic types. Generic functions work as follows:
  408. def repeat(x: T, n: int) -> List[T]:
  409. '''Return a list containing n references to x.'''
  410. return [x]*n
  411. def longest(x: A, y: A) -> A:
  412. '''Return the longest of two strings.'''
  413. return x if len(x) >= len(y) else y
  414. The latter example's signature is essentially the overloading
  415. of (str, str) -> str and (bytes, bytes) -> bytes. Also note
  416. that if the arguments are instances of some subclass of str,
  417. the return type is still plain str.
  418. At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.
  419. Type variables defined with covariant=True or contravariant=True
  420. can be used to declare covariant or contravariant generic types.
  421. See PEP 484 for more details. By default generic types are invariant
  422. in all type variables.
  423. Type variables can be introspected. e.g.:
  424. T.__name__ == 'T'
  425. T.__constraints__ == ()
  426. T.__covariant__ == False
  427. T.__contravariant__ = False
  428. A.__constraints__ == (str, bytes)
  429. Note that only type variables defined in global scope can be pickled.
  430. """
  431. __slots__ = ('__name__', '__bound__', '__constraints__',
  432. '__covariant__', '__contravariant__')
  433. def __init__(self, name, *constraints, bound=None,
  434. covariant=False, contravariant=False):
  435. self.__name__ = name
  436. if covariant and contravariant:
  437. raise ValueError("Bivariant types are not supported.")
  438. self.__covariant__ = bool(covariant)
  439. self.__contravariant__ = bool(contravariant)
  440. if constraints and bound is not None:
  441. raise TypeError("Constraints cannot be combined with bound=...")
  442. if constraints and len(constraints) == 1:
  443. raise TypeError("A single constraint is not allowed")
  444. msg = "TypeVar(name, constraint, ...): constraints must be types."
  445. self.__constraints__ = tuple(_type_check(t, msg) for t in constraints)
  446. if bound:
  447. self.__bound__ = _type_check(bound, "Bound must be a type.")
  448. else:
  449. self.__bound__ = None
  450. try:
  451. def_mod = sys._getframe(1).f_globals.get('__name__', '__main__') # for pickling
  452. except (AttributeError, ValueError):
  453. def_mod = None
  454. if def_mod != 'typing':
  455. self.__module__ = def_mod
  456. def __repr__(self):
  457. if self.__covariant__:
  458. prefix = '+'
  459. elif self.__contravariant__:
  460. prefix = '-'
  461. else:
  462. prefix = '~'
  463. return prefix + self.__name__
  464. def __reduce__(self):
  465. return self.__name__
  466. # Special typing constructs Union, Optional, Generic, Callable and Tuple
  467. # use three special attributes for internal bookkeeping of generic types:
  468. # * __parameters__ is a tuple of unique free type parameters of a generic
  469. # type, for example, Dict[T, T].__parameters__ == (T,);
  470. # * __origin__ keeps a reference to a type that was subscripted,
  471. # e.g., Union[T, int].__origin__ == Union, or the non-generic version of
  472. # the type.
  473. # * __args__ is a tuple of all arguments used in subscripting,
  474. # e.g., Dict[T, int].__args__ == (T, int).
  475. # Mapping from non-generic type names that have a generic alias in typing
  476. # but with a different name.
  477. _normalize_alias = {'list': 'List',
  478. 'tuple': 'Tuple',
  479. 'dict': 'Dict',
  480. 'set': 'Set',
  481. 'frozenset': 'FrozenSet',
  482. 'deque': 'Deque',
  483. 'defaultdict': 'DefaultDict',
  484. 'type': 'Type',
  485. 'Set': 'AbstractSet'}
  486. def _is_dunder(attr):
  487. return attr.startswith('__') and attr.endswith('__')
  488. class _GenericAlias(_Final, _root=True):
  489. """The central part of internal API.
  490. This represents a generic version of type 'origin' with type arguments 'params'.
  491. There are two kind of these aliases: user defined and special. The special ones
  492. are wrappers around builtin collections and ABCs in collections.abc. These must
  493. have 'name' always set. If 'inst' is False, then the alias can't be instantiated,
  494. this is used by e.g. typing.List and typing.Dict.
  495. """
  496. def __init__(self, origin, params, *, inst=True, special=False, name=None):
  497. self._inst = inst
  498. self._special = special
  499. if special and name is None:
  500. orig_name = origin.__name__
  501. name = _normalize_alias.get(orig_name, orig_name)
  502. self._name = name
  503. if not isinstance(params, tuple):
  504. params = (params,)
  505. self.__origin__ = origin
  506. self.__args__ = tuple(... if a is _TypingEllipsis else
  507. () if a is _TypingEmpty else
  508. a for a in params)
  509. self.__parameters__ = _collect_type_vars(params)
  510. self.__slots__ = None # This is not documented.
  511. if not name:
  512. self.__module__ = origin.__module__
  513. @_tp_cache
  514. def __getitem__(self, params):
  515. if self.__origin__ in (Generic, _Protocol):
  516. # Can't subscript Generic[...] or _Protocol[...].
  517. raise TypeError(f"Cannot subscript already-subscripted {self}")
  518. if not isinstance(params, tuple):
  519. params = (params,)
  520. msg = "Parameters to generic types must be types."
  521. params = tuple(_type_check(p, msg) for p in params)
  522. _check_generic(self, params)
  523. return _subs_tvars(self, self.__parameters__, params)
  524. def copy_with(self, params):
  525. # We don't copy self._special.
  526. return _GenericAlias(self.__origin__, params, name=self._name, inst=self._inst)
  527. def __repr__(self):
  528. if (self._name != 'Callable' or
  529. len(self.__args__) == 2 and self.__args__[0] is Ellipsis):
  530. if self._name:
  531. name = 'typing.' + self._name
  532. else:
  533. name = _type_repr(self.__origin__)
  534. if not self._special:
  535. args = f'[{", ".join([_type_repr(a) for a in self.__args__])}]'
  536. else:
  537. args = ''
  538. return (f'{name}{args}')
  539. if self._special:
  540. return 'typing.Callable'
  541. return (f'typing.Callable'
  542. f'[[{", ".join([_type_repr(a) for a in self.__args__[:-1]])}], '
  543. f'{_type_repr(self.__args__[-1])}]')
  544. def __eq__(self, other):
  545. if not isinstance(other, _GenericAlias):
  546. return NotImplemented
  547. if self.__origin__ != other.__origin__:
  548. return False
  549. if self.__origin__ is Union and other.__origin__ is Union:
  550. return frozenset(self.__args__) == frozenset(other.__args__)
  551. return self.__args__ == other.__args__
  552. def __hash__(self):
  553. if self.__origin__ is Union:
  554. return hash((Union, frozenset(self.__args__)))
  555. return hash((self.__origin__, self.__args__))
  556. def __call__(self, *args, **kwargs):
  557. if not self._inst:
  558. raise TypeError(f"Type {self._name} cannot be instantiated; "
  559. f"use {self._name.lower()}() instead")
  560. result = self.__origin__(*args, **kwargs)
  561. try:
  562. result.__orig_class__ = self
  563. except AttributeError:
  564. pass
  565. return result
  566. def __mro_entries__(self, bases):
  567. if self._name: # generic version of an ABC or built-in class
  568. res = []
  569. if self.__origin__ not in bases:
  570. res.append(self.__origin__)
  571. i = bases.index(self)
  572. if not any(isinstance(b, _GenericAlias) or issubclass(b, Generic)
  573. for b in bases[i+1:]):
  574. res.append(Generic)
  575. return tuple(res)
  576. if self.__origin__ is Generic:
  577. i = bases.index(self)
  578. for b in bases[i+1:]:
  579. if isinstance(b, _GenericAlias) and b is not self:
  580. return ()
  581. return (self.__origin__,)
  582. def __getattr__(self, attr):
  583. # We are careful for copy and pickle.
  584. # Also for simplicity we just don't relay all dunder names
  585. if '__origin__' in self.__dict__ and not _is_dunder(attr):
  586. return getattr(self.__origin__, attr)
  587. raise AttributeError(attr)
  588. def __setattr__(self, attr, val):
  589. if _is_dunder(attr) or attr in ('_name', '_inst', '_special'):
  590. super().__setattr__(attr, val)
  591. else:
  592. setattr(self.__origin__, attr, val)
  593. def __instancecheck__(self, obj):
  594. return self.__subclasscheck__(type(obj))
  595. def __subclasscheck__(self, cls):
  596. if self._special:
  597. if not isinstance(cls, _GenericAlias):
  598. return issubclass(cls, self.__origin__)
  599. if cls._special:
  600. return issubclass(cls.__origin__, self.__origin__)
  601. raise TypeError("Subscripted generics cannot be used with"
  602. " class and instance checks")
  603. def __reduce__(self):
  604. if self._special:
  605. return self._name
  606. if self._name:
  607. origin = globals()[self._name]
  608. else:
  609. origin = self.__origin__
  610. if (origin is Callable and
  611. not (len(self.__args__) == 2 and self.__args__[0] is Ellipsis)):
  612. args = list(self.__args__[:-1]), self.__args__[-1]
  613. else:
  614. args = tuple(self.__args__)
  615. if len(args) == 1 and not isinstance(args[0], tuple):
  616. args, = args
  617. return operator.getitem, (origin, args)
  618. class _VariadicGenericAlias(_GenericAlias, _root=True):
  619. """Same as _GenericAlias above but for variadic aliases. Currently,
  620. this is used only by special internal aliases: Tuple and Callable.
  621. """
  622. def __getitem__(self, params):
  623. if self._name != 'Callable' or not self._special:
  624. return self.__getitem_inner__(params)
  625. if not isinstance(params, tuple) or len(params) != 2:
  626. raise TypeError("Callable must be used as "
  627. "Callable[[arg, ...], result].")
  628. args, result = params
  629. if args is Ellipsis:
  630. params = (Ellipsis, result)
  631. else:
  632. if not isinstance(args, list):
  633. raise TypeError(f"Callable[args, result]: args must be a list."
  634. f" Got {args}")
  635. params = (tuple(args), result)
  636. return self.__getitem_inner__(params)
  637. @_tp_cache
  638. def __getitem_inner__(self, params):
  639. if self.__origin__ is tuple and self._special:
  640. if params == ():
  641. return self.copy_with((_TypingEmpty,))
  642. if not isinstance(params, tuple):
  643. params = (params,)
  644. if len(params) == 2 and params[1] is ...:
  645. msg = "Tuple[t, ...]: t must be a type."
  646. p = _type_check(params[0], msg)
  647. return self.copy_with((p, _TypingEllipsis))
  648. msg = "Tuple[t0, t1, ...]: each t must be a type."
  649. params = tuple(_type_check(p, msg) for p in params)
  650. return self.copy_with(params)
  651. if self.__origin__ is collections.abc.Callable and self._special:
  652. args, result = params
  653. msg = "Callable[args, result]: result must be a type."
  654. result = _type_check(result, msg)
  655. if args is Ellipsis:
  656. return self.copy_with((_TypingEllipsis, result))
  657. msg = "Callable[[arg, ...], result]: each arg must be a type."
  658. args = tuple(_type_check(arg, msg) for arg in args)
  659. params = args + (result,)
  660. return self.copy_with(params)
  661. return super().__getitem__(params)
  662. class Generic:
  663. """Abstract base class for generic types.
  664. A generic type is typically declared by inheriting from
  665. this class parameterized with one or more type variables.
  666. For example, a generic mapping type might be defined as::
  667. class Mapping(Generic[KT, VT]):
  668. def __getitem__(self, key: KT) -> VT:
  669. ...
  670. # Etc.
  671. This class can then be used as follows::
  672. def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
  673. try:
  674. return mapping[key]
  675. except KeyError:
  676. return default
  677. """
  678. __slots__ = ()
  679. def __new__(cls, *args, **kwds):
  680. if cls is Generic:
  681. raise TypeError("Type Generic cannot be instantiated; "
  682. "it can be used only as a base class")
  683. if super().__new__ is object.__new__ and cls.__init__ is not object.__init__:
  684. obj = super().__new__(cls)
  685. else:
  686. obj = super().__new__(cls, *args, **kwds)
  687. return obj
  688. @_tp_cache
  689. def __class_getitem__(cls, params):
  690. if not isinstance(params, tuple):
  691. params = (params,)
  692. if not params and cls is not Tuple:
  693. raise TypeError(
  694. f"Parameter list to {cls.__qualname__}[...] cannot be empty")
  695. msg = "Parameters to generic types must be types."
  696. params = tuple(_type_check(p, msg) for p in params)
  697. if cls is Generic:
  698. # Generic can only be subscripted with unique type variables.
  699. if not all(isinstance(p, TypeVar) for p in params):
  700. raise TypeError(
  701. "Parameters to Generic[...] must all be type variables")
  702. if len(set(params)) != len(params):
  703. raise TypeError(
  704. "Parameters to Generic[...] must all be unique")
  705. elif cls is _Protocol:
  706. # _Protocol is internal at the moment, just skip the check
  707. pass
  708. else:
  709. # Subscripting a regular Generic subclass.
  710. _check_generic(cls, params)
  711. return _GenericAlias(cls, params)
  712. def __init_subclass__(cls, *args, **kwargs):
  713. super().__init_subclass__(*args, **kwargs)
  714. tvars = []
  715. if '__orig_bases__' in cls.__dict__:
  716. error = Generic in cls.__orig_bases__
  717. else:
  718. error = Generic in cls.__bases__ and cls.__name__ != '_Protocol'
  719. if error:
  720. raise TypeError("Cannot inherit from plain Generic")
  721. if '__orig_bases__' in cls.__dict__:
  722. tvars = _collect_type_vars(cls.__orig_bases__)
  723. # Look for Generic[T1, ..., Tn].
  724. # If found, tvars must be a subset of it.
  725. # If not found, tvars is it.
  726. # Also check for and reject plain Generic,
  727. # and reject multiple Generic[...].
  728. gvars = None
  729. for base in cls.__orig_bases__:
  730. if (isinstance(base, _GenericAlias) and
  731. base.__origin__ is Generic):
  732. if gvars is not None:
  733. raise TypeError(
  734. "Cannot inherit from Generic[...] multiple types.")
  735. gvars = base.__parameters__
  736. if gvars is None:
  737. gvars = tvars
  738. else:
  739. tvarset = set(tvars)
  740. gvarset = set(gvars)
  741. if not tvarset <= gvarset:
  742. s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)
  743. s_args = ', '.join(str(g) for g in gvars)
  744. raise TypeError(f"Some type variables ({s_vars}) are"
  745. f" not listed in Generic[{s_args}]")
  746. tvars = gvars
  747. cls.__parameters__ = tuple(tvars)
  748. class _TypingEmpty:
  749. """Internal placeholder for () or []. Used by TupleMeta and CallableMeta
  750. to allow empty list/tuple in specific places, without allowing them
  751. to sneak in where prohibited.
  752. """
  753. class _TypingEllipsis:
  754. """Internal placeholder for ... (ellipsis)."""
  755. def cast(typ, val):
  756. """Cast a value to a type.
  757. This returns the value unchanged. To the type checker this
  758. signals that the return value has the designated type, but at
  759. runtime we intentionally don't check anything (we want this
  760. to be as fast as possible).
  761. """
  762. return val
  763. def _get_defaults(func):
  764. """Internal helper to extract the default arguments, by name."""
  765. try:
  766. code = func.__code__
  767. except AttributeError:
  768. # Some built-in functions don't have __code__, __defaults__, etc.
  769. return {}
  770. pos_count = code.co_argcount
  771. arg_names = code.co_varnames
  772. arg_names = arg_names[:pos_count]
  773. defaults = func.__defaults__ or ()
  774. kwdefaults = func.__kwdefaults__
  775. res = dict(kwdefaults) if kwdefaults else {}
  776. pos_offset = pos_count - len(defaults)
  777. for name, value in zip(arg_names[pos_offset:], defaults):
  778. assert name not in res
  779. res[name] = value
  780. return res
  781. _allowed_types = (types.FunctionType, types.BuiltinFunctionType,
  782. types.MethodType, types.ModuleType,
  783. WrapperDescriptorType, MethodWrapperType, MethodDescriptorType)
  784. def get_type_hints(obj, globalns=None, localns=None):
  785. """Return type hints for an object.
  786. This is often the same as obj.__annotations__, but it handles
  787. forward references encoded as string literals, and if necessary
  788. adds Optional[t] if a default value equal to None is set.
  789. The argument may be a module, class, method, or function. The annotations
  790. are returned as a dictionary. For classes, annotations include also
  791. inherited members.
  792. TypeError is raised if the argument is not of a type that can contain
  793. annotations, and an empty dictionary is returned if no annotations are
  794. present.
  795. BEWARE -- the behavior of globalns and localns is counterintuitive
  796. (unless you are familiar with how eval() and exec() work). The
  797. search order is locals first, then globals.
  798. - If no dict arguments are passed, an attempt is made to use the
  799. globals from obj (or the respective module's globals for classes),
  800. and these are also used as the locals. If the object does not appear
  801. to have globals, an empty dictionary is used.
  802. - If one dict argument is passed, it is used for both globals and
  803. locals.
  804. - If two dict arguments are passed, they specify globals and
  805. locals, respectively.
  806. """
  807. if getattr(obj, '__no_type_check__', None):
  808. return {}
  809. # Classes require a special treatment.
  810. if isinstance(obj, type):
  811. hints = {}
  812. for base in reversed(obj.__mro__):
  813. if globalns is None:
  814. base_globals = sys.modules[base.__module__].__dict__
  815. else:
  816. base_globals = globalns
  817. ann = base.__dict__.get('__annotations__', {})
  818. for name, value in ann.items():
  819. if value is None:
  820. value = type(None)
  821. if isinstance(value, str):
  822. value = ForwardRef(value, is_argument=False)
  823. value = _eval_type(value, base_globals, localns)
  824. hints[name] = value
  825. return hints
  826. if globalns is None:
  827. if isinstance(obj, types.ModuleType):
  828. globalns = obj.__dict__
  829. else:
  830. nsobj = obj
  831. # Find globalns for the unwrapped object.
  832. while hasattr(nsobj, '__wrapped__'):
  833. nsobj = nsobj.__wrapped__
  834. globalns = getattr(nsobj, '__globals__', {})
  835. if localns is None:
  836. localns = globalns
  837. elif localns is None:
  838. localns = globalns
  839. hints = getattr(obj, '__annotations__', None)
  840. if hints is None:
  841. # Return empty annotations for something that _could_ have them.
  842. if isinstance(obj, _allowed_types):
  843. return {}
  844. else:
  845. raise TypeError('{!r} is not a module, class, method, '
  846. 'or function.'.format(obj))
  847. defaults = _get_defaults(obj)
  848. hints = dict(hints)
  849. for name, value in hints.items():
  850. if value is None:
  851. value = type(None)
  852. if isinstance(value, str):
  853. value = ForwardRef(value)
  854. value = _eval_type(value, globalns, localns)
  855. if name in defaults and defaults[name] is None:
  856. value = Optional[value]
  857. hints[name] = value
  858. return hints
  859. def no_type_check(arg):
  860. """Decorator to indicate that annotations are not type hints.
  861. The argument must be a class or function; if it is a class, it
  862. applies recursively to all methods and classes defined in that class
  863. (but not to methods defined in its superclasses or subclasses).
  864. This mutates the function(s) or class(es) in place.
  865. """
  866. if isinstance(arg, type):
  867. arg_attrs = arg.__dict__.copy()
  868. for attr, val in arg.__dict__.items():
  869. if val in arg.__bases__ + (arg,):
  870. arg_attrs.pop(attr)
  871. for obj in arg_attrs.values():
  872. if isinstance(obj, types.FunctionType):
  873. obj.__no_type_check__ = True
  874. if isinstance(obj, type):
  875. no_type_check(obj)
  876. try:
  877. arg.__no_type_check__ = True
  878. except TypeError: # built-in classes
  879. pass
  880. return arg
  881. def no_type_check_decorator(decorator):
  882. """Decorator to give another decorator the @no_type_check effect.
  883. This wraps the decorator with something that wraps the decorated
  884. function in @no_type_check.
  885. """
  886. @functools.wraps(decorator)
  887. def wrapped_decorator(*args, **kwds):
  888. func = decorator(*args, **kwds)
  889. func = no_type_check(func)
  890. return func
  891. return wrapped_decorator
  892. def _overload_dummy(*args, **kwds):
  893. """Helper for @overload to raise when called."""
  894. raise NotImplementedError(
  895. "You should not call an overloaded function. "
  896. "A series of @overload-decorated functions "
  897. "outside a stub module should always be followed "
  898. "by an implementation that is not @overload-ed.")
  899. def overload(func):
  900. """Decorator for overloaded functions/methods.
  901. In a stub file, place two or more stub definitions for the same
  902. function in a row, each decorated with @overload. For example:
  903. @overload
  904. def utf8(value: None) -> None: ...
  905. @overload
  906. def utf8(value: bytes) -> bytes: ...
  907. @overload
  908. def utf8(value: str) -> bytes: ...
  909. In a non-stub file (i.e. a regular .py file), do the same but
  910. follow it with an implementation. The implementation should *not*
  911. be decorated with @overload. For example:
  912. @overload
  913. def utf8(value: None) -> None: ...
  914. @overload
  915. def utf8(value: bytes) -> bytes: ...
  916. @overload
  917. def utf8(value: str) -> bytes: ...
  918. def utf8(value):
  919. # implementation goes here
  920. """
  921. return _overload_dummy
  922. class _ProtocolMeta(type):
  923. """Internal metaclass for _Protocol.
  924. This exists so _Protocol classes can be generic without deriving
  925. from Generic.
  926. """
  927. def __instancecheck__(self, obj):
  928. if _Protocol not in self.__bases__:
  929. return super().__instancecheck__(obj)
  930. raise TypeError("Protocols cannot be used with isinstance().")
  931. def __subclasscheck__(self, cls):
  932. if not self._is_protocol:
  933. # No structural checks since this isn't a protocol.
  934. return NotImplemented
  935. if self is _Protocol:
  936. # Every class is a subclass of the empty protocol.
  937. return True
  938. # Find all attributes defined in the protocol.
  939. attrs = self._get_protocol_attrs()
  940. for attr in attrs:
  941. if not any(attr in d.__dict__ for d in cls.__mro__):
  942. return False
  943. return True
  944. def _get_protocol_attrs(self):
  945. # Get all Protocol base classes.
  946. protocol_bases = []
  947. for c in self.__mro__:
  948. if getattr(c, '_is_protocol', False) and c.__name__ != '_Protocol':
  949. protocol_bases.append(c)
  950. # Get attributes included in protocol.
  951. attrs = set()
  952. for base in protocol_bases:
  953. for attr in base.__dict__.keys():
  954. # Include attributes not defined in any non-protocol bases.
  955. for c in self.__mro__:
  956. if (c is not base and attr in c.__dict__ and
  957. not getattr(c, '_is_protocol', False)):
  958. break
  959. else:
  960. if (not attr.startswith('_abc_') and
  961. attr != '__abstractmethods__' and
  962. attr != '__annotations__' and
  963. attr != '__weakref__' and
  964. attr != '_is_protocol' and
  965. attr != '_gorg' and
  966. attr != '__dict__' and
  967. attr != '__args__' and
  968. attr != '__slots__' and
  969. attr != '_get_protocol_attrs' and
  970. attr != '__next_in_mro__' and
  971. attr != '__parameters__' and
  972. attr != '__origin__' and
  973. attr != '__orig_bases__' and
  974. attr != '__extra__' and
  975. attr != '__tree_hash__' and
  976. attr != '__module__'):
  977. attrs.add(attr)
  978. return attrs
  979. class _Protocol(Generic, metaclass=_ProtocolMeta):
  980. """Internal base class for protocol classes.
  981. This implements a simple-minded structural issubclass check
  982. (similar but more general than the one-offs in collections.abc
  983. such as Hashable).
  984. """
  985. __slots__ = ()
  986. _is_protocol = True
  987. def __class_getitem__(cls, params):
  988. return super().__class_getitem__(params)
  989. # Some unconstrained type variables. These are used by the container types.
  990. # (These are not for export.)
  991. T = TypeVar('T') # Any type.
  992. KT = TypeVar('KT') # Key type.
  993. VT = TypeVar('VT') # Value type.
  994. T_co = TypeVar('T_co', covariant=True) # Any type covariant containers.
  995. V_co = TypeVar('V_co', covariant=True) # Any type covariant containers.
  996. VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
  997. T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
  998. # Internal type variable used for Type[].
  999. CT_co = TypeVar('CT_co', covariant=True, bound=type)
  1000. # A useful type variable with constraints. This represents string types.
  1001. # (This one *is* for export!)
  1002. AnyStr = TypeVar('AnyStr', bytes, str)
  1003. # Various ABCs mimicking those in collections.abc.
  1004. def _alias(origin, params, inst=True):
  1005. return _GenericAlias(origin, params, special=True, inst=inst)
  1006. Hashable = _alias(collections.abc.Hashable, ()) # Not generic.
  1007. Awaitable = _alias(collections.abc.Awaitable, T_co)
  1008. Coroutine = _alias(collections.abc.Coroutine, (T_co, T_contra, V_co))
  1009. AsyncIterable = _alias(collections.abc.AsyncIterable, T_co)
  1010. AsyncIterator = _alias(collections.abc.AsyncIterator, T_co)
  1011. Iterable = _alias(collections.abc.Iterable, T_co)
  1012. Iterator = _alias(collections.abc.Iterator, T_co)
  1013. Reversible = _alias(collections.abc.Reversible, T_co)
  1014. Sized = _alias(collections.abc.Sized, ()) # Not generic.
  1015. Container = _alias(collections.abc.Container, T_co)
  1016. Collection = _alias(collections.abc.Collection, T_co)
  1017. Callable = _VariadicGenericAlias(collections.abc.Callable, (), special=True)
  1018. Callable.__doc__ = \
  1019. """Callable type; Callable[[int], str] is a function of (int) -> str.
  1020. The subscription syntax must always be used with exactly two
  1021. values: the argument list and the return type. The argument list
  1022. must be a list of types or ellipsis; the return type must be a single type.
  1023. There is no syntax to indicate optional or keyword arguments,
  1024. such function types are rarely used as callback types.
  1025. """
  1026. AbstractSet = _alias(collections.abc.Set, T_co)
  1027. MutableSet = _alias(collections.abc.MutableSet, T)
  1028. # NOTE: Mapping is only covariant in the value type.
  1029. Mapping = _alias(collections.abc.Mapping, (KT, VT_co))
  1030. MutableMapping = _alias(collections.abc.MutableMapping, (KT, VT))
  1031. Sequence = _alias(collections.abc.Sequence, T_co)
  1032. MutableSequence = _alias(collections.abc.MutableSequence, T)
  1033. ByteString = _alias(collections.abc.ByteString, ()) # Not generic
  1034. Tuple = _VariadicGenericAlias(tuple, (), inst=False, special=True)
  1035. Tuple.__doc__ = \
  1036. """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
  1037. Example: Tuple[T1, T2] is a tuple of two elements corresponding
  1038. to type variables T1 and T2. Tuple[int, float, str] is a tuple
  1039. of an int, a float and a string.
  1040. To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
  1041. """
  1042. List = _alias(list, T, inst=False)
  1043. Deque = _alias(collections.deque, T)
  1044. Set = _alias(set, T, inst=False)
  1045. FrozenSet = _alias(frozenset, T_co, inst=False)
  1046. MappingView = _alias(collections.abc.MappingView, T_co)
  1047. KeysView = _alias(collections.abc.KeysView, KT)
  1048. ItemsView = _alias(collections.abc.ItemsView, (KT, VT_co))
  1049. ValuesView = _alias(collections.abc.ValuesView, VT_co)
  1050. ContextManager = _alias(contextlib.AbstractContextManager, T_co)
  1051. AsyncContextManager = _alias(contextlib.AbstractAsyncContextManager, T_co)
  1052. Dict = _alias(dict, (KT, VT), inst=False)
  1053. DefaultDict = _alias(collections.defaultdict, (KT, VT))
  1054. OrderedDict = _alias(collections.OrderedDict, (KT, VT))
  1055. Counter = _alias(collections.Counter, T)
  1056. ChainMap = _alias(collections.ChainMap, (KT, VT))
  1057. Generator = _alias(collections.abc.Generator, (T_co, T_contra, V_co))
  1058. AsyncGenerator = _alias(collections.abc.AsyncGenerator, (T_co, T_contra))
  1059. Type = _alias(type, CT_co, inst=False)
  1060. Type.__doc__ = \
  1061. """A special construct usable to annotate class objects.
  1062. For example, suppose we have the following classes::
  1063. class User: ... # Abstract base for User classes
  1064. class BasicUser(User): ...
  1065. class ProUser(User): ...
  1066. class TeamUser(User): ...
  1067. And a function that takes a class argument that's a subclass of
  1068. User and returns an instance of the corresponding class::
  1069. U = TypeVar('U', bound=User)
  1070. def new_user(user_class: Type[U]) -> U:
  1071. user = user_class()
  1072. # (Here we could write the user object to a database)
  1073. return user
  1074. joe = new_user(BasicUser)
  1075. At this point the type checker knows that joe has type BasicUser.
  1076. """
  1077. class SupportsInt(_Protocol):
  1078. """An ABC with one abstract method __int__."""
  1079. __slots__ = ()
  1080. @abstractmethod
  1081. def __int__(self) -> int:
  1082. pass
  1083. class SupportsFloat(_Protocol):
  1084. """An ABC with one abstract method __float__."""
  1085. __slots__ = ()
  1086. @abstractmethod
  1087. def __float__(self) -> float:
  1088. pass
  1089. class SupportsComplex(_Protocol):
  1090. """An ABC with one abstract method __complex__."""
  1091. __slots__ = ()
  1092. @abstractmethod
  1093. def __complex__(self) -> complex:
  1094. pass
  1095. class SupportsBytes(_Protocol):
  1096. """An ABC with one abstract method __bytes__."""
  1097. __slots__ = ()
  1098. @abstractmethod
  1099. def __bytes__(self) -> bytes:
  1100. pass
  1101. class SupportsAbs(_Protocol[T_co]):
  1102. """An ABC with one abstract method __abs__ that is covariant in its return type."""
  1103. __slots__ = ()
  1104. @abstractmethod
  1105. def __abs__(self) -> T_co:
  1106. pass
  1107. class SupportsRound(_Protocol[T_co]):
  1108. """An ABC with one abstract method __round__ that is covariant in its return type."""
  1109. __slots__ = ()
  1110. @abstractmethod
  1111. def __round__(self, ndigits: int = 0) -> T_co:
  1112. pass
  1113. def _make_nmtuple(name, types):
  1114. msg = "NamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a type"
  1115. types = [(n, _type_check(t, msg)) for n, t in types]
  1116. nm_tpl = collections.namedtuple(name, [n for n, t in types])
  1117. # Prior to PEP 526, only _field_types attribute was assigned.
  1118. # Now, both __annotations__ and _field_types are used to maintain compatibility.
  1119. nm_tpl.__annotations__ = nm_tpl._field_types = collections.OrderedDict(types)
  1120. try:
  1121. nm_tpl.__module__ = sys._getframe(2).f_globals.get('__name__', '__main__')
  1122. except (AttributeError, ValueError):
  1123. pass
  1124. return nm_tpl
  1125. # attributes prohibited to set in NamedTuple class syntax
  1126. _prohibited = ('__new__', '__init__', '__slots__', '__getnewargs__',
  1127. '_fields', '_field_defaults', '_field_types',
  1128. '_make', '_replace', '_asdict', '_source')
  1129. _special = ('__module__', '__name__', '__annotations__')
  1130. class NamedTupleMeta(type):
  1131. def __new__(cls, typename, bases, ns):
  1132. if ns.get('_root', False):
  1133. return super().__new__(cls, typename, bases, ns)
  1134. types = ns.get('__annotations__', {})
  1135. nm_tpl = _make_nmtuple(typename, types.items())
  1136. defaults = []
  1137. defaults_dict = {}
  1138. for field_name in types:
  1139. if field_name in ns:
  1140. default_value = ns[field_name]
  1141. defaults.append(default_value)
  1142. defaults_dict[field_name] = default_value
  1143. elif defaults:
  1144. raise TypeError("Non-default namedtuple field {field_name} cannot "
  1145. "follow default field(s) {default_names}"
  1146. .format(field_name=field_name,
  1147. default_names=', '.join(defaults_dict.keys())))
  1148. nm_tpl.__new__.__annotations__ = collections.OrderedDict(types)
  1149. nm_tpl.__new__.__defaults__ = tuple(defaults)
  1150. nm_tpl._field_defaults = defaults_dict
  1151. # update from user namespace without overriding special namedtuple attributes
  1152. for key in ns:
  1153. if key in _prohibited:
  1154. raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
  1155. elif key not in _special and key not in nm_tpl._fields:
  1156. setattr(nm_tpl, key, ns[key])
  1157. return nm_tpl
  1158. class NamedTuple(metaclass=NamedTupleMeta):
  1159. """Typed version of namedtuple.
  1160. Usage in Python versions >= 3.6::
  1161. class Employee(NamedTuple):
  1162. name: str
  1163. id: int
  1164. This is equivalent to::
  1165. Employee = collections.namedtuple('Employee', ['name', 'id'])
  1166. The resulting class has extra __annotations__ and _field_types
  1167. attributes, giving an ordered dict mapping field names to types.
  1168. __annotations__ should be preferred, while _field_types
  1169. is kept to maintain pre PEP 526 compatibility. (The field names
  1170. are in the _fields attribute, which is part of the namedtuple
  1171. API.) Alternative equivalent keyword syntax is also accepted::
  1172. Employee = NamedTuple('Employee', name=str, id=int)
  1173. In Python versions <= 3.5 use::
  1174. Employee = NamedTuple('Employee', [('name', str), ('id', int)])
  1175. """
  1176. _root = True
  1177. def __new__(*args, **kwargs):
  1178. if not args:
  1179. raise TypeError('NamedTuple.__new__(): not enough arguments')
  1180. cls, *args = args # allow the "cls" keyword be passed
  1181. if args:
  1182. typename, *args = args # allow the "typename" keyword be passed
  1183. elif 'typename' in kwargs:
  1184. typename = kwargs.pop('typename')
  1185. else:
  1186. raise TypeError("NamedTuple.__new__() missing 1 required positional "
  1187. "argument: 'typename'")
  1188. if args:
  1189. try:
  1190. fields, = args # allow the "fields" keyword be passed
  1191. except ValueError:
  1192. raise TypeError(f'NamedTuple.__new__() takes from 2 to 3 '
  1193. f'positional arguments but {len(args) + 2} '
  1194. f'were given') from None
  1195. elif 'fields' in kwargs and len(kwargs) == 1:
  1196. fields = kwargs.pop('fields')
  1197. else:
  1198. fields = None
  1199. if fields is None:
  1200. fields = kwargs.items()
  1201. elif kwargs:
  1202. raise TypeError("Either list of fields or keywords"
  1203. " can be provided to NamedTuple, not both")
  1204. return _make_nmtuple(typename, fields)
  1205. __new__.__text_signature__ = '($cls, typename, fields=None, /, **kwargs)'
  1206. def NewType(name, tp):
  1207. """NewType creates simple unique types with almost zero
  1208. runtime overhead. NewType(name, tp) is considered a subtype of tp
  1209. by static type checkers. At runtime, NewType(name, tp) returns
  1210. a dummy function that simply returns its argument. Usage::
  1211. UserId = NewType('UserId', int)
  1212. def name_by_id(user_id: UserId) -> str:
  1213. ...
  1214. UserId('user') # Fails type check
  1215. name_by_id(42) # Fails type check
  1216. name_by_id(UserId(42)) # OK
  1217. num = UserId(5) + 1 # type: int
  1218. """
  1219. def new_type(x):
  1220. return x
  1221. new_type.__name__ = name
  1222. new_type.__supertype__ = tp
  1223. return new_type
  1224. # Python-version-specific alias (Python 2: unicode; Python 3: str)
  1225. Text = str
  1226. # Constant that's True when type checking, but False here.
  1227. TYPE_CHECKING = False
  1228. class IO(Generic[AnyStr]):
  1229. """Generic base class for TextIO and BinaryIO.
  1230. This is an abstract, generic version of the return of open().
  1231. NOTE: This does not distinguish between the different possible
  1232. classes (text vs. binary, read vs. write vs. read/write,
  1233. append-only, unbuffered). The TextIO and BinaryIO subclasses
  1234. below capture the distinctions between text vs. binary, which is
  1235. pervasive in the interface; however we currently do not offer a
  1236. way to track the other distinctions in the type system.
  1237. """
  1238. __slots__ = ()
  1239. @abstractproperty
  1240. def mode(self) -> str:
  1241. pass
  1242. @abstractproperty
  1243. def name(self) -> str:
  1244. pass
  1245. @abstractmethod
  1246. def close(self) -> None:
  1247. pass
  1248. @abstractproperty
  1249. def closed(self) -> bool:
  1250. pass
  1251. @abstractmethod
  1252. def fileno(self) -> int:
  1253. pass
  1254. @abstractmethod
  1255. def flush(self) -> None:
  1256. pass
  1257. @abstractmethod
  1258. def isatty(self) -> bool:
  1259. pass
  1260. @abstractmethod
  1261. def read(self, n: int = -1) -> AnyStr:
  1262. pass
  1263. @abstractmethod
  1264. def readable(self) -> bool:
  1265. pass
  1266. @abstractmethod
  1267. def readline(self, limit: int = -1) -> AnyStr:
  1268. pass
  1269. @abstractmethod
  1270. def readlines(self, hint: int = -1) -> List[AnyStr]:
  1271. pass
  1272. @abstractmethod
  1273. def seek(self, offset: int, whence: int = 0) -> int:
  1274. pass
  1275. @abstractmethod
  1276. def seekable(self) -> bool:
  1277. pass
  1278. @abstractmethod
  1279. def tell(self) -> int:
  1280. pass
  1281. @abstractmethod
  1282. def truncate(self, size: int = None) -> int:
  1283. pass
  1284. @abstractmethod
  1285. def writable(self) -> bool:
  1286. pass
  1287. @abstractmethod
  1288. def write(self, s: AnyStr) -> int:
  1289. pass
  1290. @abstractmethod
  1291. def writelines(self, lines: List[AnyStr]) -> None:
  1292. pass
  1293. @abstractmethod
  1294. def __enter__(self) -> 'IO[AnyStr]':
  1295. pass
  1296. @abstractmethod
  1297. def __exit__(self, type, value, traceback) -> None:
  1298. pass
  1299. class BinaryIO(IO[bytes]):
  1300. """Typed version of the return of open() in binary mode."""
  1301. __slots__ = ()
  1302. @abstractmethod
  1303. def write(self, s: Union[bytes, bytearray]) -> int:
  1304. pass
  1305. @abstractmethod
  1306. def __enter__(self) -> 'BinaryIO':
  1307. pass
  1308. class TextIO(IO[str]):
  1309. """Typed version of the return of open() in text mode."""
  1310. __slots__ = ()
  1311. @abstractproperty
  1312. def buffer(self) -> BinaryIO:
  1313. pass
  1314. @abstractproperty
  1315. def encoding(self) -> str:
  1316. pass
  1317. @abstractproperty
  1318. def errors(self) -> Optional[str]:
  1319. pass
  1320. @abstractproperty
  1321. def line_buffering(self) -> bool:
  1322. pass
  1323. @abstractproperty
  1324. def newlines(self) -> Any:
  1325. pass
  1326. @abstractmethod
  1327. def __enter__(self) -> 'TextIO':
  1328. pass
  1329. class io:
  1330. """Wrapper namespace for IO generic classes."""
  1331. __all__ = ['IO', 'TextIO', 'BinaryIO']
  1332. IO = IO
  1333. TextIO = TextIO
  1334. BinaryIO = BinaryIO
  1335. io.__name__ = __name__ + '.io'
  1336. sys.modules[io.__name__] = io
  1337. Pattern = _alias(stdlib_re.Pattern, AnyStr)
  1338. Match = _alias(stdlib_re.Match, AnyStr)
  1339. class re:
  1340. """Wrapper namespace for re type aliases."""
  1341. __all__ = ['Pattern', 'Match']
  1342. Pattern = Pattern
  1343. Match = Match
  1344. re.__name__ = __name__ + '.re'
  1345. sys.modules[re.__name__] = re