logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

typing.py (90599B)


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