blob: b140b0e6696266cd0c9c860982c3792b04448312 [file] [log] [blame]
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001"""
2The typing module: Support for gradual typing as defined by PEP 484.
3
4At large scale, the structure of the module is following:
Tim McNamara5265b3a2018-09-01 20:56:58 +12005* Imports and exports, all public names should be explicitly added to __all__.
Ivan Levkivskyid911e402018-01-20 11:23:59 +00006* Internal helper functions: these should never be used in code outside this module.
kj73607be2020-12-24 12:33:48 +08007* _SpecialForm and its instances (special forms):
8 Any, NoReturn, ClassVar, Union, Optional, Concatenate
9* Classes whose instances can be type arguments in addition to types:
10 ForwardRef, TypeVar and ParamSpec
Ivan Levkivskyid911e402018-01-20 11:23:59 +000011* The core of internal generics API: _GenericAlias and _VariadicGenericAlias, the latter is
12 currently only used by Tuple and Callable. All subscripted types like X[int], Union[int, str],
13 etc., are instances of either of these classes.
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +010014* The public counterpart of the generics API consists of two classes: Generic and Protocol.
Ivan Levkivskyid911e402018-01-20 11:23:59 +000015* Public helper functions: get_type_hints, overload, cast, no_type_check,
16 no_type_check_decorator.
17* Generic aliases for collections.abc ABCs and few additional protocols.
ananthan-123ab6423f2020-02-19 10:03:05 +053018* Special types: NewType, NamedTuple, TypedDict.
Ivan Levkivskyid911e402018-01-20 11:23:59 +000019* Wrapper submodules for re and io related types.
20"""
21
HongWeipeng6ce03ec2019-09-27 15:54:26 +080022from abc import abstractmethod, ABCMeta
Batuhan Taskaya044a1042020-10-06 23:03:02 +030023import ast
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070024import collections
Ivan Levkivskyid911e402018-01-20 11:23:59 +000025import collections.abc
Brett Cannonf3ad0422016-04-15 10:51:30 -070026import contextlib
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070027import functools
Serhiy Storchaka09f32212018-05-26 21:19:26 +030028import operator
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070029import re as stdlib_re # Avoid confusion with the re we export.
30import sys
31import types
Guido van Rossum48b069a2020-04-07 09:50:06 -070032from types import WrapperDescriptorType, MethodWrapperType, MethodDescriptorType, GenericAlias
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070033
34# Please keep __all__ alphabetized within each category.
35__all__ = [
36 # Super-special typing primitives.
Jakub Stasiakcf5b1092020-02-05 02:10:19 +010037 'Annotated',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070038 'Any',
39 'Callable',
Guido van Rossum0a6976d2016-09-11 15:34:56 -070040 'ClassVar',
kj73607be2020-12-24 12:33:48 +080041 'Concatenate',
Ivan Levkivskyif3672422019-05-26 09:37:07 +010042 'Final',
Anthony Sottiled30da5d2019-05-29 11:19:38 -070043 'ForwardRef',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070044 'Generic',
Ivan Levkivskyib891c462019-05-26 09:37:48 +010045 'Literal',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070046 'Optional',
kj73607be2020-12-24 12:33:48 +080047 'ParamSpec',
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +010048 'Protocol',
Guido van Rossumeb9aca32016-05-24 16:38:22 -070049 'Tuple',
50 'Type',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070051 'TypeVar',
52 'Union',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070053
54 # ABCs (from collections.abc).
55 'AbstractSet', # collections.abc.Set.
56 'ByteString',
57 'Container',
Ivan Levkivskyi29fda8d2017-06-10 21:57:56 +020058 'ContextManager',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070059 'Hashable',
60 'ItemsView',
61 'Iterable',
62 'Iterator',
63 'KeysView',
64 'Mapping',
65 'MappingView',
66 'MutableMapping',
67 'MutableSequence',
68 'MutableSet',
69 'Sequence',
70 'Sized',
71 'ValuesView',
Ivan Levkivskyid911e402018-01-20 11:23:59 +000072 'Awaitable',
73 'AsyncIterator',
74 'AsyncIterable',
75 'Coroutine',
76 'Collection',
77 'AsyncGenerator',
78 'AsyncContextManager',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070079
80 # Structural checks, a.k.a. protocols.
81 'Reversible',
82 'SupportsAbs',
Ivan Levkivskyif06e0212017-05-02 19:14:07 +020083 'SupportsBytes',
84 'SupportsComplex',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070085 'SupportsFloat',
Paul Dagnelie4c7a46e2019-05-22 07:23:01 -070086 'SupportsIndex',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070087 'SupportsInt',
88 'SupportsRound',
89
90 # Concrete collection types.
Anthony Sottiled30da5d2019-05-29 11:19:38 -070091 'ChainMap',
Ivan Levkivskyib692dc82017-02-13 22:50:14 +010092 'Counter',
Raymond Hettinger80490522017-01-16 22:42:37 -080093 'Deque',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070094 'Dict',
Guido van Rossumbd5b9a02016-04-05 08:28:52 -070095 'DefaultDict',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070096 'List',
Anthony Sottiled30da5d2019-05-29 11:19:38 -070097 'OrderedDict',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070098 'Set',
Guido van Rossumefa798d2016-08-23 11:01:50 -070099 'FrozenSet',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700100 'NamedTuple', # Not really a type.
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +0100101 'TypedDict', # Not really a type.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700102 'Generator',
103
104 # One-off things.
105 'AnyStr',
106 'cast',
Ivan Levkivskyif3672422019-05-26 09:37:07 +0100107 'final',
Ivan Levkivskyi4c23aff2019-05-31 00:10:07 +0100108 'get_args',
109 'get_origin',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700110 'get_type_hints',
Patrick Reader0705ec82020-09-16 05:58:32 +0100111 'is_typeddict',
Guido van Rossum91185fe2016-06-08 11:19:11 -0700112 'NewType',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700113 'no_type_check',
114 'no_type_check_decorator',
aetracht45738202018-03-19 14:41:32 -0400115 'NoReturn',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700116 'overload',
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100117 'runtime_checkable',
Guido van Rossum0e0563c2016-04-05 14:54:25 -0700118 'Text',
Guido van Rossum91185fe2016-06-08 11:19:11 -0700119 'TYPE_CHECKING',
Mikhail Golubev4f3c2502020-10-08 00:44:31 +0300120 'TypeAlias',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700121]
122
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700123# 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
kj463c7d32020-12-14 02:38:24 +0800127
128def _type_convert(arg):
129 """For converting None to type(None), and strings to ForwardRef."""
130 if arg is None:
131 return type(None)
132 if isinstance(arg, str):
133 return ForwardRef(arg)
134 return arg
135
136
Nina Zakharenko0e61dff2018-05-22 20:32:10 -0700137def _type_check(arg, msg, is_argument=True):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000138 """Check that the argument is a type, and return it (internal helper).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700139
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000140 As a special case, accept None and return type(None) instead. Also wrap strings
141 into ForwardRef instances. Consider several corner cases, for example plain
142 special forms like Union are not valid, while Union[int, str] is OK, etc.
143 The msg argument is a human-readable error message, e.g::
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700144
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000145 "Union[arg, ...]: arg should be a type."
Guido van Rossum4cefe742016-09-27 15:20:12 -0700146
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000147 We append the repr() of the actual value (truncated to 100 chars).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700148 """
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100149 invalid_generic_forms = (Generic, Protocol)
Nina Zakharenko0e61dff2018-05-22 20:32:10 -0700150 if is_argument:
Ivan Levkivskyif3672422019-05-26 09:37:07 +0100151 invalid_generic_forms = invalid_generic_forms + (ClassVar, Final)
Nina Zakharenko2d2d3b12018-05-16 12:27:03 -0400152
kj463c7d32020-12-14 02:38:24 +0800153 arg = _type_convert(arg)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000154 if (isinstance(arg, _GenericAlias) and
Nina Zakharenko2d2d3b12018-05-16 12:27:03 -0400155 arg.__origin__ in invalid_generic_forms):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000156 raise TypeError(f"{arg} is not valid as type argument")
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300157 if arg in (Any, NoReturn):
158 return arg
159 if isinstance(arg, _SpecialForm) or arg in (Generic, Protocol):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000160 raise TypeError(f"Plain {arg} is not valid as type argument")
kj73607be2020-12-24 12:33:48 +0800161 if isinstance(arg, (type, TypeVar, ForwardRef, types.Union, ParamSpec)):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000162 return arg
163 if not callable(arg):
164 raise TypeError(f"{msg} Got {arg!r:.100}.")
165 return arg
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700166
167
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000168def _type_repr(obj):
169 """Return the repr() of an object, special-casing types (internal helper).
170
171 If obj is a type, we return a shorter version than the default
172 type.__repr__, based on the module and qualified name, which is
173 typically enough to uniquely identify a type. For everything
174 else, we fall back on repr(obj).
175 """
kj1f7dfb22020-11-02 02:13:38 +0800176 if isinstance(obj, types.GenericAlias):
177 return repr(obj)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000178 if isinstance(obj, type):
179 if obj.__module__ == 'builtins':
180 return obj.__qualname__
181 return f'{obj.__module__}.{obj.__qualname__}'
182 if obj is ...:
183 return('...')
184 if isinstance(obj, types.FunctionType):
185 return obj.__name__
186 return repr(obj)
187
188
189def _collect_type_vars(types):
kj73607be2020-12-24 12:33:48 +0800190 """Collect all type variable-like variables contained
191 in types in order of first appearance (lexicographic order). For example::
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000192
193 _collect_type_vars((T, List[S, T])) == (T, S)
194 """
195 tvars = []
196 for t in types:
kj73607be2020-12-24 12:33:48 +0800197 if isinstance(t, _TypeVarLike) and t not in tvars:
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000198 tvars.append(t)
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +0300199 if isinstance(t, (_GenericAlias, GenericAlias)):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000200 tvars.extend([t for t in t.__parameters__ if t not in tvars])
201 return tuple(tvars)
202
203
Serhiy Storchakafcb28562020-05-10 11:53:16 +0300204def _check_generic(cls, parameters, elen):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000205 """Check correct count for parameters of a generic cls (internal helper).
206 This gives a nice error message in case of count mismatch.
207 """
Serhiy Storchakafcb28562020-05-10 11:53:16 +0300208 if not elen:
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000209 raise TypeError(f"{cls} is not a generic class")
210 alen = len(parameters)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000211 if alen != elen:
212 raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};"
213 f" actual {alen}, expected {elen}")
214
kj73607be2020-12-24 12:33:48 +0800215def _prepare_paramspec_params(cls, params):
216 """Prepares the parameters for a Generic containing ParamSpec
217 variables (internal helper).
218 """
219 # Special case where Z[[int, str, bool]] == Z[int, str, bool] in PEP 612.
220 if len(cls.__parameters__) == 1 and len(params) > 1:
221 return (params,)
222 else:
223 _params = []
224 # Convert lists to tuples to help other libraries cache the results.
225 for p, tvar in zip(params, cls.__parameters__):
226 if isinstance(tvar, ParamSpec) and isinstance(p, list):
227 p = tuple(p)
228 _params.append(p)
229 return tuple(_params)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000230
Yurii Karabasf03d3182020-11-17 04:23:19 +0200231def _deduplicate(params):
232 # Weed out strict duplicates, preserving the first of each occurrence.
233 all_params = set(params)
234 if len(all_params) < len(params):
235 new_params = []
236 for t in params:
237 if t in all_params:
238 new_params.append(t)
239 all_params.remove(t)
240 params = new_params
241 assert not all_params, all_params
242 return params
243
244
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000245def _remove_dups_flatten(parameters):
Ivan Levkivskyif65e31f2018-05-18 16:00:38 -0700246 """An internal helper for Union creation and substitution: flatten Unions
247 among parameters, then remove duplicates.
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000248 """
249 # Flatten out Union[Union[...], ...].
250 params = []
251 for p in parameters:
Maggie Moss1b4552c2020-09-09 13:23:24 -0700252 if isinstance(p, (_UnionGenericAlias, types.Union)):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000253 params.extend(p.__args__)
254 elif isinstance(p, tuple) and len(p) > 0 and p[0] is Union:
255 params.extend(p[1:])
256 else:
257 params.append(p)
Yurii Karabasf03d3182020-11-17 04:23:19 +0200258
259 return tuple(_deduplicate(params))
260
261
262def _flatten_literal_params(parameters):
263 """An internal helper for Literal creation: flatten Literals among parameters"""
264 params = []
265 for p in parameters:
266 if isinstance(p, _LiteralGenericAlias):
267 params.extend(p.__args__)
268 else:
269 params.append(p)
Ivan Levkivskyif65e31f2018-05-18 16:00:38 -0700270 return tuple(params)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000271
272
273_cleanups = []
274
275
Yurii Karabasf03d3182020-11-17 04:23:19 +0200276def _tp_cache(func=None, /, *, typed=False):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000277 """Internal wrapper caching __getitem__ of generic types with a fallback to
278 original function for non-hashable arguments.
279 """
Yurii Karabasf03d3182020-11-17 04:23:19 +0200280 def decorator(func):
281 cached = functools.lru_cache(typed=typed)(func)
282 _cleanups.append(cached.cache_clear)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000283
Yurii Karabasf03d3182020-11-17 04:23:19 +0200284 @functools.wraps(func)
285 def inner(*args, **kwds):
286 try:
287 return cached(*args, **kwds)
288 except TypeError:
289 pass # All real errors (not unhashable args) are raised below.
290 return func(*args, **kwds)
291 return inner
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000292
Yurii Karabasf03d3182020-11-17 04:23:19 +0200293 if func is not None:
294 return decorator(func)
295
296 return decorator
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000297
wyfo653f4202020-07-22 21:47:28 +0200298def _eval_type(t, globalns, localns, recursive_guard=frozenset()):
Graham Bleaney84ef33c2020-09-08 18:41:10 -0400299 """Evaluate all forward references in the given type t.
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000300 For use of globalns and localns see the docstring for get_type_hints().
wyfo653f4202020-07-22 21:47:28 +0200301 recursive_guard is used to prevent prevent infinite recursion
302 with recursive ForwardRef.
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000303 """
304 if isinstance(t, ForwardRef):
wyfo653f4202020-07-22 21:47:28 +0200305 return t._evaluate(globalns, localns, recursive_guard)
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +0300306 if isinstance(t, (_GenericAlias, GenericAlias)):
wyfo653f4202020-07-22 21:47:28 +0200307 ev_args = tuple(_eval_type(a, globalns, localns, recursive_guard) for a in t.__args__)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000308 if ev_args == t.__args__:
309 return t
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +0300310 if isinstance(t, GenericAlias):
311 return GenericAlias(t.__origin__, ev_args)
312 else:
313 return t.copy_with(ev_args)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000314 return t
315
316
317class _Final:
318 """Mixin to prohibit subclassing"""
Guido van Rossum4cefe742016-09-27 15:20:12 -0700319
Guido van Rossum83ec3022017-01-17 20:43:28 -0800320 __slots__ = ('__weakref__',)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700321
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300322 def __init_subclass__(self, /, *args, **kwds):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000323 if '_root' not in kwds:
324 raise TypeError("Cannot subclass special typing classes")
325
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100326class _Immutable:
327 """Mixin to indicate that object should not be copied."""
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +0300328 __slots__ = ()
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000329
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100330 def __copy__(self):
331 return self
332
333 def __deepcopy__(self, memo):
334 return self
335
336
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300337# Internal indicator of special typing constructs.
338# See __doc__ instance attribute for specific docs.
339class _SpecialForm(_Final, _root=True):
340 __slots__ = ('_name', '__doc__', '_getitem')
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000341
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300342 def __init__(self, getitem):
343 self._getitem = getitem
344 self._name = getitem.__name__
345 self.__doc__ = getitem.__doc__
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000346
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300347 def __mro_entries__(self, bases):
348 raise TypeError(f"Cannot subclass {self!r}")
Guido van Rossum4cefe742016-09-27 15:20:12 -0700349
350 def __repr__(self):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000351 return 'typing.' + self._name
352
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100353 def __reduce__(self):
354 return self._name
Guido van Rossum4cefe742016-09-27 15:20:12 -0700355
356 def __call__(self, *args, **kwds):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000357 raise TypeError(f"Cannot instantiate {self!r}")
358
359 def __instancecheck__(self, obj):
360 raise TypeError(f"{self} cannot be used with isinstance()")
361
362 def __subclasscheck__(self, cls):
363 raise TypeError(f"{self} cannot be used with issubclass()")
364
365 @_tp_cache
366 def __getitem__(self, parameters):
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300367 return self._getitem(self, parameters)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700368
Yurii Karabasf03d3182020-11-17 04:23:19 +0200369
370class _LiteralSpecialForm(_SpecialForm, _root=True):
371 @_tp_cache(typed=True)
372 def __getitem__(self, parameters):
373 return self._getitem(self, parameters)
374
375
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300376@_SpecialForm
377def Any(self, parameters):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000378 """Special type indicating an unconstrained type.
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700379
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000380 - Any is compatible with every type.
381 - Any assumed to have all methods.
382 - All values assumed to be instances of Any.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700383
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000384 Note that all the above statements are true from the point of view of
385 static type checkers. At runtime, Any should not be used with instance
386 or class checks.
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300387 """
388 raise TypeError(f"{self} is not subscriptable")
Guido van Rossumd70fe632015-08-05 12:11:06 +0200389
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300390@_SpecialForm
391def NoReturn(self, parameters):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000392 """Special type indicating functions that never return.
393 Example::
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700394
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000395 from typing import NoReturn
396
397 def stop() -> NoReturn:
398 raise Exception('no way')
399
400 This type is invalid in other positions, e.g., ``List[NoReturn]``
401 will fail in static type checkers.
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300402 """
403 raise TypeError(f"{self} is not subscriptable")
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000404
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300405@_SpecialForm
406def ClassVar(self, parameters):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000407 """Special type construct to mark class variables.
408
409 An annotation wrapped in ClassVar indicates that a given
410 attribute is intended to be used as a class variable and
411 should not be set on instances of that class. Usage::
412
413 class Starship:
414 stats: ClassVar[Dict[str, int]] = {} # class variable
415 damage: int = 10 # instance variable
416
417 ClassVar accepts only types and cannot be further subscribed.
418
419 Note that ClassVar is not a class itself, and should not
420 be used with isinstance() or issubclass().
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300421 """
422 item = _type_check(parameters, f'{self} accepts only single type.')
423 return _GenericAlias(self, (item,))
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000424
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300425@_SpecialForm
426def Final(self, parameters):
Ivan Levkivskyif3672422019-05-26 09:37:07 +0100427 """Special typing construct to indicate final names to type checkers.
428
429 A final name cannot be re-assigned or overridden in a subclass.
430 For example:
431
432 MAX_SIZE: Final = 9000
433 MAX_SIZE += 1 # Error reported by type checker
434
435 class Connection:
436 TIMEOUT: Final[int] = 10
437
438 class FastConnector(Connection):
439 TIMEOUT = 1 # Error reported by type checker
440
441 There is no runtime checking of these properties.
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300442 """
443 item = _type_check(parameters, f'{self} accepts only single type.')
444 return _GenericAlias(self, (item,))
Ivan Levkivskyif3672422019-05-26 09:37:07 +0100445
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300446@_SpecialForm
447def Union(self, parameters):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000448 """Union type; Union[X, Y] means either X or Y.
449
450 To define a union, use e.g. Union[int, str]. Details:
451 - The arguments must be types and there must be at least one.
452 - None as an argument is a special case and is replaced by
453 type(None).
454 - Unions of unions are flattened, e.g.::
455
456 Union[Union[int, str], float] == Union[int, str, float]
457
458 - Unions of a single argument vanish, e.g.::
459
460 Union[int] == int # The constructor actually returns int
461
462 - Redundant arguments are skipped, e.g.::
463
464 Union[int, str, int] == Union[int, str]
465
466 - When comparing unions, the argument order is ignored, e.g.::
467
468 Union[int, str] == Union[str, int]
469
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000470 - You cannot subclass or instantiate a union.
471 - You can use Optional[X] as a shorthand for Union[X, None].
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300472 """
473 if parameters == ():
474 raise TypeError("Cannot take a Union of no types.")
475 if not isinstance(parameters, tuple):
476 parameters = (parameters,)
477 msg = "Union[arg, ...]: each arg must be a type."
478 parameters = tuple(_type_check(p, msg) for p in parameters)
479 parameters = _remove_dups_flatten(parameters)
480 if len(parameters) == 1:
481 return parameters[0]
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +0300482 return _UnionGenericAlias(self, parameters)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000483
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300484@_SpecialForm
485def Optional(self, parameters):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000486 """Optional type.
487
488 Optional[X] is equivalent to Union[X, None].
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300489 """
490 arg = _type_check(parameters, f"{self} requires a single type.")
491 return Union[arg, type(None)]
Guido van Rossumb7dedc82016-10-29 12:44:29 -0700492
Yurii Karabasf03d3182020-11-17 04:23:19 +0200493@_LiteralSpecialForm
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300494def Literal(self, parameters):
Ivan Levkivskyib891c462019-05-26 09:37:48 +0100495 """Special typing form to define literal types (a.k.a. value types).
496
497 This form can be used to indicate to type checkers that the corresponding
498 variable or function parameter has a value equivalent to the provided
499 literal (or one of several literals):
500
501 def validate_simple(data: Any) -> Literal[True]: # always returns True
502 ...
503
504 MODE = Literal['r', 'rb', 'w', 'wb']
505 def open_helper(file: str, mode: MODE) -> str:
506 ...
507
508 open_helper('/some/path', 'r') # Passes type check
509 open_helper('/other/path', 'typo') # Error in type checker
510
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300511 Literal[...] cannot be subclassed. At runtime, an arbitrary value
512 is allowed as type argument to Literal[...], but type checkers may
513 impose restrictions.
514 """
515 # There is no '_type_check' call because arguments to Literal[...] are
516 # values, not types.
Yurii Karabasf03d3182020-11-17 04:23:19 +0200517 if not isinstance(parameters, tuple):
518 parameters = (parameters,)
519
520 parameters = _flatten_literal_params(parameters)
521
522 try:
523 parameters = tuple(p for p, _ in _deduplicate(list(_value_and_type_iter(parameters))))
524 except TypeError: # unhashable parameters
525 pass
526
527 return _LiteralGenericAlias(self, parameters)
Ivan Levkivskyib891c462019-05-26 09:37:48 +0100528
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700529
Mikhail Golubev4f3c2502020-10-08 00:44:31 +0300530@_SpecialForm
531def TypeAlias(self, parameters):
532 """Special marker indicating that an assignment should
533 be recognized as a proper type alias definition by type
534 checkers.
535
536 For example::
537
538 Predicate: TypeAlias = Callable[..., bool]
539
540 It's invalid when used anywhere except as in the example above.
541 """
542 raise TypeError(f"{self} is not subscriptable")
543
544
kj73607be2020-12-24 12:33:48 +0800545@_SpecialForm
546def Concatenate(self, parameters):
547 """Used in conjunction with ParamSpec and Callable to represent a higher
548 order function which adds, removes or transforms parameters of a Callable.
549
550 For example::
551
552 Callable[Concatenate[int, P], int]
553
554 See PEP 612 for detailed information.
555 """
556 if parameters == ():
557 raise TypeError("Cannot take a Concatenate of no types.")
558 if not isinstance(parameters, tuple):
559 parameters = (parameters,)
560 if not isinstance(parameters[-1], ParamSpec):
561 raise TypeError("The last parameter to Concatenate should be a "
562 "ParamSpec variable.")
563 msg = "Concatenate[arg, ...]: each arg must be a type."
564 parameters = tuple(_type_check(p, msg) for p in parameters)
565 return _ConcatenateGenericAlias(self, parameters)
566
567
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000568class ForwardRef(_Final, _root=True):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800569 """Internal wrapper to hold a forward reference."""
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700570
Guido van Rossum4cefe742016-09-27 15:20:12 -0700571 __slots__ = ('__forward_arg__', '__forward_code__',
Nina Zakharenko2d2d3b12018-05-16 12:27:03 -0400572 '__forward_evaluated__', '__forward_value__',
573 '__forward_is_argument__')
Guido van Rossum4cefe742016-09-27 15:20:12 -0700574
Nina Zakharenko0e61dff2018-05-22 20:32:10 -0700575 def __init__(self, arg, is_argument=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700576 if not isinstance(arg, str):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000577 raise TypeError(f"Forward reference must be a string -- got {arg!r}")
Batuhan Taskaya044a1042020-10-06 23:03:02 +0300578
579 # Double-stringified forward references is a result of activating
580 # the 'annotations' future by default. This way, we eliminate them in
581 # the runtime.
582 if arg.startswith(("'", '\"')) and arg.endswith(("'", '"')):
583 arg = arg[1:-1]
584
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700585 try:
586 code = compile(arg, '<string>', 'eval')
587 except SyntaxError:
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000588 raise SyntaxError(f"Forward reference must be an expression -- got {arg!r}")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700589 self.__forward_arg__ = arg
590 self.__forward_code__ = code
591 self.__forward_evaluated__ = False
592 self.__forward_value__ = None
Nina Zakharenko2d2d3b12018-05-16 12:27:03 -0400593 self.__forward_is_argument__ = is_argument
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700594
wyfo653f4202020-07-22 21:47:28 +0200595 def _evaluate(self, globalns, localns, recursive_guard):
596 if self.__forward_arg__ in recursive_guard:
597 return self
Guido van Rossumdad17902016-11-10 08:29:18 -0800598 if not self.__forward_evaluated__ or localns is not globalns:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700599 if globalns is None and localns is None:
600 globalns = localns = {}
601 elif globalns is None:
602 globalns = localns
603 elif localns is None:
604 localns = globalns
wyfo653f4202020-07-22 21:47:28 +0200605 type_ =_type_check(
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700606 eval(self.__forward_code__, globalns, localns),
Nina Zakharenko2d2d3b12018-05-16 12:27:03 -0400607 "Forward references must evaluate to types.",
wyfo653f4202020-07-22 21:47:28 +0200608 is_argument=self.__forward_is_argument__,
609 )
610 self.__forward_value__ = _eval_type(
611 type_, globalns, localns, recursive_guard | {self.__forward_arg__}
612 )
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700613 self.__forward_evaluated__ = True
614 return self.__forward_value__
615
Guido van Rossum4cefe742016-09-27 15:20:12 -0700616 def __eq__(self, other):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000617 if not isinstance(other, ForwardRef):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700618 return NotImplemented
plokmijnuhbye082e7c2019-09-13 20:40:54 +0100619 if self.__forward_evaluated__ and other.__forward_evaluated__:
620 return (self.__forward_arg__ == other.__forward_arg__ and
621 self.__forward_value__ == other.__forward_value__)
622 return self.__forward_arg__ == other.__forward_arg__
Guido van Rossum4cefe742016-09-27 15:20:12 -0700623
624 def __hash__(self):
plokmijnuhbye082e7c2019-09-13 20:40:54 +0100625 return hash(self.__forward_arg__)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700626
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700627 def __repr__(self):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000628 return f'ForwardRef({self.__forward_arg__!r})'
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700629
kj73607be2020-12-24 12:33:48 +0800630class _TypeVarLike:
631 """Mixin for TypeVar-like types (TypeVar and ParamSpec)."""
632 def __init__(self, bound, covariant, contravariant):
633 """Used to setup TypeVars and ParamSpec's bound, covariant and
634 contravariant attributes.
635 """
636 if covariant and contravariant:
637 raise ValueError("Bivariant types are not supported.")
638 self.__covariant__ = bool(covariant)
639 self.__contravariant__ = bool(contravariant)
640 if bound:
641 self.__bound__ = _type_check(bound, "Bound must be a type.")
642 else:
643 self.__bound__ = None
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700644
kj73607be2020-12-24 12:33:48 +0800645 def __or__(self, right):
646 return Union[self, right]
647
648 def __ror__(self, right):
649 return Union[self, right]
650
651 def __repr__(self):
652 if self.__covariant__:
653 prefix = '+'
654 elif self.__contravariant__:
655 prefix = '-'
656 else:
657 prefix = '~'
658 return prefix + self.__name__
659
660 def __reduce__(self):
661 return self.__name__
662
663
664class TypeVar( _Final, _Immutable, _TypeVarLike, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700665 """Type variable.
666
667 Usage::
668
669 T = TypeVar('T') # Can be anything
670 A = TypeVar('A', str, bytes) # Must be str or bytes
671
672 Type variables exist primarily for the benefit of static type
673 checkers. They serve as the parameters for generic types as well
674 as for generic function definitions. See class Generic for more
675 information on generic types. Generic functions work as follows:
676
Guido van Rossumb24569a2016-11-20 18:01:29 -0800677 def repeat(x: T, n: int) -> List[T]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700678 '''Return a list containing n references to x.'''
679 return [x]*n
680
681 def longest(x: A, y: A) -> A:
682 '''Return the longest of two strings.'''
683 return x if len(x) >= len(y) else y
684
685 The latter example's signature is essentially the overloading
686 of (str, str) -> str and (bytes, bytes) -> bytes. Also note
687 that if the arguments are instances of some subclass of str,
688 the return type is still plain str.
689
Guido van Rossumb24569a2016-11-20 18:01:29 -0800690 At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700691
Guido van Rossumefa798d2016-08-23 11:01:50 -0700692 Type variables defined with covariant=True or contravariant=True
João D. Ferreira86bfed32018-07-07 16:41:20 +0100693 can be used to declare covariant or contravariant generic types.
Guido van Rossumefa798d2016-08-23 11:01:50 -0700694 See PEP 484 for more details. By default generic types are invariant
695 in all type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700696
697 Type variables can be introspected. e.g.:
698
699 T.__name__ == 'T'
700 T.__constraints__ == ()
701 T.__covariant__ == False
702 T.__contravariant__ = False
703 A.__constraints__ == (str, bytes)
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100704
705 Note that only type variables defined in global scope can be pickled.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700706 """
707
Guido van Rossum4cefe742016-09-27 15:20:12 -0700708 __slots__ = ('__name__', '__bound__', '__constraints__',
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +0300709 '__covariant__', '__contravariant__', '__dict__')
Guido van Rossum4cefe742016-09-27 15:20:12 -0700710
711 def __init__(self, name, *constraints, bound=None,
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800712 covariant=False, contravariant=False):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700713 self.__name__ = name
kj73607be2020-12-24 12:33:48 +0800714 super().__init__(bound, covariant, contravariant)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700715 if constraints and bound is not None:
716 raise TypeError("Constraints cannot be combined with bound=...")
717 if constraints and len(constraints) == 1:
718 raise TypeError("A single constraint is not allowed")
719 msg = "TypeVar(name, constraint, ...): constraints must be types."
720 self.__constraints__ = tuple(_type_check(t, msg) for t in constraints)
HongWeipenga25a04f2020-04-21 04:01:53 +0800721 try:
722 def_mod = sys._getframe(1).f_globals.get('__name__', '__main__') # for pickling
723 except (AttributeError, ValueError):
724 def_mod = None
Serhiy Storchaka09f32212018-05-26 21:19:26 +0300725 if def_mod != 'typing':
726 self.__module__ = def_mod
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700727
Maggie Moss1b4552c2020-09-09 13:23:24 -0700728
kj73607be2020-12-24 12:33:48 +0800729class ParamSpec(_Final, _Immutable, _TypeVarLike, _root=True):
730 """Parameter specification variable.
Maggie Moss1b4552c2020-09-09 13:23:24 -0700731
kj73607be2020-12-24 12:33:48 +0800732 Usage::
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700733
kj73607be2020-12-24 12:33:48 +0800734 P = ParamSpec('P')
735
736 Parameter specification variables exist primarily for the benefit of static
737 type checkers. They are used to forward the parameter types of one
738 Callable to another Callable, a pattern commonly found in higher order
739 functions and decorators. They are only valid when used in Concatenate, or
740 as the first argument to Callable, or as parameters for user-defined Generics.
741 See class Generic for more information on generic types. An example for
742 annotating a decorator::
743
744 T = TypeVar('T')
745 P = ParamSpec('P')
746
747 def add_logging(f: Callable[P, T]) -> Callable[P, T]:
748 '''A type-safe decorator to add logging to a function.'''
749 def inner(*args: P.args, **kwargs: P.kwargs) -> T:
750 logging.info(f'{f.__name__} was called')
751 return f(*args, **kwargs)
752 return inner
753
754 @add_logging
755 def add_two(x: float, y: float) -> float:
756 '''Add two numbers together.'''
757 return x + y
758
759 Parameter specification variables defined with covariant=True or
760 contravariant=True can be used to declare covariant or contravariant
761 generic types. These keyword arguments are valid, but their actual semantics
762 are yet to be decided. See PEP 612 for details.
763
764 Parameter specification variables can be introspected. e.g.:
765
766 P.__name__ == 'T'
767 P.__bound__ == None
768 P.__covariant__ == False
769 P.__contravariant__ == False
770
771 Note that only parameter specification variables defined in global scope can
772 be pickled.
773 """
774
775 __slots__ = ('__name__', '__bound__', '__covariant__', '__contravariant__',
776 '__dict__')
777
778 args = object()
779 kwargs = object()
780
781 def __init__(self, name, bound=None, covariant=False, contravariant=False):
782 self.__name__ = name
783 super().__init__(bound, covariant, contravariant)
784 try:
785 def_mod = sys._getframe(1).f_globals.get('__name__', '__main__')
786 except (AttributeError, ValueError):
787 def_mod = None
788 if def_mod != 'typing':
789 self.__module__ = def_mod
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100790
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700791
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000792def _is_dunder(attr):
793 return attr.startswith('__') and attr.endswith('__')
Guido van Rossum83ec3022017-01-17 20:43:28 -0800794
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +0300795class _BaseGenericAlias(_Final, _root=True):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000796 """The central part of internal API.
797
798 This represents a generic version of type 'origin' with type arguments 'params'.
799 There are two kind of these aliases: user defined and special. The special ones
800 are wrappers around builtin collections and ABCs in collections.abc. These must
801 have 'name' always set. If 'inst' is False, then the alias can't be instantiated,
802 this is used by e.g. typing.List and typing.Dict.
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700803 """
Serhiy Storchakafcb28562020-05-10 11:53:16 +0300804 def __init__(self, origin, *, inst=True, name=None):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000805 self._inst = inst
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000806 self._name = name
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700807 self.__origin__ = origin
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000808 self.__slots__ = None # This is not documented.
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +0300809
810 def __call__(self, *args, **kwargs):
811 if not self._inst:
812 raise TypeError(f"Type {self._name} cannot be instantiated; "
813 f"use {self.__origin__.__name__}() instead")
814 result = self.__origin__(*args, **kwargs)
815 try:
816 result.__orig_class__ = self
817 except AttributeError:
818 pass
819 return result
820
821 def __mro_entries__(self, bases):
822 res = []
823 if self.__origin__ not in bases:
824 res.append(self.__origin__)
825 i = bases.index(self)
826 for b in bases[i+1:]:
827 if isinstance(b, _BaseGenericAlias) or issubclass(b, Generic):
828 break
829 else:
830 res.append(Generic)
831 return tuple(res)
832
833 def __getattr__(self, attr):
834 # We are careful for copy and pickle.
835 # Also for simplicity we just don't relay all dunder names
836 if '__origin__' in self.__dict__ and not _is_dunder(attr):
837 return getattr(self.__origin__, attr)
838 raise AttributeError(attr)
839
840 def __setattr__(self, attr, val):
Serhiy Storchakafcb28562020-05-10 11:53:16 +0300841 if _is_dunder(attr) or attr in ('_name', '_inst', '_nparams'):
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +0300842 super().__setattr__(attr, val)
843 else:
844 setattr(self.__origin__, attr, val)
845
846 def __instancecheck__(self, obj):
847 return self.__subclasscheck__(type(obj))
848
849 def __subclasscheck__(self, cls):
850 raise TypeError("Subscripted generics cannot be used with"
851 " class and instance checks")
852
853
Serhiy Storchakafcb28562020-05-10 11:53:16 +0300854# Special typing constructs Union, Optional, Generic, Callable and Tuple
855# use three special attributes for internal bookkeeping of generic types:
856# * __parameters__ is a tuple of unique free type parameters of a generic
857# type, for example, Dict[T, T].__parameters__ == (T,);
858# * __origin__ keeps a reference to a type that was subscripted,
859# e.g., Union[T, int].__origin__ == Union, or the non-generic version of
860# the type.
861# * __args__ is a tuple of all arguments used in subscripting,
862# e.g., Dict[T, int].__args__ == (T, int).
863
864
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +0300865class _GenericAlias(_BaseGenericAlias, _root=True):
Serhiy Storchakafcb28562020-05-10 11:53:16 +0300866 def __init__(self, origin, params, *, inst=True, name=None):
867 super().__init__(origin, inst=inst, name=name)
868 if not isinstance(params, tuple):
869 params = (params,)
870 self.__args__ = tuple(... if a is _TypingEllipsis else
871 () if a is _TypingEmpty else
872 a for a in params)
873 self.__parameters__ = _collect_type_vars(params)
874 if not name:
875 self.__module__ = origin.__module__
876
877 def __eq__(self, other):
878 if not isinstance(other, _GenericAlias):
879 return NotImplemented
880 return (self.__origin__ == other.__origin__
881 and self.__args__ == other.__args__)
882
883 def __hash__(self):
884 return hash((self.__origin__, self.__args__))
885
Maggie Moss1b4552c2020-09-09 13:23:24 -0700886 def __or__(self, right):
887 return Union[self, right]
888
889 def __ror__(self, right):
890 return Union[self, right]
891
Guido van Rossum4cefe742016-09-27 15:20:12 -0700892 @_tp_cache
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700893 def __getitem__(self, params):
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100894 if self.__origin__ in (Generic, Protocol):
895 # Can't subscript Generic[...] or Protocol[...].
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000896 raise TypeError(f"Cannot subscript already-subscripted {self}")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700897 if not isinstance(params, tuple):
898 params = (params,)
kj73607be2020-12-24 12:33:48 +0800899 params = tuple(_type_convert(p) for p in params)
900 if any(isinstance(t, ParamSpec) for t in self.__parameters__):
901 params = _prepare_paramspec_params(self, params)
Serhiy Storchakafcb28562020-05-10 11:53:16 +0300902 _check_generic(self, params, len(self.__parameters__))
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +0300903
904 subst = dict(zip(self.__parameters__, params))
905 new_args = []
906 for arg in self.__args__:
kj73607be2020-12-24 12:33:48 +0800907 if isinstance(arg, _TypeVarLike):
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +0300908 arg = subst[arg]
Serhiy Storchakafcb28562020-05-10 11:53:16 +0300909 elif isinstance(arg, (_GenericAlias, GenericAlias)):
Serhiy Storchaka0122d482020-05-10 13:39:40 +0300910 subparams = arg.__parameters__
911 if subparams:
912 subargs = tuple(subst[x] for x in subparams)
913 arg = arg[subargs]
kj73607be2020-12-24 12:33:48 +0800914 # Required to flatten out the args for CallableGenericAlias
915 if self.__origin__ == collections.abc.Callable and isinstance(arg, tuple):
916 new_args.extend(arg)
917 else:
918 new_args.append(arg)
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +0300919 return self.copy_with(tuple(new_args))
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100920
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000921 def copy_with(self, params):
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +0300922 return self.__class__(self.__origin__, params, name=self._name, inst=self._inst)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700923
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000924 def __repr__(self):
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +0300925 if self._name:
926 name = 'typing.' + self._name
927 else:
928 name = _type_repr(self.__origin__)
929 args = ", ".join([_type_repr(a) for a in self.__args__])
930 return f'{name}[{args}]'
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000931
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +0300932 def __reduce__(self):
933 if self._name:
934 origin = globals()[self._name]
935 else:
936 origin = self.__origin__
937 args = tuple(self.__args__)
938 if len(args) == 1 and not isinstance(args[0], tuple):
939 args, = args
940 return operator.getitem, (origin, args)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000941
942 def __mro_entries__(self, bases):
943 if self._name: # generic version of an ABC or built-in class
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +0300944 return super().__mro_entries__(bases)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000945 if self.__origin__ is Generic:
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100946 if Protocol in bases:
947 return ()
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000948 i = bases.index(self)
949 for b in bases[i+1:]:
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +0300950 if isinstance(b, _BaseGenericAlias) and b is not self:
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000951 return ()
952 return (self.__origin__,)
953
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000954
Serhiy Storchakafcb28562020-05-10 11:53:16 +0300955# _nparams is the number of accepted parameters, e.g. 0 for Hashable,
956# 1 for List and 2 for Dict. It may be -1 if variable number of
957# parameters are accepted (needs custom __getitem__).
958
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +0300959class _SpecialGenericAlias(_BaseGenericAlias, _root=True):
Serhiy Storchakafcb28562020-05-10 11:53:16 +0300960 def __init__(self, origin, nparams, *, inst=True, name=None):
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +0300961 if name is None:
962 name = origin.__name__
Serhiy Storchakafcb28562020-05-10 11:53:16 +0300963 super().__init__(origin, inst=inst, name=name)
964 self._nparams = nparams
Serhiy Storchaka2fbc57a2020-05-10 15:14:27 +0300965 if origin.__module__ == 'builtins':
966 self.__doc__ = f'A generic version of {origin.__qualname__}.'
967 else:
968 self.__doc__ = f'A generic version of {origin.__module__}.{origin.__qualname__}.'
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000969
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +0300970 @_tp_cache
971 def __getitem__(self, params):
972 if not isinstance(params, tuple):
973 params = (params,)
974 msg = "Parameters to generic types must be types."
975 params = tuple(_type_check(p, msg) for p in params)
Serhiy Storchakafcb28562020-05-10 11:53:16 +0300976 _check_generic(self, params, self._nparams)
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +0300977 return self.copy_with(params)
978
979 def copy_with(self, params):
980 return _GenericAlias(self.__origin__, params,
981 name=self._name, inst=self._inst)
982
983 def __repr__(self):
984 return 'typing.' + self._name
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000985
986 def __subclasscheck__(self, cls):
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +0300987 if isinstance(cls, _SpecialGenericAlias):
988 return issubclass(cls.__origin__, self.__origin__)
989 if not isinstance(cls, _GenericAlias):
990 return issubclass(cls, self.__origin__)
991 return super().__subclasscheck__(cls)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700992
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100993 def __reduce__(self):
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +0300994 return self._name
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100995
Maggie Moss1b4552c2020-09-09 13:23:24 -0700996 def __or__(self, right):
997 return Union[self, right]
998
999 def __ror__(self, right):
1000 return Union[self, right]
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001001
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +03001002class _CallableGenericAlias(_GenericAlias, _root=True):
1003 def __repr__(self):
1004 assert self._name == 'Callable'
kj73607be2020-12-24 12:33:48 +08001005 args = self.__args__
1006 if len(args) == 2 and (args[0] is Ellipsis
1007 or isinstance(args[0], (ParamSpec, _ConcatenateGenericAlias))):
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +03001008 return super().__repr__()
1009 return (f'typing.Callable'
kj73607be2020-12-24 12:33:48 +08001010 f'[[{", ".join([_type_repr(a) for a in args[:-1]])}], '
1011 f'{_type_repr(args[-1])}]')
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +03001012
1013 def __reduce__(self):
1014 args = self.__args__
kj73607be2020-12-24 12:33:48 +08001015 if not (len(args) == 2 and (args[0] is Ellipsis
1016 or isinstance(args[0], (ParamSpec, _ConcatenateGenericAlias)))):
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +03001017 args = list(args[:-1]), args[-1]
1018 return operator.getitem, (Callable, args)
1019
1020
1021class _CallableType(_SpecialGenericAlias, _root=True):
1022 def copy_with(self, params):
1023 return _CallableGenericAlias(self.__origin__, params,
1024 name=self._name, inst=self._inst)
1025
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001026 def __getitem__(self, params):
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001027 if not isinstance(params, tuple) or len(params) != 2:
1028 raise TypeError("Callable must be used as "
1029 "Callable[[arg, ...], result].")
1030 args, result = params
kj463c7d32020-12-14 02:38:24 +08001031 # This relaxes what args can be on purpose to allow things like
1032 # PEP 612 ParamSpec. Responsibility for whether a user is using
1033 # Callable[...] properly is deferred to static type checkers.
1034 if isinstance(args, list):
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001035 params = (tuple(args), result)
kj463c7d32020-12-14 02:38:24 +08001036 else:
1037 params = (args, result)
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001038 return self.__getitem_inner__(params)
1039
1040 @_tp_cache
1041 def __getitem_inner__(self, params):
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +03001042 args, result = params
1043 msg = "Callable[args, result]: result must be a type."
1044 result = _type_check(result, msg)
1045 if args is Ellipsis:
1046 return self.copy_with((_TypingEllipsis, result))
kj463c7d32020-12-14 02:38:24 +08001047 if not isinstance(args, tuple):
1048 args = (args,)
1049 args = tuple(_type_convert(arg) for arg in args)
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +03001050 params = args + (result,)
1051 return self.copy_with(params)
1052
1053
1054class _TupleType(_SpecialGenericAlias, _root=True):
1055 @_tp_cache
1056 def __getitem__(self, params):
1057 if params == ():
1058 return self.copy_with((_TypingEmpty,))
1059 if not isinstance(params, tuple):
1060 params = (params,)
1061 if len(params) == 2 and params[1] is ...:
1062 msg = "Tuple[t, ...]: t must be a type."
1063 p = _type_check(params[0], msg)
1064 return self.copy_with((p, _TypingEllipsis))
1065 msg = "Tuple[t0, t1, ...]: each t must be a type."
1066 params = tuple(_type_check(p, msg) for p in params)
1067 return self.copy_with(params)
1068
1069
1070class _UnionGenericAlias(_GenericAlias, _root=True):
1071 def copy_with(self, params):
1072 return Union[params]
1073
1074 def __eq__(self, other):
1075 if not isinstance(other, _UnionGenericAlias):
1076 return NotImplemented
1077 return set(self.__args__) == set(other.__args__)
1078
1079 def __hash__(self):
1080 return hash(frozenset(self.__args__))
1081
1082 def __repr__(self):
1083 args = self.__args__
1084 if len(args) == 2:
1085 if args[0] is type(None):
1086 return f'typing.Optional[{_type_repr(args[1])}]'
1087 elif args[1] is type(None):
1088 return f'typing.Optional[{_type_repr(args[0])}]'
1089 return super().__repr__()
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001090
Maggie Moss1b4552c2020-09-09 13:23:24 -07001091 def __instancecheck__(self, obj):
1092 return self.__subclasscheck__(type(obj))
1093
1094 def __subclasscheck__(self, cls):
1095 for arg in self.__args__:
1096 if issubclass(cls, arg):
1097 return True
1098
1099
Yurii Karabasf03d3182020-11-17 04:23:19 +02001100def _value_and_type_iter(parameters):
1101 return ((p, type(p)) for p in parameters)
1102
1103
1104class _LiteralGenericAlias(_GenericAlias, _root=True):
1105
1106 def __eq__(self, other):
1107 if not isinstance(other, _LiteralGenericAlias):
1108 return NotImplemented
1109
1110 return set(_value_and_type_iter(self.__args__)) == set(_value_and_type_iter(other.__args__))
1111
1112 def __hash__(self):
Yurii Karabas1b540772020-11-19 18:17:38 +02001113 return hash(frozenset(_value_and_type_iter(self.__args__)))
Yurii Karabasf03d3182020-11-17 04:23:19 +02001114
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001115
kj73607be2020-12-24 12:33:48 +08001116class _ConcatenateGenericAlias(_GenericAlias, _root=True):
1117 pass
1118
1119
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001120class Generic:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001121 """Abstract base class for generic types.
1122
Guido van Rossumb24569a2016-11-20 18:01:29 -08001123 A generic type is typically declared by inheriting from
1124 this class parameterized with one or more type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001125 For example, a generic mapping type might be defined as::
1126
1127 class Mapping(Generic[KT, VT]):
1128 def __getitem__(self, key: KT) -> VT:
1129 ...
1130 # Etc.
1131
1132 This class can then be used as follows::
1133
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001134 def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001135 try:
1136 return mapping[key]
1137 except KeyError:
1138 return default
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001139 """
Guido van Rossumd70fe632015-08-05 12:11:06 +02001140 __slots__ = ()
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001141 _is_protocol = False
Guido van Rossumd70fe632015-08-05 12:11:06 +02001142
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001143 @_tp_cache
1144 def __class_getitem__(cls, params):
1145 if not isinstance(params, tuple):
1146 params = (params,)
1147 if not params and cls is not Tuple:
1148 raise TypeError(
1149 f"Parameter list to {cls.__qualname__}[...] cannot be empty")
kj73607be2020-12-24 12:33:48 +08001150 params = tuple(_type_convert(p) for p in params)
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001151 if cls in (Generic, Protocol):
1152 # Generic and Protocol can only be subscripted with unique type variables.
kj73607be2020-12-24 12:33:48 +08001153 if not all(isinstance(p, _TypeVarLike) for p in params):
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001154 raise TypeError(
kj73607be2020-12-24 12:33:48 +08001155 f"Parameters to {cls.__name__}[...] must all be type variables "
1156 f"or parameter specification variables.")
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001157 if len(set(params)) != len(params):
1158 raise TypeError(
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001159 f"Parameters to {cls.__name__}[...] must all be unique")
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001160 else:
1161 # Subscripting a regular Generic subclass.
kj73607be2020-12-24 12:33:48 +08001162 if any(isinstance(t, ParamSpec) for t in cls.__parameters__):
1163 params = _prepare_paramspec_params(cls, params)
Serhiy Storchakafcb28562020-05-10 11:53:16 +03001164 _check_generic(cls, params, len(cls.__parameters__))
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001165 return _GenericAlias(cls, params)
1166
1167 def __init_subclass__(cls, *args, **kwargs):
Ivan Levkivskyiee566fe2018-04-04 17:00:15 +01001168 super().__init_subclass__(*args, **kwargs)
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001169 tvars = []
1170 if '__orig_bases__' in cls.__dict__:
1171 error = Generic in cls.__orig_bases__
1172 else:
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001173 error = Generic in cls.__bases__ and cls.__name__ != 'Protocol'
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001174 if error:
1175 raise TypeError("Cannot inherit from plain Generic")
1176 if '__orig_bases__' in cls.__dict__:
1177 tvars = _collect_type_vars(cls.__orig_bases__)
1178 # Look for Generic[T1, ..., Tn].
1179 # If found, tvars must be a subset of it.
1180 # If not found, tvars is it.
1181 # Also check for and reject plain Generic,
1182 # and reject multiple Generic[...].
1183 gvars = None
1184 for base in cls.__orig_bases__:
1185 if (isinstance(base, _GenericAlias) and
1186 base.__origin__ is Generic):
1187 if gvars is not None:
1188 raise TypeError(
1189 "Cannot inherit from Generic[...] multiple types.")
1190 gvars = base.__parameters__
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001191 if gvars is not None:
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001192 tvarset = set(tvars)
1193 gvarset = set(gvars)
1194 if not tvarset <= gvarset:
1195 s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)
1196 s_args = ', '.join(str(g) for g in gvars)
1197 raise TypeError(f"Some type variables ({s_vars}) are"
1198 f" not listed in Generic[{s_args}]")
1199 tvars = gvars
1200 cls.__parameters__ = tuple(tvars)
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001201
1202
1203class _TypingEmpty:
Guido van Rossumb24569a2016-11-20 18:01:29 -08001204 """Internal placeholder for () or []. Used by TupleMeta and CallableMeta
1205 to allow empty list/tuple in specific places, without allowing them
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001206 to sneak in where prohibited.
1207 """
1208
1209
1210class _TypingEllipsis:
Guido van Rossumb24569a2016-11-20 18:01:29 -08001211 """Internal placeholder for ... (ellipsis)."""
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001212
1213
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001214_TYPING_INTERNALS = ['__parameters__', '__orig_bases__', '__orig_class__',
1215 '_is_protocol', '_is_runtime_protocol']
1216
1217_SPECIAL_NAMES = ['__abstractmethods__', '__annotations__', '__dict__', '__doc__',
1218 '__init__', '__module__', '__new__', '__slots__',
Guido van Rossum48b069a2020-04-07 09:50:06 -07001219 '__subclasshook__', '__weakref__', '__class_getitem__']
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001220
1221# These special attributes will be not collected as protocol members.
1222EXCLUDED_ATTRIBUTES = _TYPING_INTERNALS + _SPECIAL_NAMES + ['_MutableMapping__marker']
1223
1224
1225def _get_protocol_attrs(cls):
1226 """Collect protocol members from a protocol class objects.
1227
1228 This includes names actually defined in the class dictionary, as well
1229 as names that appear in annotations. Special names (above) are skipped.
1230 """
1231 attrs = set()
1232 for base in cls.__mro__[:-1]: # without object
1233 if base.__name__ in ('Protocol', 'Generic'):
1234 continue
1235 annotations = getattr(base, '__annotations__', {})
1236 for attr in list(base.__dict__.keys()) + list(annotations.keys()):
1237 if not attr.startswith('_abc_') and attr not in EXCLUDED_ATTRIBUTES:
1238 attrs.add(attr)
1239 return attrs
1240
1241
1242def _is_callable_members_only(cls):
1243 # PEP 544 prohibits using issubclass() with protocols that have non-method members.
1244 return all(callable(getattr(cls, attr, None)) for attr in _get_protocol_attrs(cls))
1245
1246
1247def _no_init(self, *args, **kwargs):
1248 if type(self)._is_protocol:
1249 raise TypeError('Protocols cannot be instantiated')
1250
1251
Rossc1af1282020-12-29 11:55:28 +00001252def _allow_reckless_class_checks():
Nickolena Fishercfaf4c02020-04-26 12:49:11 -05001253 """Allow instance and class checks for special stdlib modules.
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001254
1255 The abc and functools modules indiscriminately call isinstance() and
1256 issubclass() on the whole MRO of a user class, which may contain protocols.
1257 """
1258 try:
1259 return sys._getframe(3).f_globals['__name__'] in ['abc', 'functools']
1260 except (AttributeError, ValueError): # For platforms without _getframe().
1261 return True
1262
1263
Victor Stinner0e95bbf2020-08-12 10:53:12 +02001264_PROTO_ALLOWLIST = {
Divij Rajkumar692a0dc2019-09-12 11:13:51 +01001265 'collections.abc': [
1266 'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable',
1267 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible',
1268 ],
1269 'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'],
1270}
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001271
1272
1273class _ProtocolMeta(ABCMeta):
1274 # This metaclass is really unfortunate and exists only because of
1275 # the lack of __instancehook__.
1276 def __instancecheck__(cls, instance):
1277 # We need this method for situations where attributes are
1278 # assigned in __init__.
1279 if ((not getattr(cls, '_is_protocol', False) or
1280 _is_callable_members_only(cls)) and
1281 issubclass(instance.__class__, cls)):
1282 return True
1283 if cls._is_protocol:
1284 if all(hasattr(instance, attr) and
1285 # All *methods* can be blocked by setting them to None.
1286 (not callable(getattr(cls, attr, None)) or
1287 getattr(instance, attr) is not None)
1288 for attr in _get_protocol_attrs(cls)):
1289 return True
1290 return super().__instancecheck__(instance)
1291
1292
1293class Protocol(Generic, metaclass=_ProtocolMeta):
1294 """Base class for protocol classes.
1295
1296 Protocol classes are defined as::
1297
1298 class Proto(Protocol):
1299 def meth(self) -> int:
1300 ...
1301
1302 Such classes are primarily used with static type checkers that recognize
1303 structural subtyping (static duck-typing), for example::
1304
1305 class C:
1306 def meth(self) -> int:
1307 return 0
1308
1309 def func(x: Proto) -> int:
1310 return x.meth()
1311
1312 func(C()) # Passes static type check
1313
1314 See PEP 544 for details. Protocol classes decorated with
1315 @typing.runtime_checkable act as simple-minded runtime protocols that check
1316 only the presence of given attributes, ignoring their type signatures.
1317 Protocol classes can be generic, they are defined as::
1318
1319 class GenProto(Protocol[T]):
1320 def meth(self) -> T:
1321 ...
1322 """
1323 __slots__ = ()
1324 _is_protocol = True
1325 _is_runtime_protocol = False
1326
1327 def __init_subclass__(cls, *args, **kwargs):
1328 super().__init_subclass__(*args, **kwargs)
1329
1330 # Determine if this is a protocol or a concrete subclass.
1331 if not cls.__dict__.get('_is_protocol', False):
1332 cls._is_protocol = any(b is Protocol for b in cls.__bases__)
1333
1334 # Set (or override) the protocol subclass hook.
1335 def _proto_hook(other):
1336 if not cls.__dict__.get('_is_protocol', False):
1337 return NotImplemented
1338
1339 # First, perform various sanity checks.
1340 if not getattr(cls, '_is_runtime_protocol', False):
Rossc1af1282020-12-29 11:55:28 +00001341 if _allow_reckless_class_checks():
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001342 return NotImplemented
1343 raise TypeError("Instance and class checks can only be used with"
1344 " @runtime_checkable protocols")
1345 if not _is_callable_members_only(cls):
Rossc1af1282020-12-29 11:55:28 +00001346 if _allow_reckless_class_checks():
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001347 return NotImplemented
1348 raise TypeError("Protocols with non-method members"
1349 " don't support issubclass()")
1350 if not isinstance(other, type):
1351 # Same error message as for issubclass(1, int).
1352 raise TypeError('issubclass() arg 1 must be a class')
1353
1354 # Second, perform the actual structural compatibility check.
1355 for attr in _get_protocol_attrs(cls):
1356 for base in other.__mro__:
1357 # Check if the members appears in the class dictionary...
1358 if attr in base.__dict__:
1359 if base.__dict__[attr] is None:
1360 return NotImplemented
1361 break
1362
1363 # ...or in annotations, if it is a sub-protocol.
1364 annotations = getattr(base, '__annotations__', {})
1365 if (isinstance(annotations, collections.abc.Mapping) and
1366 attr in annotations and
1367 issubclass(other, Generic) and other._is_protocol):
1368 break
1369 else:
1370 return NotImplemented
1371 return True
1372
1373 if '__subclasshook__' not in cls.__dict__:
1374 cls.__subclasshook__ = _proto_hook
1375
1376 # We have nothing more to do for non-protocols...
1377 if not cls._is_protocol:
1378 return
1379
1380 # ... otherwise check consistency of bases, and prohibit instantiation.
1381 for base in cls.__bases__:
1382 if not (base in (object, Generic) or
Victor Stinner0e95bbf2020-08-12 10:53:12 +02001383 base.__module__ in _PROTO_ALLOWLIST and
1384 base.__name__ in _PROTO_ALLOWLIST[base.__module__] or
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001385 issubclass(base, Generic) and base._is_protocol):
1386 raise TypeError('Protocols can only inherit from other'
1387 ' protocols, got %r' % base)
1388 cls.__init__ = _no_init
1389
1390
Jakub Stasiakcf5b1092020-02-05 02:10:19 +01001391class _AnnotatedAlias(_GenericAlias, _root=True):
1392 """Runtime representation of an annotated type.
1393
1394 At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
1395 with extra annotations. The alias behaves like a normal typing alias,
1396 instantiating is the same as instantiating the underlying type, binding
1397 it to types is also the same.
1398 """
1399 def __init__(self, origin, metadata):
1400 if isinstance(origin, _AnnotatedAlias):
1401 metadata = origin.__metadata__ + metadata
1402 origin = origin.__origin__
1403 super().__init__(origin, origin)
1404 self.__metadata__ = metadata
1405
1406 def copy_with(self, params):
1407 assert len(params) == 1
1408 new_type = params[0]
1409 return _AnnotatedAlias(new_type, self.__metadata__)
1410
1411 def __repr__(self):
1412 return "typing.Annotated[{}, {}]".format(
1413 _type_repr(self.__origin__),
1414 ", ".join(repr(a) for a in self.__metadata__)
1415 )
1416
1417 def __reduce__(self):
1418 return operator.getitem, (
1419 Annotated, (self.__origin__,) + self.__metadata__
1420 )
1421
1422 def __eq__(self, other):
1423 if not isinstance(other, _AnnotatedAlias):
1424 return NotImplemented
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +03001425 return (self.__origin__ == other.__origin__
1426 and self.__metadata__ == other.__metadata__)
Jakub Stasiakcf5b1092020-02-05 02:10:19 +01001427
1428 def __hash__(self):
1429 return hash((self.__origin__, self.__metadata__))
1430
1431
1432class Annotated:
1433 """Add context specific metadata to a type.
1434
1435 Example: Annotated[int, runtime_check.Unsigned] indicates to the
1436 hypothetical runtime_check module that this type is an unsigned int.
1437 Every other consumer of this type can ignore this metadata and treat
1438 this type as int.
1439
1440 The first argument to Annotated must be a valid type.
1441
1442 Details:
1443
1444 - It's an error to call `Annotated` with less than two arguments.
1445 - Nested Annotated are flattened::
1446
1447 Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
1448
1449 - Instantiating an annotated type is equivalent to instantiating the
1450 underlying type::
1451
1452 Annotated[C, Ann1](5) == C(5)
1453
1454 - Annotated can be used as a generic type alias::
1455
1456 Optimized = Annotated[T, runtime.Optimize()]
1457 Optimized[int] == Annotated[int, runtime.Optimize()]
1458
1459 OptimizedList = Annotated[List[T], runtime.Optimize()]
1460 OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
1461 """
1462
1463 __slots__ = ()
1464
1465 def __new__(cls, *args, **kwargs):
1466 raise TypeError("Type Annotated cannot be instantiated.")
1467
1468 @_tp_cache
1469 def __class_getitem__(cls, params):
1470 if not isinstance(params, tuple) or len(params) < 2:
1471 raise TypeError("Annotated[...] should be used "
1472 "with at least two arguments (a type and an "
1473 "annotation).")
1474 msg = "Annotated[t, ...]: t must be a type."
1475 origin = _type_check(params[0], msg)
1476 metadata = tuple(params[1:])
1477 return _AnnotatedAlias(origin, metadata)
1478
1479 def __init_subclass__(cls, *args, **kwargs):
1480 raise TypeError(
1481 "Cannot subclass {}.Annotated".format(cls.__module__)
1482 )
1483
1484
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001485def runtime_checkable(cls):
1486 """Mark a protocol class as a runtime protocol.
1487
1488 Such protocol can be used with isinstance() and issubclass().
1489 Raise TypeError if applied to a non-protocol class.
1490 This allows a simple-minded structural check very similar to
1491 one trick ponies in collections.abc such as Iterable.
1492 For example::
1493
1494 @runtime_checkable
1495 class Closable(Protocol):
1496 def close(self): ...
1497
1498 assert isinstance(open('/some/file'), Closable)
1499
1500 Warning: this will check only the presence of the required methods,
1501 not their type signatures!
1502 """
1503 if not issubclass(cls, Generic) or not cls._is_protocol:
1504 raise TypeError('@runtime_checkable can be only applied to protocol classes,'
1505 ' got %r' % cls)
1506 cls._is_runtime_protocol = True
1507 return cls
1508
1509
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001510def cast(typ, val):
1511 """Cast a value to a type.
1512
1513 This returns the value unchanged. To the type checker this
1514 signals that the return value has the designated type, but at
1515 runtime we intentionally don't check anything (we want this
1516 to be as fast as possible).
1517 """
1518 return val
1519
1520
1521def _get_defaults(func):
1522 """Internal helper to extract the default arguments, by name."""
Guido van Rossum991d14f2016-11-09 13:12:51 -08001523 try:
1524 code = func.__code__
1525 except AttributeError:
1526 # Some built-in functions don't have __code__, __defaults__, etc.
1527 return {}
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001528 pos_count = code.co_argcount
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001529 arg_names = code.co_varnames
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001530 arg_names = arg_names[:pos_count]
1531 defaults = func.__defaults__ or ()
1532 kwdefaults = func.__kwdefaults__
1533 res = dict(kwdefaults) if kwdefaults else {}
1534 pos_offset = pos_count - len(defaults)
1535 for name, value in zip(arg_names[pos_offset:], defaults):
1536 assert name not in res
1537 res[name] = value
1538 return res
1539
1540
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001541_allowed_types = (types.FunctionType, types.BuiltinFunctionType,
1542 types.MethodType, types.ModuleType,
Ivan Levkivskyif06e0212017-05-02 19:14:07 +02001543 WrapperDescriptorType, MethodWrapperType, MethodDescriptorType)
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001544
1545
Jakub Stasiakcf5b1092020-02-05 02:10:19 +01001546def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
Guido van Rossum991d14f2016-11-09 13:12:51 -08001547 """Return type hints for an object.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001548
Guido van Rossum991d14f2016-11-09 13:12:51 -08001549 This is often the same as obj.__annotations__, but it handles
Jakub Stasiakcf5b1092020-02-05 02:10:19 +01001550 forward references encoded as string literals, adds Optional[t] if a
1551 default value equal to None is set and recursively replaces all
1552 'Annotated[T, ...]' with 'T' (unless 'include_extras=True').
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001553
Guido van Rossum991d14f2016-11-09 13:12:51 -08001554 The argument may be a module, class, method, or function. The annotations
1555 are returned as a dictionary. For classes, annotations include also
1556 inherited members.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001557
Guido van Rossum991d14f2016-11-09 13:12:51 -08001558 TypeError is raised if the argument is not of a type that can contain
1559 annotations, and an empty dictionary is returned if no annotations are
1560 present.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001561
Guido van Rossum991d14f2016-11-09 13:12:51 -08001562 BEWARE -- the behavior of globalns and localns is counterintuitive
1563 (unless you are familiar with how eval() and exec() work). The
1564 search order is locals first, then globals.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001565
Guido van Rossum991d14f2016-11-09 13:12:51 -08001566 - If no dict arguments are passed, an attempt is made to use the
Łukasz Langaf350a262017-09-14 14:33:00 -04001567 globals from obj (or the respective module's globals for classes),
1568 and these are also used as the locals. If the object does not appear
1569 to have globals, an empty dictionary is used.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001570
Guido van Rossum991d14f2016-11-09 13:12:51 -08001571 - If one dict argument is passed, it is used for both globals and
1572 locals.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001573
Guido van Rossum991d14f2016-11-09 13:12:51 -08001574 - If two dict arguments are passed, they specify globals and
1575 locals, respectively.
1576 """
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001577
Guido van Rossum991d14f2016-11-09 13:12:51 -08001578 if getattr(obj, '__no_type_check__', None):
1579 return {}
Guido van Rossum991d14f2016-11-09 13:12:51 -08001580 # Classes require a special treatment.
1581 if isinstance(obj, type):
1582 hints = {}
1583 for base in reversed(obj.__mro__):
Łukasz Langaf350a262017-09-14 14:33:00 -04001584 if globalns is None:
1585 base_globals = sys.modules[base.__module__].__dict__
1586 else:
1587 base_globals = globalns
Guido van Rossum991d14f2016-11-09 13:12:51 -08001588 ann = base.__dict__.get('__annotations__', {})
1589 for name, value in ann.items():
1590 if value is None:
1591 value = type(None)
1592 if isinstance(value, str):
Nina Zakharenko0e61dff2018-05-22 20:32:10 -07001593 value = ForwardRef(value, is_argument=False)
Łukasz Langaf350a262017-09-14 14:33:00 -04001594 value = _eval_type(value, base_globals, localns)
Guido van Rossum991d14f2016-11-09 13:12:51 -08001595 hints[name] = value
Jakub Stasiakcf5b1092020-02-05 02:10:19 +01001596 return hints if include_extras else {k: _strip_annotations(t) for k, t in hints.items()}
Łukasz Langaf350a262017-09-14 14:33:00 -04001597
1598 if globalns is None:
1599 if isinstance(obj, types.ModuleType):
1600 globalns = obj.__dict__
1601 else:
benedwards140aca3a32019-11-21 17:24:58 +00001602 nsobj = obj
1603 # Find globalns for the unwrapped object.
1604 while hasattr(nsobj, '__wrapped__'):
1605 nsobj = nsobj.__wrapped__
1606 globalns = getattr(nsobj, '__globals__', {})
Łukasz Langaf350a262017-09-14 14:33:00 -04001607 if localns is None:
1608 localns = globalns
1609 elif localns is None:
1610 localns = globalns
Guido van Rossum991d14f2016-11-09 13:12:51 -08001611 hints = getattr(obj, '__annotations__', None)
1612 if hints is None:
1613 # Return empty annotations for something that _could_ have them.
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001614 if isinstance(obj, _allowed_types):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001615 return {}
Guido van Rossum991d14f2016-11-09 13:12:51 -08001616 else:
1617 raise TypeError('{!r} is not a module, class, method, '
1618 'or function.'.format(obj))
1619 defaults = _get_defaults(obj)
1620 hints = dict(hints)
1621 for name, value in hints.items():
1622 if value is None:
1623 value = type(None)
1624 if isinstance(value, str):
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001625 value = ForwardRef(value)
Guido van Rossum991d14f2016-11-09 13:12:51 -08001626 value = _eval_type(value, globalns, localns)
1627 if name in defaults and defaults[name] is None:
1628 value = Optional[value]
1629 hints[name] = value
Jakub Stasiakcf5b1092020-02-05 02:10:19 +01001630 return hints if include_extras else {k: _strip_annotations(t) for k, t in hints.items()}
1631
1632
1633def _strip_annotations(t):
1634 """Strips the annotations from a given type.
1635 """
1636 if isinstance(t, _AnnotatedAlias):
1637 return _strip_annotations(t.__origin__)
1638 if isinstance(t, _GenericAlias):
1639 stripped_args = tuple(_strip_annotations(a) for a in t.__args__)
1640 if stripped_args == t.__args__:
1641 return t
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +03001642 return t.copy_with(stripped_args)
Serhiy Storchaka68b352a2020-04-26 21:21:08 +03001643 if isinstance(t, GenericAlias):
1644 stripped_args = tuple(_strip_annotations(a) for a in t.__args__)
1645 if stripped_args == t.__args__:
1646 return t
1647 return GenericAlias(t.__origin__, stripped_args)
Jakub Stasiakcf5b1092020-02-05 02:10:19 +01001648 return t
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001649
1650
Ivan Levkivskyi4c23aff2019-05-31 00:10:07 +01001651def get_origin(tp):
1652 """Get the unsubscripted version of a type.
1653
Jakub Stasiak38aaaaa2020-02-07 02:15:12 +01001654 This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
1655 and Annotated. Return None for unsupported types. Examples::
Ivan Levkivskyi4c23aff2019-05-31 00:10:07 +01001656
1657 get_origin(Literal[42]) is Literal
1658 get_origin(int) is None
1659 get_origin(ClassVar[int]) is ClassVar
1660 get_origin(Generic) is Generic
1661 get_origin(Generic[T]) is Generic
1662 get_origin(Union[T, int]) is Union
1663 get_origin(List[Tuple[T, T]][int]) == list
1664 """
Jakub Stasiakcf5b1092020-02-05 02:10:19 +01001665 if isinstance(tp, _AnnotatedAlias):
1666 return Annotated
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +03001667 if isinstance(tp, (_BaseGenericAlias, GenericAlias)):
Ivan Levkivskyi4c23aff2019-05-31 00:10:07 +01001668 return tp.__origin__
1669 if tp is Generic:
1670 return Generic
Ken Jinefb1f092020-12-29 10:26:19 +08001671 if isinstance(tp, types.Union):
1672 return types.Union
Ivan Levkivskyi4c23aff2019-05-31 00:10:07 +01001673 return None
1674
1675
1676def get_args(tp):
1677 """Get type arguments with all substitutions performed.
1678
1679 For unions, basic simplifications used by Union constructor are performed.
1680 Examples::
1681 get_args(Dict[str, int]) == (str, int)
1682 get_args(int) == ()
1683 get_args(Union[int, Union[T, int], str][int]) == (int, str)
1684 get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
1685 get_args(Callable[[], T][int]) == ([], int)
1686 """
Jakub Stasiakcf5b1092020-02-05 02:10:19 +01001687 if isinstance(tp, _AnnotatedAlias):
1688 return (tp.__origin__,) + tp.__metadata__
Ken Jin4140f102020-12-29 04:06:19 +08001689 if isinstance(tp, (_GenericAlias, GenericAlias)):
Ivan Levkivskyi4c23aff2019-05-31 00:10:07 +01001690 res = tp.__args__
Ken Jinefb1f092020-12-29 10:26:19 +08001691 if (tp.__origin__ is collections.abc.Callable
1692 and not (res[0] is Ellipsis
1693 or isinstance(res[0], (ParamSpec, _ConcatenateGenericAlias)))):
Ivan Levkivskyi4c23aff2019-05-31 00:10:07 +01001694 res = (list(res[:-1]), res[-1])
1695 return res
Ken Jinefb1f092020-12-29 10:26:19 +08001696 if isinstance(tp, types.Union):
1697 return tp.__args__
Ivan Levkivskyi4c23aff2019-05-31 00:10:07 +01001698 return ()
1699
1700
Patrick Reader0705ec82020-09-16 05:58:32 +01001701def is_typeddict(tp):
1702 """Check if an annotation is a TypedDict class
1703
1704 For example::
1705 class Film(TypedDict):
1706 title: str
1707 year: int
1708
1709 is_typeddict(Film) # => True
1710 is_typeddict(Union[list, str]) # => False
1711 """
1712 return isinstance(tp, _TypedDictMeta)
1713
1714
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001715def no_type_check(arg):
1716 """Decorator to indicate that annotations are not type hints.
1717
1718 The argument must be a class or function; if it is a class, it
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001719 applies recursively to all methods and classes defined in that class
1720 (but not to methods defined in its superclasses or subclasses).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001721
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001722 This mutates the function(s) or class(es) in place.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001723 """
1724 if isinstance(arg, type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001725 arg_attrs = arg.__dict__.copy()
1726 for attr, val in arg.__dict__.items():
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001727 if val in arg.__bases__ + (arg,):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001728 arg_attrs.pop(attr)
1729 for obj in arg_attrs.values():
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001730 if isinstance(obj, types.FunctionType):
1731 obj.__no_type_check__ = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001732 if isinstance(obj, type):
1733 no_type_check(obj)
1734 try:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001735 arg.__no_type_check__ = True
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001736 except TypeError: # built-in classes
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001737 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001738 return arg
1739
1740
1741def no_type_check_decorator(decorator):
1742 """Decorator to give another decorator the @no_type_check effect.
1743
1744 This wraps the decorator with something that wraps the decorated
1745 function in @no_type_check.
1746 """
1747
1748 @functools.wraps(decorator)
1749 def wrapped_decorator(*args, **kwds):
1750 func = decorator(*args, **kwds)
1751 func = no_type_check(func)
1752 return func
1753
1754 return wrapped_decorator
1755
1756
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001757def _overload_dummy(*args, **kwds):
1758 """Helper for @overload to raise when called."""
1759 raise NotImplementedError(
1760 "You should not call an overloaded function. "
1761 "A series of @overload-decorated functions "
1762 "outside a stub module should always be followed "
1763 "by an implementation that is not @overload-ed.")
1764
1765
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001766def overload(func):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001767 """Decorator for overloaded functions/methods.
1768
1769 In a stub file, place two or more stub definitions for the same
1770 function in a row, each decorated with @overload. For example:
1771
1772 @overload
1773 def utf8(value: None) -> None: ...
1774 @overload
1775 def utf8(value: bytes) -> bytes: ...
1776 @overload
1777 def utf8(value: str) -> bytes: ...
1778
1779 In a non-stub file (i.e. a regular .py file), do the same but
1780 follow it with an implementation. The implementation should *not*
1781 be decorated with @overload. For example:
1782
1783 @overload
1784 def utf8(value: None) -> None: ...
1785 @overload
1786 def utf8(value: bytes) -> bytes: ...
1787 @overload
1788 def utf8(value: str) -> bytes: ...
1789 def utf8(value):
1790 # implementation goes here
1791 """
1792 return _overload_dummy
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001793
1794
Ivan Levkivskyif3672422019-05-26 09:37:07 +01001795def final(f):
1796 """A decorator to indicate final methods and final classes.
1797
1798 Use this decorator to indicate to type checkers that the decorated
1799 method cannot be overridden, and decorated class cannot be subclassed.
1800 For example:
1801
1802 class Base:
1803 @final
1804 def done(self) -> None:
1805 ...
1806 class Sub(Base):
1807 def done(self) -> None: # Error reported by type checker
1808 ...
1809
1810 @final
1811 class Leaf:
1812 ...
1813 class Other(Leaf): # Error reported by type checker
1814 ...
1815
1816 There is no runtime checking of these properties.
1817 """
1818 return f
1819
1820
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001821# Some unconstrained type variables. These are used by the container types.
1822# (These are not for export.)
1823T = TypeVar('T') # Any type.
1824KT = TypeVar('KT') # Key type.
1825VT = TypeVar('VT') # Value type.
1826T_co = TypeVar('T_co', covariant=True) # Any type covariant containers.
1827V_co = TypeVar('V_co', covariant=True) # Any type covariant containers.
1828VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
1829T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
1830# Internal type variable used for Type[].
1831CT_co = TypeVar('CT_co', covariant=True, bound=type)
1832
1833# A useful type variable with constraints. This represents string types.
1834# (This one *is* for export!)
1835AnyStr = TypeVar('AnyStr', bytes, str)
1836
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001837
1838# Various ABCs mimicking those in collections.abc.
Serhiy Storchakac1c7d8e2020-05-07 04:09:33 +03001839_alias = _SpecialGenericAlias
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001840
Serhiy Storchakafcb28562020-05-10 11:53:16 +03001841Hashable = _alias(collections.abc.Hashable, 0) # Not generic.
1842Awaitable = _alias(collections.abc.Awaitable, 1)
1843Coroutine = _alias(collections.abc.Coroutine, 3)
1844AsyncIterable = _alias(collections.abc.AsyncIterable, 1)
1845AsyncIterator = _alias(collections.abc.AsyncIterator, 1)
1846Iterable = _alias(collections.abc.Iterable, 1)
1847Iterator = _alias(collections.abc.Iterator, 1)
1848Reversible = _alias(collections.abc.Reversible, 1)
1849Sized = _alias(collections.abc.Sized, 0) # Not generic.
1850Container = _alias(collections.abc.Container, 1)
1851Collection = _alias(collections.abc.Collection, 1)
1852Callable = _CallableType(collections.abc.Callable, 2)
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001853Callable.__doc__ = \
1854 """Callable type; Callable[[int], str] is a function of (int) -> str.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001855
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001856 The subscription syntax must always be used with exactly two
1857 values: the argument list and the return type. The argument list
1858 must be a list of types or ellipsis; the return type must be a single type.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001859
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001860 There is no syntax to indicate optional or keyword arguments,
1861 such function types are rarely used as callback types.
1862 """
Serhiy Storchakafcb28562020-05-10 11:53:16 +03001863AbstractSet = _alias(collections.abc.Set, 1, name='AbstractSet')
1864MutableSet = _alias(collections.abc.MutableSet, 1)
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001865# NOTE: Mapping is only covariant in the value type.
Serhiy Storchakafcb28562020-05-10 11:53:16 +03001866Mapping = _alias(collections.abc.Mapping, 2)
1867MutableMapping = _alias(collections.abc.MutableMapping, 2)
1868Sequence = _alias(collections.abc.Sequence, 1)
1869MutableSequence = _alias(collections.abc.MutableSequence, 1)
1870ByteString = _alias(collections.abc.ByteString, 0) # Not generic
1871# Tuple accepts variable number of parameters.
1872Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001873Tuple.__doc__ = \
1874 """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001875
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001876 Example: Tuple[T1, T2] is a tuple of two elements corresponding
1877 to type variables T1 and T2. Tuple[int, float, str] is a tuple
1878 of an int, a float and a string.
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001879
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001880 To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
1881 """
Serhiy Storchakafcb28562020-05-10 11:53:16 +03001882List = _alias(list, 1, inst=False, name='List')
1883Deque = _alias(collections.deque, 1, name='Deque')
1884Set = _alias(set, 1, inst=False, name='Set')
1885FrozenSet = _alias(frozenset, 1, inst=False, name='FrozenSet')
1886MappingView = _alias(collections.abc.MappingView, 1)
1887KeysView = _alias(collections.abc.KeysView, 1)
1888ItemsView = _alias(collections.abc.ItemsView, 2)
1889ValuesView = _alias(collections.abc.ValuesView, 1)
1890ContextManager = _alias(contextlib.AbstractContextManager, 1, name='ContextManager')
1891AsyncContextManager = _alias(contextlib.AbstractAsyncContextManager, 1, name='AsyncContextManager')
1892Dict = _alias(dict, 2, inst=False, name='Dict')
1893DefaultDict = _alias(collections.defaultdict, 2, name='DefaultDict')
1894OrderedDict = _alias(collections.OrderedDict, 2)
1895Counter = _alias(collections.Counter, 1)
1896ChainMap = _alias(collections.ChainMap, 2)
1897Generator = _alias(collections.abc.Generator, 3)
1898AsyncGenerator = _alias(collections.abc.AsyncGenerator, 2)
1899Type = _alias(type, 1, inst=False, name='Type')
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001900Type.__doc__ = \
1901 """A special construct usable to annotate class objects.
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001902
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001903 For example, suppose we have the following classes::
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001904
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001905 class User: ... # Abstract base for User classes
1906 class BasicUser(User): ...
1907 class ProUser(User): ...
1908 class TeamUser(User): ...
Guido van Rossumf17c2002015-12-03 17:31:24 -08001909
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001910 And a function that takes a class argument that's a subclass of
1911 User and returns an instance of the corresponding class::
Guido van Rossumf17c2002015-12-03 17:31:24 -08001912
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001913 U = TypeVar('U', bound=User)
1914 def new_user(user_class: Type[U]) -> U:
1915 user = user_class()
1916 # (Here we could write the user object to a database)
1917 return user
Guido van Rossumf17c2002015-12-03 17:31:24 -08001918
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001919 joe = new_user(BasicUser)
Guido van Rossumf17c2002015-12-03 17:31:24 -08001920
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001921 At this point the type checker knows that joe has type BasicUser.
1922 """
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001923
1924
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001925@runtime_checkable
1926class SupportsInt(Protocol):
Serhiy Storchaka8252c522019-10-08 16:30:17 +03001927 """An ABC with one abstract method __int__."""
Guido van Rossumd70fe632015-08-05 12:11:06 +02001928 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001929
1930 @abstractmethod
1931 def __int__(self) -> int:
1932 pass
1933
1934
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001935@runtime_checkable
1936class SupportsFloat(Protocol):
Serhiy Storchaka8252c522019-10-08 16:30:17 +03001937 """An ABC with one abstract method __float__."""
Guido van Rossumd70fe632015-08-05 12:11:06 +02001938 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001939
1940 @abstractmethod
1941 def __float__(self) -> float:
1942 pass
1943
1944
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001945@runtime_checkable
1946class SupportsComplex(Protocol):
Serhiy Storchaka8252c522019-10-08 16:30:17 +03001947 """An ABC with one abstract method __complex__."""
Guido van Rossumd70fe632015-08-05 12:11:06 +02001948 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001949
1950 @abstractmethod
1951 def __complex__(self) -> complex:
1952 pass
1953
1954
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001955@runtime_checkable
1956class SupportsBytes(Protocol):
Serhiy Storchaka8252c522019-10-08 16:30:17 +03001957 """An ABC with one abstract method __bytes__."""
Guido van Rossumd70fe632015-08-05 12:11:06 +02001958 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001959
1960 @abstractmethod
1961 def __bytes__(self) -> bytes:
1962 pass
1963
1964
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001965@runtime_checkable
1966class SupportsIndex(Protocol):
Serhiy Storchaka8252c522019-10-08 16:30:17 +03001967 """An ABC with one abstract method __index__."""
Paul Dagnelie4c7a46e2019-05-22 07:23:01 -07001968 __slots__ = ()
1969
1970 @abstractmethod
1971 def __index__(self) -> int:
1972 pass
1973
1974
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001975@runtime_checkable
1976class SupportsAbs(Protocol[T_co]):
Serhiy Storchaka8252c522019-10-08 16:30:17 +03001977 """An ABC with one abstract method __abs__ that is covariant in its return type."""
Guido van Rossumd70fe632015-08-05 12:11:06 +02001978 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001979
1980 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001981 def __abs__(self) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001982 pass
1983
1984
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001985@runtime_checkable
1986class SupportsRound(Protocol[T_co]):
Serhiy Storchaka8252c522019-10-08 16:30:17 +03001987 """An ABC with one abstract method __round__ that is covariant in its return type."""
Guido van Rossumd70fe632015-08-05 12:11:06 +02001988 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001989
1990 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001991 def __round__(self, ndigits: int = 0) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001992 pass
1993
1994
Serhiy Storchakaa2ec0692020-04-08 10:59:04 +03001995def _make_nmtuple(name, types, module, defaults = ()):
1996 fields = [n for n, t in types]
1997 types = {n: _type_check(t, f"field {n} annotation must be a type")
1998 for n, t in types}
1999 nm_tpl = collections.namedtuple(name, fields,
2000 defaults=defaults, module=module)
2001 nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = types
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002002 return nm_tpl
2003
2004
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01002005# attributes prohibited to set in NamedTuple class syntax
Serhiy Storchakaa2ec0692020-04-08 10:59:04 +03002006_prohibited = frozenset({'__new__', '__init__', '__slots__', '__getnewargs__',
2007 '_fields', '_field_defaults',
2008 '_make', '_replace', '_asdict', '_source'})
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01002009
Serhiy Storchakaa2ec0692020-04-08 10:59:04 +03002010_special = frozenset({'__module__', '__name__', '__annotations__'})
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01002011
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002012
Guido van Rossum2f841442016-11-15 09:48:06 -08002013class NamedTupleMeta(type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002014
Guido van Rossum2f841442016-11-15 09:48:06 -08002015 def __new__(cls, typename, bases, ns):
Serhiy Storchakaa2ec0692020-04-08 10:59:04 +03002016 assert bases[0] is _NamedTuple
Guido van Rossum2f841442016-11-15 09:48:06 -08002017 types = ns.get('__annotations__', {})
Serhiy Storchakaa2ec0692020-04-08 10:59:04 +03002018 default_names = []
Guido van Rossum3c268be2017-01-18 08:03:50 -08002019 for field_name in types:
2020 if field_name in ns:
Serhiy Storchakaa2ec0692020-04-08 10:59:04 +03002021 default_names.append(field_name)
2022 elif default_names:
2023 raise TypeError(f"Non-default namedtuple field {field_name} "
2024 f"cannot follow default field"
2025 f"{'s' if len(default_names) > 1 else ''} "
2026 f"{', '.join(default_names)}")
2027 nm_tpl = _make_nmtuple(typename, types.items(),
2028 defaults=[ns[n] for n in default_names],
2029 module=ns['__module__'])
Guido van Rossum95919c02017-01-22 17:47:20 -08002030 # update from user namespace without overriding special namedtuple attributes
2031 for key in ns:
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01002032 if key in _prohibited:
2033 raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
2034 elif key not in _special and key not in nm_tpl._fields:
Guido van Rossum95919c02017-01-22 17:47:20 -08002035 setattr(nm_tpl, key, ns[key])
Guido van Rossum3c268be2017-01-18 08:03:50 -08002036 return nm_tpl
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002037
Guido van Rossumd7adfe12017-01-22 17:43:53 -08002038
Serhiy Storchakaa2ec0692020-04-08 10:59:04 +03002039def NamedTuple(typename, fields=None, /, **kwargs):
Guido van Rossum2f841442016-11-15 09:48:06 -08002040 """Typed version of namedtuple.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002041
Guido van Rossum2f841442016-11-15 09:48:06 -08002042 Usage in Python versions >= 3.6::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002043
Guido van Rossum2f841442016-11-15 09:48:06 -08002044 class Employee(NamedTuple):
2045 name: str
2046 id: int
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002047
Guido van Rossum2f841442016-11-15 09:48:06 -08002048 This is equivalent to::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002049
Guido van Rossum2f841442016-11-15 09:48:06 -08002050 Employee = collections.namedtuple('Employee', ['name', 'id'])
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002051
Raymond Hettingerf7b57df2019-03-18 09:53:56 -07002052 The resulting class has an extra __annotations__ attribute, giving a
2053 dict that maps field names to types. (The field names are also in
2054 the _fields attribute, which is part of the namedtuple API.)
2055 Alternative equivalent keyword syntax is also accepted::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002056
Guido van Rossum2f841442016-11-15 09:48:06 -08002057 Employee = NamedTuple('Employee', name=str, id=int)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002058
Guido van Rossum2f841442016-11-15 09:48:06 -08002059 In Python versions <= 3.5 use::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002060
Guido van Rossum2f841442016-11-15 09:48:06 -08002061 Employee = NamedTuple('Employee', [('name', str), ('id', int)])
2062 """
Serhiy Storchakaa2ec0692020-04-08 10:59:04 +03002063 if fields is None:
2064 fields = kwargs.items()
2065 elif kwargs:
2066 raise TypeError("Either list of fields or keywords"
2067 " can be provided to NamedTuple, not both")
2068 try:
2069 module = sys._getframe(1).f_globals.get('__name__', '__main__')
2070 except (AttributeError, ValueError):
2071 module = None
2072 return _make_nmtuple(typename, fields, module=module)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002073
Serhiy Storchakaa2ec0692020-04-08 10:59:04 +03002074_NamedTuple = type.__new__(NamedTupleMeta, 'NamedTuple', (), {})
2075
2076def _namedtuple_mro_entries(bases):
2077 if len(bases) > 1:
2078 raise TypeError("Multiple inheritance with NamedTuple is not supported")
2079 assert bases[0] is NamedTuple
2080 return (_NamedTuple,)
2081
2082NamedTuple.__mro_entries__ = _namedtuple_mro_entries
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002083
2084
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01002085class _TypedDictMeta(type):
2086 def __new__(cls, name, bases, ns, total=True):
2087 """Create new typed dict class object.
2088
Serhiy Storchakaf228bf22020-04-08 11:03:27 +03002089 This method is called when TypedDict is subclassed,
2090 or when TypedDict is instantiated. This way
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01002091 TypedDict supports all three syntax forms described in its docstring.
Serhiy Storchakaf228bf22020-04-08 11:03:27 +03002092 Subclasses and instances of TypedDict return actual dictionaries.
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01002093 """
Serhiy Storchakaf228bf22020-04-08 11:03:27 +03002094 for base in bases:
2095 if type(base) is not _TypedDictMeta:
2096 raise TypeError('cannot inherit from both a TypedDict type '
2097 'and a non-TypedDict base class')
2098 tp_dict = type.__new__(_TypedDictMeta, name, (dict,), ns)
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01002099
Vlad Emelianov10e87e52020-02-13 20:53:29 +01002100 annotations = {}
2101 own_annotations = ns.get('__annotations__', {})
2102 own_annotation_keys = set(own_annotations.keys())
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01002103 msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
Vlad Emelianov10e87e52020-02-13 20:53:29 +01002104 own_annotations = {
2105 n: _type_check(tp, msg) for n, tp in own_annotations.items()
2106 }
2107 required_keys = set()
2108 optional_keys = set()
Zac Hatfield-Dodds665ad3d2019-11-24 21:48:48 +11002109
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01002110 for base in bases:
Vlad Emelianov10e87e52020-02-13 20:53:29 +01002111 annotations.update(base.__dict__.get('__annotations__', {}))
2112 required_keys.update(base.__dict__.get('__required_keys__', ()))
2113 optional_keys.update(base.__dict__.get('__optional_keys__', ()))
Zac Hatfield-Dodds665ad3d2019-11-24 21:48:48 +11002114
Vlad Emelianov10e87e52020-02-13 20:53:29 +01002115 annotations.update(own_annotations)
2116 if total:
2117 required_keys.update(own_annotation_keys)
2118 else:
2119 optional_keys.update(own_annotation_keys)
2120
2121 tp_dict.__annotations__ = annotations
2122 tp_dict.__required_keys__ = frozenset(required_keys)
2123 tp_dict.__optional_keys__ = frozenset(optional_keys)
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01002124 if not hasattr(tp_dict, '__total__'):
2125 tp_dict.__total__ = total
2126 return tp_dict
2127
Serhiy Storchakaf228bf22020-04-08 11:03:27 +03002128 __call__ = dict # static method
2129
2130 def __subclasscheck__(cls, other):
2131 # Typed dicts are only for static structural subtyping.
2132 raise TypeError('TypedDict does not support instance and class checks')
2133
2134 __instancecheck__ = __subclasscheck__
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01002135
2136
Serhiy Storchakaf228bf22020-04-08 11:03:27 +03002137def TypedDict(typename, fields=None, /, *, total=True, **kwargs):
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01002138 """A simple typed namespace. At runtime it is equivalent to a plain dict.
2139
2140 TypedDict creates a dictionary type that expects all of its
2141 instances to have a certain set of keys, where each key is
2142 associated with a value of a consistent type. This expectation
2143 is not checked at runtime but is only enforced by type checkers.
2144 Usage::
2145
2146 class Point2D(TypedDict):
2147 x: int
2148 y: int
2149 label: str
2150
2151 a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
2152 b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
2153
2154 assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
2155
Zac Hatfield-Dodds665ad3d2019-11-24 21:48:48 +11002156 The type info can be accessed via the Point2D.__annotations__ dict, and
2157 the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
2158 TypedDict supports two additional equivalent forms::
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01002159
2160 Point2D = TypedDict('Point2D', x=int, y=int, label=str)
2161 Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
2162
ananthan-123ab6423f2020-02-19 10:03:05 +05302163 By default, all keys must be present in a TypedDict. It is possible
2164 to override this by specifying totality.
2165 Usage::
2166
2167 class point2D(TypedDict, total=False):
2168 x: int
2169 y: int
2170
2171 This means that a point2D TypedDict can have any of the keys omitted.A type
2172 checker is only expected to support a literal False or True as the value of
2173 the total argument. True is the default, and makes all items defined in the
2174 class body be required.
2175
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01002176 The class syntax is only supported in Python 3.6+, while two other
2177 syntax forms work for Python 2.7 and 3.2+
2178 """
Serhiy Storchakaf228bf22020-04-08 11:03:27 +03002179 if fields is None:
2180 fields = kwargs
2181 elif kwargs:
2182 raise TypeError("TypedDict takes either a dict or keyword arguments,"
2183 " but not both")
2184
Alex Grönholm67b769f2020-12-10 23:49:05 +02002185 ns = {'__annotations__': dict(fields)}
Serhiy Storchakaf228bf22020-04-08 11:03:27 +03002186 try:
2187 # Setting correct module is necessary to make typed dict classes pickleable.
2188 ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__')
2189 except (AttributeError, ValueError):
2190 pass
2191
Alex Grönholm67b769f2020-12-10 23:49:05 +02002192 return _TypedDictMeta(typename, (), ns, total=total)
Serhiy Storchakaf228bf22020-04-08 11:03:27 +03002193
2194_TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {})
2195TypedDict.__mro_entries__ = lambda bases: (_TypedDict,)
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01002196
2197
Guido van Rossum91185fe2016-06-08 11:19:11 -07002198def NewType(name, tp):
2199 """NewType creates simple unique types with almost zero
2200 runtime overhead. NewType(name, tp) is considered a subtype of tp
2201 by static type checkers. At runtime, NewType(name, tp) returns
2202 a dummy function that simply returns its argument. Usage::
2203
2204 UserId = NewType('UserId', int)
2205
2206 def name_by_id(user_id: UserId) -> str:
2207 ...
2208
2209 UserId('user') # Fails type check
2210
2211 name_by_id(42) # Fails type check
2212 name_by_id(UserId(42)) # OK
2213
2214 num = UserId(5) + 1 # type: int
2215 """
2216
2217 def new_type(x):
2218 return x
2219
2220 new_type.__name__ = name
2221 new_type.__supertype__ = tp
2222 return new_type
2223
2224
Guido van Rossum0e0563c2016-04-05 14:54:25 -07002225# Python-version-specific alias (Python 2: unicode; Python 3: str)
2226Text = str
2227
2228
Guido van Rossum91185fe2016-06-08 11:19:11 -07002229# Constant that's True when type checking, but False here.
2230TYPE_CHECKING = False
2231
2232
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002233class IO(Generic[AnyStr]):
2234 """Generic base class for TextIO and BinaryIO.
2235
2236 This is an abstract, generic version of the return of open().
2237
2238 NOTE: This does not distinguish between the different possible
2239 classes (text vs. binary, read vs. write vs. read/write,
2240 append-only, unbuffered). The TextIO and BinaryIO subclasses
2241 below capture the distinctions between text vs. binary, which is
2242 pervasive in the interface; however we currently do not offer a
2243 way to track the other distinctions in the type system.
2244 """
2245
Guido van Rossumd70fe632015-08-05 12:11:06 +02002246 __slots__ = ()
2247
HongWeipeng6ce03ec2019-09-27 15:54:26 +08002248 @property
2249 @abstractmethod
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002250 def mode(self) -> str:
2251 pass
2252
HongWeipeng6ce03ec2019-09-27 15:54:26 +08002253 @property
2254 @abstractmethod
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002255 def name(self) -> str:
2256 pass
2257
2258 @abstractmethod
2259 def close(self) -> None:
2260 pass
2261
Shantanu2e6569b2020-01-29 18:52:36 -08002262 @property
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002263 @abstractmethod
2264 def closed(self) -> bool:
2265 pass
2266
2267 @abstractmethod
2268 def fileno(self) -> int:
2269 pass
2270
2271 @abstractmethod
2272 def flush(self) -> None:
2273 pass
2274
2275 @abstractmethod
2276 def isatty(self) -> bool:
2277 pass
2278
2279 @abstractmethod
2280 def read(self, n: int = -1) -> AnyStr:
2281 pass
2282
2283 @abstractmethod
2284 def readable(self) -> bool:
2285 pass
2286
2287 @abstractmethod
2288 def readline(self, limit: int = -1) -> AnyStr:
2289 pass
2290
2291 @abstractmethod
2292 def readlines(self, hint: int = -1) -> List[AnyStr]:
2293 pass
2294
2295 @abstractmethod
2296 def seek(self, offset: int, whence: int = 0) -> int:
2297 pass
2298
2299 @abstractmethod
2300 def seekable(self) -> bool:
2301 pass
2302
2303 @abstractmethod
2304 def tell(self) -> int:
2305 pass
2306
2307 @abstractmethod
2308 def truncate(self, size: int = None) -> int:
2309 pass
2310
2311 @abstractmethod
2312 def writable(self) -> bool:
2313 pass
2314
2315 @abstractmethod
2316 def write(self, s: AnyStr) -> int:
2317 pass
2318
2319 @abstractmethod
2320 def writelines(self, lines: List[AnyStr]) -> None:
2321 pass
2322
2323 @abstractmethod
2324 def __enter__(self) -> 'IO[AnyStr]':
2325 pass
2326
2327 @abstractmethod
2328 def __exit__(self, type, value, traceback) -> None:
2329 pass
2330
2331
2332class BinaryIO(IO[bytes]):
2333 """Typed version of the return of open() in binary mode."""
2334
Guido van Rossumd70fe632015-08-05 12:11:06 +02002335 __slots__ = ()
2336
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002337 @abstractmethod
2338 def write(self, s: Union[bytes, bytearray]) -> int:
2339 pass
2340
2341 @abstractmethod
2342 def __enter__(self) -> 'BinaryIO':
2343 pass
2344
2345
2346class TextIO(IO[str]):
2347 """Typed version of the return of open() in text mode."""
2348
Guido van Rossumd70fe632015-08-05 12:11:06 +02002349 __slots__ = ()
2350
HongWeipeng6ce03ec2019-09-27 15:54:26 +08002351 @property
2352 @abstractmethod
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002353 def buffer(self) -> BinaryIO:
2354 pass
2355
HongWeipeng6ce03ec2019-09-27 15:54:26 +08002356 @property
2357 @abstractmethod
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002358 def encoding(self) -> str:
2359 pass
2360
HongWeipeng6ce03ec2019-09-27 15:54:26 +08002361 @property
2362 @abstractmethod
Guido van Rossum991d14f2016-11-09 13:12:51 -08002363 def errors(self) -> Optional[str]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002364 pass
2365
HongWeipeng6ce03ec2019-09-27 15:54:26 +08002366 @property
2367 @abstractmethod
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002368 def line_buffering(self) -> bool:
2369 pass
2370
HongWeipeng6ce03ec2019-09-27 15:54:26 +08002371 @property
2372 @abstractmethod
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002373 def newlines(self) -> Any:
2374 pass
2375
2376 @abstractmethod
2377 def __enter__(self) -> 'TextIO':
2378 pass
2379
2380
2381class io:
2382 """Wrapper namespace for IO generic classes."""
2383
2384 __all__ = ['IO', 'TextIO', 'BinaryIO']
2385 IO = IO
2386 TextIO = TextIO
2387 BinaryIO = BinaryIO
2388
Guido van Rossumd7adfe12017-01-22 17:43:53 -08002389
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002390io.__name__ = __name__ + '.io'
2391sys.modules[io.__name__] = io
2392
Serhiy Storchakafcb28562020-05-10 11:53:16 +03002393Pattern = _alias(stdlib_re.Pattern, 1)
2394Match = _alias(stdlib_re.Match, 1)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002395
2396class re:
2397 """Wrapper namespace for re type aliases."""
2398
2399 __all__ = ['Pattern', 'Match']
2400 Pattern = Pattern
2401 Match = Match
2402
Guido van Rossumd7adfe12017-01-22 17:43:53 -08002403
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002404re.__name__ = __name__ + '.re'
2405sys.modules[re.__name__] = re