typing.py 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651
  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. def_mod = sys._getframe(1).f_globals['__name__'] # for pickling
  451. if def_mod != 'typing':
  452. self.__module__ = def_mod
  453. def __repr__(self):
  454. if self.__covariant__:
  455. prefix = '+'
  456. elif self.__contravariant__:
  457. prefix = '-'
  458. else:
  459. prefix = '~'
  460. return prefix + self.__name__
  461. def __reduce__(self):
  462. return self.__name__
  463. # Special typing constructs Union, Optional, Generic, Callable and Tuple
  464. # use three special attributes for internal bookkeeping of generic types:
  465. # * __parameters__ is a tuple of unique free type parameters of a generic
  466. # type, for example, Dict[T, T].__parameters__ == (T,);
  467. # * __origin__ keeps a reference to a type that was subscripted,
  468. # e.g., Union[T, int].__origin__ == Union, or the non-generic version of
  469. # the type.
  470. # * __args__ is a tuple of all arguments used in subscripting,
  471. # e.g., Dict[T, int].__args__ == (T, int).
  472. # Mapping from non-generic type names that have a generic alias in typing
  473. # but with a different name.
  474. _normalize_alias = {'list': 'List',
  475. 'tuple': 'Tuple',
  476. 'dict': 'Dict',
  477. 'set': 'Set',
  478. 'frozenset': 'FrozenSet',
  479. 'deque': 'Deque',
  480. 'defaultdict': 'DefaultDict',
  481. 'type': 'Type',
  482. 'Set': 'AbstractSet'}
  483. def _is_dunder(attr):
  484. return attr.startswith('__') and attr.endswith('__')
  485. class _GenericAlias(_Final, _root=True):
  486. """The central part of internal API.
  487. This represents a generic version of type 'origin' with type arguments 'params'.
  488. There are two kind of these aliases: user defined and special. The special ones
  489. are wrappers around builtin collections and ABCs in collections.abc. These must
  490. have 'name' always set. If 'inst' is False, then the alias can't be instantiated,
  491. this is used by e.g. typing.List and typing.Dict.
  492. """
  493. def __init__(self, origin, params, *, inst=True, special=False, name=None):
  494. self._inst = inst
  495. self._special = special
  496. if special and name is None:
  497. orig_name = origin.__name__
  498. name = _normalize_alias.get(orig_name, orig_name)
  499. self._name = name
  500. if not isinstance(params, tuple):
  501. params = (params,)
  502. self.__origin__ = origin
  503. self.__args__ = tuple(... if a is _TypingEllipsis else
  504. () if a is _TypingEmpty else
  505. a for a in params)
  506. self.__parameters__ = _collect_type_vars(params)
  507. self.__slots__ = None # This is not documented.
  508. if not name:
  509. self.__module__ = origin.__module__
  510. @_tp_cache
  511. def __getitem__(self, params):
  512. if self.__origin__ in (Generic, _Protocol):
  513. # Can't subscript Generic[...] or _Protocol[...].
  514. raise TypeError(f"Cannot subscript already-subscripted {self}")
  515. if not isinstance(params, tuple):
  516. params = (params,)
  517. msg = "Parameters to generic types must be types."
  518. params = tuple(_type_check(p, msg) for p in params)
  519. _check_generic(self, params)
  520. return _subs_tvars(self, self.__parameters__, params)
  521. def copy_with(self, params):
  522. # We don't copy self._special.
  523. return _GenericAlias(self.__origin__, params, name=self._name, inst=self._inst)
  524. def __repr__(self):
  525. if (self._name != 'Callable' or
  526. len(self.__args__) == 2 and self.__args__[0] is Ellipsis):
  527. if self._name:
  528. name = 'typing.' + self._name
  529. else:
  530. name = _type_repr(self.__origin__)
  531. if not self._special:
  532. args = f'[{", ".join([_type_repr(a) for a in self.__args__])}]'
  533. else:
  534. args = ''
  535. return (f'{name}{args}')
  536. if self._special:
  537. return 'typing.Callable'
  538. return (f'typing.Callable'
  539. f'[[{", ".join([_type_repr(a) for a in self.__args__[:-1]])}], '
  540. f'{_type_repr(self.__args__[-1])}]')
  541. def __eq__(self, other):
  542. if not isinstance(other, _GenericAlias):
  543. return NotImplemented
  544. if self.__origin__ != other.__origin__:
  545. return False
  546. if self.__origin__ is Union and other.__origin__ is Union:
  547. return frozenset(self.__args__) == frozenset(other.__args__)
  548. return self.__args__ == other.__args__
  549. def __hash__(self):
  550. if self.__origin__ is Union:
  551. return hash((Union, frozenset(self.__args__)))
  552. return hash((self.__origin__, self.__args__))
  553. def __call__(self, *args, **kwargs):
  554. if not self._inst:
  555. raise TypeError(f"Type {self._name} cannot be instantiated; "
  556. f"use {self._name.lower()}() instead")
  557. result = self.__origin__(*args, **kwargs)
  558. try:
  559. result.__orig_class__ = self
  560. except AttributeError:
  561. pass
  562. return result
  563. def __mro_entries__(self, bases):
  564. if self._name: # generic version of an ABC or built-in class
  565. res = []
  566. if self.__origin__ not in bases:
  567. res.append(self.__origin__)
  568. i = bases.index(self)
  569. if not any(isinstance(b, _GenericAlias) or issubclass(b, Generic)
  570. for b in bases[i+1:]):
  571. res.append(Generic)
  572. return tuple(res)
  573. if self.__origin__ is Generic:
  574. i = bases.index(self)
  575. for b in bases[i+1:]:
  576. if isinstance(b, _GenericAlias) and b is not self:
  577. return ()
  578. return (self.__origin__,)
  579. def __getattr__(self, attr):
  580. # We are careful for copy and pickle.
  581. # Also for simplicity we just don't relay all dunder names
  582. if '__origin__' in self.__dict__ and not _is_dunder(attr):
  583. return getattr(self.__origin__, attr)
  584. raise AttributeError(attr)
  585. def __setattr__(self, attr, val):
  586. if _is_dunder(attr) or attr in ('_name', '_inst', '_special'):
  587. super().__setattr__(attr, val)
  588. else:
  589. setattr(self.__origin__, attr, val)
  590. def __instancecheck__(self, obj):
  591. return self.__subclasscheck__(type(obj))
  592. def __subclasscheck__(self, cls):
  593. if self._special:
  594. if not isinstance(cls, _GenericAlias):
  595. return issubclass(cls, self.__origin__)
  596. if cls._special:
  597. return issubclass(cls.__origin__, self.__origin__)
  598. raise TypeError("Subscripted generics cannot be used with"
  599. " class and instance checks")
  600. def __reduce__(self):
  601. if self._special:
  602. return self._name
  603. if self._name:
  604. origin = globals()[self._name]
  605. else:
  606. origin = self.__origin__
  607. if (origin is Callable and
  608. not (len(self.__args__) == 2 and self.__args__[0] is Ellipsis)):
  609. args = list(self.__args__[:-1]), self.__args__[-1]
  610. else:
  611. args = tuple(self.__args__)
  612. if len(args) == 1 and not isinstance(args[0], tuple):
  613. args, = args
  614. return operator.getitem, (origin, args)
  615. class _VariadicGenericAlias(_GenericAlias, _root=True):
  616. """Same as _GenericAlias above but for variadic aliases. Currently,
  617. this is used only by special internal aliases: Tuple and Callable.
  618. """
  619. def __getitem__(self, params):
  620. if self._name != 'Callable' or not self._special:
  621. return self.__getitem_inner__(params)
  622. if not isinstance(params, tuple) or len(params) != 2:
  623. raise TypeError("Callable must be used as "
  624. "Callable[[arg, ...], result].")
  625. args, result = params
  626. if args is Ellipsis:
  627. params = (Ellipsis, result)
  628. else:
  629. if not isinstance(args, list):
  630. raise TypeError(f"Callable[args, result]: args must be a list."
  631. f" Got {args}")
  632. params = (tuple(args), result)
  633. return self.__getitem_inner__(params)
  634. @_tp_cache
  635. def __getitem_inner__(self, params):
  636. if self.__origin__ is tuple and self._special:
  637. if params == ():
  638. return self.copy_with((_TypingEmpty,))
  639. if not isinstance(params, tuple):
  640. params = (params,)
  641. if len(params) == 2 and params[1] is ...:
  642. msg = "Tuple[t, ...]: t must be a type."
  643. p = _type_check(params[0], msg)
  644. return self.copy_with((p, _TypingEllipsis))
  645. msg = "Tuple[t0, t1, ...]: each t must be a type."
  646. params = tuple(_type_check(p, msg) for p in params)
  647. return self.copy_with(params)
  648. if self.__origin__ is collections.abc.Callable and self._special:
  649. args, result = params
  650. msg = "Callable[args, result]: result must be a type."
  651. result = _type_check(result, msg)
  652. if args is Ellipsis:
  653. return self.copy_with((_TypingEllipsis, result))
  654. msg = "Callable[[arg, ...], result]: each arg must be a type."
  655. args = tuple(_type_check(arg, msg) for arg in args)
  656. params = args + (result,)
  657. return self.copy_with(params)
  658. return super().__getitem__(params)
  659. class Generic:
  660. """Abstract base class for generic types.
  661. A generic type is typically declared by inheriting from
  662. this class parameterized with one or more type variables.
  663. For example, a generic mapping type might be defined as::
  664. class Mapping(Generic[KT, VT]):
  665. def __getitem__(self, key: KT) -> VT:
  666. ...
  667. # Etc.
  668. This class can then be used as follows::
  669. def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
  670. try:
  671. return mapping[key]
  672. except KeyError:
  673. return default
  674. """
  675. __slots__ = ()
  676. def __new__(cls, *args, **kwds):
  677. if cls is Generic:
  678. raise TypeError("Type Generic cannot be instantiated; "
  679. "it can be used only as a base class")
  680. if super().__new__ is object.__new__ and cls.__init__ is not object.__init__:
  681. obj = super().__new__(cls)
  682. else:
  683. obj = super().__new__(cls, *args, **kwds)
  684. return obj
  685. @_tp_cache
  686. def __class_getitem__(cls, params):
  687. if not isinstance(params, tuple):
  688. params = (params,)
  689. if not params and cls is not Tuple:
  690. raise TypeError(
  691. f"Parameter list to {cls.__qualname__}[...] cannot be empty")
  692. msg = "Parameters to generic types must be types."
  693. params = tuple(_type_check(p, msg) for p in params)
  694. if cls is Generic:
  695. # Generic can only be subscripted with unique type variables.
  696. if not all(isinstance(p, TypeVar) for p in params):
  697. raise TypeError(
  698. "Parameters to Generic[...] must all be type variables")
  699. if len(set(params)) != len(params):
  700. raise TypeError(
  701. "Parameters to Generic[...] must all be unique")
  702. elif cls is _Protocol:
  703. # _Protocol is internal at the moment, just skip the check
  704. pass
  705. else:
  706. # Subscripting a regular Generic subclass.
  707. _check_generic(cls, params)
  708. return _GenericAlias(cls, params)
  709. def __init_subclass__(cls, *args, **kwargs):
  710. super().__init_subclass__(*args, **kwargs)
  711. tvars = []
  712. if '__orig_bases__' in cls.__dict__:
  713. error = Generic in cls.__orig_bases__
  714. else:
  715. error = Generic in cls.__bases__ and cls.__name__ != '_Protocol'
  716. if error:
  717. raise TypeError("Cannot inherit from plain Generic")
  718. if '__orig_bases__' in cls.__dict__:
  719. tvars = _collect_type_vars(cls.__orig_bases__)
  720. # Look for Generic[T1, ..., Tn].
  721. # If found, tvars must be a subset of it.
  722. # If not found, tvars is it.
  723. # Also check for and reject plain Generic,
  724. # and reject multiple Generic[...].
  725. gvars = None
  726. for base in cls.__orig_bases__:
  727. if (isinstance(base, _GenericAlias) and
  728. base.__origin__ is Generic):
  729. if gvars is not None:
  730. raise TypeError(
  731. "Cannot inherit from Generic[...] multiple types.")
  732. gvars = base.__parameters__
  733. if gvars is None:
  734. gvars = tvars
  735. else:
  736. tvarset = set(tvars)
  737. gvarset = set(gvars)
  738. if not tvarset <= gvarset:
  739. s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)
  740. s_args = ', '.join(str(g) for g in gvars)
  741. raise TypeError(f"Some type variables ({s_vars}) are"
  742. f" not listed in Generic[{s_args}]")
  743. tvars = gvars
  744. cls.__parameters__ = tuple(tvars)
  745. class _TypingEmpty:
  746. """Internal placeholder for () or []. Used by TupleMeta and CallableMeta
  747. to allow empty list/tuple in specific places, without allowing them
  748. to sneak in where prohibited.
  749. """
  750. class _TypingEllipsis:
  751. """Internal placeholder for ... (ellipsis)."""
  752. def cast(typ, val):
  753. """Cast a value to a type.
  754. This returns the value unchanged. To the type checker this
  755. signals that the return value has the designated type, but at
  756. runtime we intentionally don't check anything (we want this
  757. to be as fast as possible).
  758. """
  759. return val
  760. def _get_defaults(func):
  761. """Internal helper to extract the default arguments, by name."""
  762. try:
  763. code = func.__code__
  764. except AttributeError:
  765. # Some built-in functions don't have __code__, __defaults__, etc.
  766. return {}
  767. pos_count = code.co_argcount
  768. arg_names = code.co_varnames
  769. arg_names = arg_names[:pos_count]
  770. defaults = func.__defaults__ or ()
  771. kwdefaults = func.__kwdefaults__
  772. res = dict(kwdefaults) if kwdefaults else {}
  773. pos_offset = pos_count - len(defaults)
  774. for name, value in zip(arg_names[pos_offset:], defaults):
  775. assert name not in res
  776. res[name] = value
  777. return res
  778. _allowed_types = (types.FunctionType, types.BuiltinFunctionType,
  779. types.MethodType, types.ModuleType,
  780. WrapperDescriptorType, MethodWrapperType, MethodDescriptorType)
  781. def get_type_hints(obj, globalns=None, localns=None):
  782. """Return type hints for an object.
  783. This is often the same as obj.__annotations__, but it handles
  784. forward references encoded as string literals, and if necessary
  785. adds Optional[t] if a default value equal to None is set.
  786. The argument may be a module, class, method, or function. The annotations
  787. are returned as a dictionary. For classes, annotations include also
  788. inherited members.
  789. TypeError is raised if the argument is not of a type that can contain
  790. annotations, and an empty dictionary is returned if no annotations are
  791. present.
  792. BEWARE -- the behavior of globalns and localns is counterintuitive
  793. (unless you are familiar with how eval() and exec() work). The
  794. search order is locals first, then globals.
  795. - If no dict arguments are passed, an attempt is made to use the
  796. globals from obj (or the respective module's globals for classes),
  797. and these are also used as the locals. If the object does not appear
  798. to have globals, an empty dictionary is used.
  799. - If one dict argument is passed, it is used for both globals and
  800. locals.
  801. - If two dict arguments are passed, they specify globals and
  802. locals, respectively.
  803. """
  804. if getattr(obj, '__no_type_check__', None):
  805. return {}
  806. # Classes require a special treatment.
  807. if isinstance(obj, type):
  808. hints = {}
  809. for base in reversed(obj.__mro__):
  810. if globalns is None:
  811. base_globals = sys.modules[base.__module__].__dict__
  812. else:
  813. base_globals = globalns
  814. ann = base.__dict__.get('__annotations__', {})
  815. for name, value in ann.items():
  816. if value is None:
  817. value = type(None)
  818. if isinstance(value, str):
  819. value = ForwardRef(value, is_argument=False)
  820. value = _eval_type(value, base_globals, localns)
  821. hints[name] = value
  822. return hints
  823. if globalns is None:
  824. if isinstance(obj, types.ModuleType):
  825. globalns = obj.__dict__
  826. else:
  827. nsobj = obj
  828. # Find globalns for the unwrapped object.
  829. while hasattr(nsobj, '__wrapped__'):
  830. nsobj = nsobj.__wrapped__
  831. globalns = getattr(nsobj, '__globals__', {})
  832. if localns is None:
  833. localns = globalns
  834. elif localns is None:
  835. localns = globalns
  836. hints = getattr(obj, '__annotations__', None)
  837. if hints is None:
  838. # Return empty annotations for something that _could_ have them.
  839. if isinstance(obj, _allowed_types):
  840. return {}
  841. else:
  842. raise TypeError('{!r} is not a module, class, method, '
  843. 'or function.'.format(obj))
  844. defaults = _get_defaults(obj)
  845. hints = dict(hints)
  846. for name, value in hints.items():
  847. if value is None:
  848. value = type(None)
  849. if isinstance(value, str):
  850. value = ForwardRef(value)
  851. value = _eval_type(value, globalns, localns)
  852. if name in defaults and defaults[name] is None:
  853. value = Optional[value]
  854. hints[name] = value
  855. return hints
  856. def no_type_check(arg):
  857. """Decorator to indicate that annotations are not type hints.
  858. The argument must be a class or function; if it is a class, it
  859. applies recursively to all methods and classes defined in that class
  860. (but not to methods defined in its superclasses or subclasses).
  861. This mutates the function(s) or class(es) in place.
  862. """
  863. if isinstance(arg, type):
  864. arg_attrs = arg.__dict__.copy()
  865. for attr, val in arg.__dict__.items():
  866. if val in arg.__bases__ + (arg,):
  867. arg_attrs.pop(attr)
  868. for obj in arg_attrs.values():
  869. if isinstance(obj, types.FunctionType):
  870. obj.__no_type_check__ = True
  871. if isinstance(obj, type):
  872. no_type_check(obj)
  873. try:
  874. arg.__no_type_check__ = True
  875. except TypeError: # built-in classes
  876. pass
  877. return arg
  878. def no_type_check_decorator(decorator):
  879. """Decorator to give another decorator the @no_type_check effect.
  880. This wraps the decorator with something that wraps the decorated
  881. function in @no_type_check.
  882. """
  883. @functools.wraps(decorator)
  884. def wrapped_decorator(*args, **kwds):
  885. func = decorator(*args, **kwds)
  886. func = no_type_check(func)
  887. return func
  888. return wrapped_decorator
  889. def _overload_dummy(*args, **kwds):
  890. """Helper for @overload to raise when called."""
  891. raise NotImplementedError(
  892. "You should not call an overloaded function. "
  893. "A series of @overload-decorated functions "
  894. "outside a stub module should always be followed "
  895. "by an implementation that is not @overload-ed.")
  896. def overload(func):
  897. """Decorator for overloaded functions/methods.
  898. In a stub file, place two or more stub definitions for the same
  899. function in a row, each decorated with @overload. For example:
  900. @overload
  901. def utf8(value: None) -> None: ...
  902. @overload
  903. def utf8(value: bytes) -> bytes: ...
  904. @overload
  905. def utf8(value: str) -> bytes: ...
  906. In a non-stub file (i.e. a regular .py file), do the same but
  907. follow it with an implementation. The implementation should *not*
  908. be decorated with @overload. For example:
  909. @overload
  910. def utf8(value: None) -> None: ...
  911. @overload
  912. def utf8(value: bytes) -> bytes: ...
  913. @overload
  914. def utf8(value: str) -> bytes: ...
  915. def utf8(value):
  916. # implementation goes here
  917. """
  918. return _overload_dummy
  919. class _ProtocolMeta(type):
  920. """Internal metaclass for _Protocol.
  921. This exists so _Protocol classes can be generic without deriving
  922. from Generic.
  923. """
  924. def __instancecheck__(self, obj):
  925. if _Protocol not in self.__bases__:
  926. return super().__instancecheck__(obj)
  927. raise TypeError("Protocols cannot be used with isinstance().")
  928. def __subclasscheck__(self, cls):
  929. if not self._is_protocol:
  930. # No structural checks since this isn't a protocol.
  931. return NotImplemented
  932. if self is _Protocol:
  933. # Every class is a subclass of the empty protocol.
  934. return True
  935. # Find all attributes defined in the protocol.
  936. attrs = self._get_protocol_attrs()
  937. for attr in attrs:
  938. if not any(attr in d.__dict__ for d in cls.__mro__):
  939. return False
  940. return True
  941. def _get_protocol_attrs(self):
  942. # Get all Protocol base classes.
  943. protocol_bases = []
  944. for c in self.__mro__:
  945. if getattr(c, '_is_protocol', False) and c.__name__ != '_Protocol':
  946. protocol_bases.append(c)
  947. # Get attributes included in protocol.
  948. attrs = set()
  949. for base in protocol_bases:
  950. for attr in base.__dict__.keys():
  951. # Include attributes not defined in any non-protocol bases.
  952. for c in self.__mro__:
  953. if (c is not base and attr in c.__dict__ and
  954. not getattr(c, '_is_protocol', False)):
  955. break
  956. else:
  957. if (not attr.startswith('_abc_') and
  958. attr != '__abstractmethods__' and
  959. attr != '__annotations__' and
  960. attr != '__weakref__' and
  961. attr != '_is_protocol' and
  962. attr != '_gorg' and
  963. attr != '__dict__' and
  964. attr != '__args__' and
  965. attr != '__slots__' and
  966. attr != '_get_protocol_attrs' and
  967. attr != '__next_in_mro__' and
  968. attr != '__parameters__' and
  969. attr != '__origin__' and
  970. attr != '__orig_bases__' and
  971. attr != '__extra__' and
  972. attr != '__tree_hash__' and
  973. attr != '__module__'):
  974. attrs.add(attr)
  975. return attrs
  976. class _Protocol(Generic, metaclass=_ProtocolMeta):
  977. """Internal base class for protocol classes.
  978. This implements a simple-minded structural issubclass check
  979. (similar but more general than the one-offs in collections.abc
  980. such as Hashable).
  981. """
  982. __slots__ = ()
  983. _is_protocol = True
  984. def __class_getitem__(cls, params):
  985. return super().__class_getitem__(params)
  986. # Some unconstrained type variables. These are used by the container types.
  987. # (These are not for export.)
  988. T = TypeVar('T') # Any type.
  989. KT = TypeVar('KT') # Key type.
  990. VT = TypeVar('VT') # Value type.
  991. T_co = TypeVar('T_co', covariant=True) # Any type covariant containers.
  992. V_co = TypeVar('V_co', covariant=True) # Any type covariant containers.
  993. VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
  994. T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
  995. # Internal type variable used for Type[].
  996. CT_co = TypeVar('CT_co', covariant=True, bound=type)
  997. # A useful type variable with constraints. This represents string types.
  998. # (This one *is* for export!)
  999. AnyStr = TypeVar('AnyStr', bytes, str)
  1000. # Various ABCs mimicking those in collections.abc.
  1001. def _alias(origin, params, inst=True):
  1002. return _GenericAlias(origin, params, special=True, inst=inst)
  1003. Hashable = _alias(collections.abc.Hashable, ()) # Not generic.
  1004. Awaitable = _alias(collections.abc.Awaitable, T_co)
  1005. Coroutine = _alias(collections.abc.Coroutine, (T_co, T_contra, V_co))
  1006. AsyncIterable = _alias(collections.abc.AsyncIterable, T_co)
  1007. AsyncIterator = _alias(collections.abc.AsyncIterator, T_co)
  1008. Iterable = _alias(collections.abc.Iterable, T_co)
  1009. Iterator = _alias(collections.abc.Iterator, T_co)
  1010. Reversible = _alias(collections.abc.Reversible, T_co)
  1011. Sized = _alias(collections.abc.Sized, ()) # Not generic.
  1012. Container = _alias(collections.abc.Container, T_co)
  1013. Collection = _alias(collections.abc.Collection, T_co)
  1014. Callable = _VariadicGenericAlias(collections.abc.Callable, (), special=True)
  1015. Callable.__doc__ = \
  1016. """Callable type; Callable[[int], str] is a function of (int) -> str.
  1017. The subscription syntax must always be used with exactly two
  1018. values: the argument list and the return type. The argument list
  1019. must be a list of types or ellipsis; the return type must be a single type.
  1020. There is no syntax to indicate optional or keyword arguments,
  1021. such function types are rarely used as callback types.
  1022. """
  1023. AbstractSet = _alias(collections.abc.Set, T_co)
  1024. MutableSet = _alias(collections.abc.MutableSet, T)
  1025. # NOTE: Mapping is only covariant in the value type.
  1026. Mapping = _alias(collections.abc.Mapping, (KT, VT_co))
  1027. MutableMapping = _alias(collections.abc.MutableMapping, (KT, VT))
  1028. Sequence = _alias(collections.abc.Sequence, T_co)
  1029. MutableSequence = _alias(collections.abc.MutableSequence, T)
  1030. ByteString = _alias(collections.abc.ByteString, ()) # Not generic
  1031. Tuple = _VariadicGenericAlias(tuple, (), inst=False, special=True)
  1032. Tuple.__doc__ = \
  1033. """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
  1034. Example: Tuple[T1, T2] is a tuple of two elements corresponding
  1035. to type variables T1 and T2. Tuple[int, float, str] is a tuple
  1036. of an int, a float and a string.
  1037. To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
  1038. """
  1039. List = _alias(list, T, inst=False)
  1040. Deque = _alias(collections.deque, T)
  1041. Set = _alias(set, T, inst=False)
  1042. FrozenSet = _alias(frozenset, T_co, inst=False)
  1043. MappingView = _alias(collections.abc.MappingView, T_co)
  1044. KeysView = _alias(collections.abc.KeysView, KT)
  1045. ItemsView = _alias(collections.abc.ItemsView, (KT, VT_co))
  1046. ValuesView = _alias(collections.abc.ValuesView, VT_co)
  1047. ContextManager = _alias(contextlib.AbstractContextManager, T_co)
  1048. AsyncContextManager = _alias(contextlib.AbstractAsyncContextManager, T_co)
  1049. Dict = _alias(dict, (KT, VT), inst=False)
  1050. DefaultDict = _alias(collections.defaultdict, (KT, VT))
  1051. OrderedDict = _alias(collections.OrderedDict, (KT, VT))
  1052. Counter = _alias(collections.Counter, T)
  1053. ChainMap = _alias(collections.ChainMap, (KT, VT))
  1054. Generator = _alias(collections.abc.Generator, (T_co, T_contra, V_co))
  1055. AsyncGenerator = _alias(collections.abc.AsyncGenerator, (T_co, T_contra))
  1056. Type = _alias(type, CT_co, inst=False)
  1057. Type.__doc__ = \
  1058. """A special construct usable to annotate class objects.
  1059. For example, suppose we have the following classes::
  1060. class User: ... # Abstract base for User classes
  1061. class BasicUser(User): ...
  1062. class ProUser(User): ...
  1063. class TeamUser(User): ...
  1064. And a function that takes a class argument that's a subclass of
  1065. User and returns an instance of the corresponding class::
  1066. U = TypeVar('U', bound=User)
  1067. def new_user(user_class: Type[U]) -> U:
  1068. user = user_class()
  1069. # (Here we could write the user object to a database)
  1070. return user
  1071. joe = new_user(BasicUser)
  1072. At this point the type checker knows that joe has type BasicUser.
  1073. """
  1074. class SupportsInt(_Protocol):
  1075. """An ABC with one abstract method __int__."""
  1076. __slots__ = ()
  1077. @abstractmethod
  1078. def __int__(self) -> int:
  1079. pass
  1080. class SupportsFloat(_Protocol):
  1081. """An ABC with one abstract method __float__."""
  1082. __slots__ = ()
  1083. @abstractmethod
  1084. def __float__(self) -> float:
  1085. pass
  1086. class SupportsComplex(_Protocol):
  1087. """An ABC with one abstract method __complex__."""
  1088. __slots__ = ()
  1089. @abstractmethod
  1090. def __complex__(self) -> complex:
  1091. pass
  1092. class SupportsBytes(_Protocol):
  1093. """An ABC with one abstract method __bytes__."""
  1094. __slots__ = ()
  1095. @abstractmethod
  1096. def __bytes__(self) -> bytes:
  1097. pass
  1098. class SupportsAbs(_Protocol[T_co]):
  1099. """An ABC with one abstract method __abs__ that is covariant in its return type."""
  1100. __slots__ = ()
  1101. @abstractmethod
  1102. def __abs__(self) -> T_co:
  1103. pass
  1104. class SupportsRound(_Protocol[T_co]):
  1105. """An ABC with one abstract method __round__ that is covariant in its return type."""
  1106. __slots__ = ()
  1107. @abstractmethod
  1108. def __round__(self, ndigits: int = 0) -> T_co:
  1109. pass
  1110. def _make_nmtuple(name, types):
  1111. msg = "NamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a type"
  1112. types = [(n, _type_check(t, msg)) for n, t in types]
  1113. nm_tpl = collections.namedtuple(name, [n for n, t in types])
  1114. # Prior to PEP 526, only _field_types attribute was assigned.
  1115. # Now, both __annotations__ and _field_types are used to maintain compatibility.
  1116. nm_tpl.__annotations__ = nm_tpl._field_types = collections.OrderedDict(types)
  1117. try:
  1118. nm_tpl.__module__ = sys._getframe(2).f_globals.get('__name__', '__main__')
  1119. except (AttributeError, ValueError):
  1120. pass
  1121. return nm_tpl
  1122. # attributes prohibited to set in NamedTuple class syntax
  1123. _prohibited = ('__new__', '__init__', '__slots__', '__getnewargs__',
  1124. '_fields', '_field_defaults', '_field_types',
  1125. '_make', '_replace', '_asdict', '_source')
  1126. _special = ('__module__', '__name__', '__annotations__')
  1127. class NamedTupleMeta(type):
  1128. def __new__(cls, typename, bases, ns):
  1129. if ns.get('_root', False):
  1130. return super().__new__(cls, typename, bases, ns)
  1131. types = ns.get('__annotations__', {})
  1132. nm_tpl = _make_nmtuple(typename, types.items())
  1133. defaults = []
  1134. defaults_dict = {}
  1135. for field_name in types:
  1136. if field_name in ns:
  1137. default_value = ns[field_name]
  1138. defaults.append(default_value)
  1139. defaults_dict[field_name] = default_value
  1140. elif defaults:
  1141. raise TypeError("Non-default namedtuple field {field_name} cannot "
  1142. "follow default field(s) {default_names}"
  1143. .format(field_name=field_name,
  1144. default_names=', '.join(defaults_dict.keys())))
  1145. nm_tpl.__new__.__annotations__ = collections.OrderedDict(types)
  1146. nm_tpl.__new__.__defaults__ = tuple(defaults)
  1147. nm_tpl._field_defaults = defaults_dict
  1148. # update from user namespace without overriding special namedtuple attributes
  1149. for key in ns:
  1150. if key in _prohibited:
  1151. raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
  1152. elif key not in _special and key not in nm_tpl._fields:
  1153. setattr(nm_tpl, key, ns[key])
  1154. return nm_tpl
  1155. class NamedTuple(metaclass=NamedTupleMeta):
  1156. """Typed version of namedtuple.
  1157. Usage in Python versions >= 3.6::
  1158. class Employee(NamedTuple):
  1159. name: str
  1160. id: int
  1161. This is equivalent to::
  1162. Employee = collections.namedtuple('Employee', ['name', 'id'])
  1163. The resulting class has extra __annotations__ and _field_types
  1164. attributes, giving an ordered dict mapping field names to types.
  1165. __annotations__ should be preferred, while _field_types
  1166. is kept to maintain pre PEP 526 compatibility. (The field names
  1167. are in the _fields attribute, which is part of the namedtuple
  1168. API.) Alternative equivalent keyword syntax is also accepted::
  1169. Employee = NamedTuple('Employee', name=str, id=int)
  1170. In Python versions <= 3.5 use::
  1171. Employee = NamedTuple('Employee', [('name', str), ('id', int)])
  1172. """
  1173. _root = True
  1174. def __new__(*args, **kwargs):
  1175. if not args:
  1176. raise TypeError('NamedTuple.__new__(): not enough arguments')
  1177. cls, *args = args # allow the "cls" keyword be passed
  1178. if args:
  1179. typename, *args = args # allow the "typename" keyword be passed
  1180. elif 'typename' in kwargs:
  1181. typename = kwargs.pop('typename')
  1182. else:
  1183. raise TypeError("NamedTuple.__new__() missing 1 required positional "
  1184. "argument: 'typename'")
  1185. if args:
  1186. try:
  1187. fields, = args # allow the "fields" keyword be passed
  1188. except ValueError:
  1189. raise TypeError(f'NamedTuple.__new__() takes from 2 to 3 '
  1190. f'positional arguments but {len(args) + 2} '
  1191. f'were given') from None
  1192. elif 'fields' in kwargs and len(kwargs) == 1:
  1193. fields = kwargs.pop('fields')
  1194. else:
  1195. fields = None
  1196. if fields is None:
  1197. fields = kwargs.items()
  1198. elif kwargs:
  1199. raise TypeError("Either list of fields or keywords"
  1200. " can be provided to NamedTuple, not both")
  1201. return _make_nmtuple(typename, fields)
  1202. __new__.__text_signature__ = '($cls, typename, fields=None, /, **kwargs)'
  1203. def NewType(name, tp):
  1204. """NewType creates simple unique types with almost zero
  1205. runtime overhead. NewType(name, tp) is considered a subtype of tp
  1206. by static type checkers. At runtime, NewType(name, tp) returns
  1207. a dummy function that simply returns its argument. Usage::
  1208. UserId = NewType('UserId', int)
  1209. def name_by_id(user_id: UserId) -> str:
  1210. ...
  1211. UserId('user') # Fails type check
  1212. name_by_id(42) # Fails type check
  1213. name_by_id(UserId(42)) # OK
  1214. num = UserId(5) + 1 # type: int
  1215. """
  1216. def new_type(x):
  1217. return x
  1218. new_type.__name__ = name
  1219. new_type.__supertype__ = tp
  1220. return new_type
  1221. # Python-version-specific alias (Python 2: unicode; Python 3: str)
  1222. Text = str
  1223. # Constant that's True when type checking, but False here.
  1224. TYPE_CHECKING = False
  1225. class IO(Generic[AnyStr]):
  1226. """Generic base class for TextIO and BinaryIO.
  1227. This is an abstract, generic version of the return of open().
  1228. NOTE: This does not distinguish between the different possible
  1229. classes (text vs. binary, read vs. write vs. read/write,
  1230. append-only, unbuffered). The TextIO and BinaryIO subclasses
  1231. below capture the distinctions between text vs. binary, which is
  1232. pervasive in the interface; however we currently do not offer a
  1233. way to track the other distinctions in the type system.
  1234. """
  1235. __slots__ = ()
  1236. @abstractproperty
  1237. def mode(self) -> str:
  1238. pass
  1239. @abstractproperty
  1240. def name(self) -> str:
  1241. pass
  1242. @abstractmethod
  1243. def close(self) -> None:
  1244. pass
  1245. @abstractproperty
  1246. def closed(self) -> bool:
  1247. pass
  1248. @abstractmethod
  1249. def fileno(self) -> int:
  1250. pass
  1251. @abstractmethod
  1252. def flush(self) -> None:
  1253. pass
  1254. @abstractmethod
  1255. def isatty(self) -> bool:
  1256. pass
  1257. @abstractmethod
  1258. def read(self, n: int = -1) -> AnyStr:
  1259. pass
  1260. @abstractmethod
  1261. def readable(self) -> bool:
  1262. pass
  1263. @abstractmethod
  1264. def readline(self, limit: int = -1) -> AnyStr:
  1265. pass
  1266. @abstractmethod
  1267. def readlines(self, hint: int = -1) -> List[AnyStr]:
  1268. pass
  1269. @abstractmethod
  1270. def seek(self, offset: int, whence: int = 0) -> int:
  1271. pass
  1272. @abstractmethod
  1273. def seekable(self) -> bool:
  1274. pass
  1275. @abstractmethod
  1276. def tell(self) -> int:
  1277. pass
  1278. @abstractmethod
  1279. def truncate(self, size: int = None) -> int:
  1280. pass
  1281. @abstractmethod
  1282. def writable(self) -> bool:
  1283. pass
  1284. @abstractmethod
  1285. def write(self, s: AnyStr) -> int:
  1286. pass
  1287. @abstractmethod
  1288. def writelines(self, lines: List[AnyStr]) -> None:
  1289. pass
  1290. @abstractmethod
  1291. def __enter__(self) -> 'IO[AnyStr]':
  1292. pass
  1293. @abstractmethod
  1294. def __exit__(self, type, value, traceback) -> None:
  1295. pass
  1296. class BinaryIO(IO[bytes]):
  1297. """Typed version of the return of open() in binary mode."""
  1298. __slots__ = ()
  1299. @abstractmethod
  1300. def write(self, s: Union[bytes, bytearray]) -> int:
  1301. pass
  1302. @abstractmethod
  1303. def __enter__(self) -> 'BinaryIO':
  1304. pass
  1305. class TextIO(IO[str]):
  1306. """Typed version of the return of open() in text mode."""
  1307. __slots__ = ()
  1308. @abstractproperty
  1309. def buffer(self) -> BinaryIO:
  1310. pass
  1311. @abstractproperty
  1312. def encoding(self) -> str:
  1313. pass
  1314. @abstractproperty
  1315. def errors(self) -> Optional[str]:
  1316. pass
  1317. @abstractproperty
  1318. def line_buffering(self) -> bool:
  1319. pass
  1320. @abstractproperty
  1321. def newlines(self) -> Any:
  1322. pass
  1323. @abstractmethod
  1324. def __enter__(self) -> 'TextIO':
  1325. pass
  1326. class io:
  1327. """Wrapper namespace for IO generic classes."""
  1328. __all__ = ['IO', 'TextIO', 'BinaryIO']
  1329. IO = IO
  1330. TextIO = TextIO
  1331. BinaryIO = BinaryIO
  1332. io.__name__ = __name__ + '.io'
  1333. sys.modules[io.__name__] = io
  1334. Pattern = _alias(stdlib_re.Pattern, AnyStr)
  1335. Match = _alias(stdlib_re.Match, AnyStr)
  1336. class re:
  1337. """Wrapper namespace for re type aliases."""
  1338. __all__ = ['Pattern', 'Match']
  1339. Pattern = Pattern
  1340. Match = Match
  1341. re.__name__ = __name__ + '.re'
  1342. sys.modules[re.__name__] = re