Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1 | """ |
| 2 | The typing module: Support for gradual typing as defined by PEP 484. |
| 3 | |
| 4 | At large scale, the structure of the module is following: |
Tim McNamara | 5265b3a | 2018-09-01 20:56:58 +1200 | [diff] [blame] | 5 | * Imports and exports, all public names should be explicitly added to __all__. |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 6 | * Internal helper functions: these should never be used in code outside this module. |
kj | 73607be | 2020-12-24 12:33:48 +0800 | [diff] [blame] | 7 | * _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 Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 11 | * 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 Levkivskyi | 74d7f76 | 2019-05-28 08:40:15 +0100 | [diff] [blame] | 14 | * The public counterpart of the generics API consists of two classes: Generic and Protocol. |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 15 | * 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-123 | ab6423f | 2020-02-19 10:03:05 +0530 | [diff] [blame] | 18 | * Special types: NewType, NamedTuple, TypedDict. |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 19 | * Wrapper submodules for re and io related types. |
| 20 | """ |
| 21 | |
HongWeipeng | 6ce03ec | 2019-09-27 15:54:26 +0800 | [diff] [blame] | 22 | from abc import abstractmethod, ABCMeta |
Batuhan Taskaya | 044a104 | 2020-10-06 23:03:02 +0300 | [diff] [blame] | 23 | import ast |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 24 | import collections |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 25 | import collections.abc |
Brett Cannon | f3ad042 | 2016-04-15 10:51:30 -0700 | [diff] [blame] | 26 | import contextlib |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 27 | import functools |
Serhiy Storchaka | 09f3221 | 2018-05-26 21:19:26 +0300 | [diff] [blame] | 28 | import operator |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 29 | import re as stdlib_re # Avoid confusion with the re we export. |
| 30 | import sys |
| 31 | import types |
Guido van Rossum | 48b069a | 2020-04-07 09:50:06 -0700 | [diff] [blame] | 32 | from types import WrapperDescriptorType, MethodWrapperType, MethodDescriptorType, GenericAlias |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 33 | |
| 34 | # Please keep __all__ alphabetized within each category. |
| 35 | __all__ = [ |
| 36 | # Super-special typing primitives. |
Jakub Stasiak | cf5b109 | 2020-02-05 02:10:19 +0100 | [diff] [blame] | 37 | 'Annotated', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 38 | 'Any', |
| 39 | 'Callable', |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 40 | 'ClassVar', |
kj | 73607be | 2020-12-24 12:33:48 +0800 | [diff] [blame] | 41 | 'Concatenate', |
Ivan Levkivskyi | f367242 | 2019-05-26 09:37:07 +0100 | [diff] [blame] | 42 | 'Final', |
Anthony Sottile | d30da5d | 2019-05-29 11:19:38 -0700 | [diff] [blame] | 43 | 'ForwardRef', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 44 | 'Generic', |
Ivan Levkivskyi | b891c46 | 2019-05-26 09:37:48 +0100 | [diff] [blame] | 45 | 'Literal', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 46 | 'Optional', |
kj | 73607be | 2020-12-24 12:33:48 +0800 | [diff] [blame] | 47 | 'ParamSpec', |
Ivan Levkivskyi | 74d7f76 | 2019-05-28 08:40:15 +0100 | [diff] [blame] | 48 | 'Protocol', |
Guido van Rossum | eb9aca3 | 2016-05-24 16:38:22 -0700 | [diff] [blame] | 49 | 'Tuple', |
| 50 | 'Type', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 51 | 'TypeVar', |
| 52 | 'Union', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 53 | |
| 54 | # ABCs (from collections.abc). |
| 55 | 'AbstractSet', # collections.abc.Set. |
| 56 | 'ByteString', |
| 57 | 'Container', |
Ivan Levkivskyi | 29fda8d | 2017-06-10 21:57:56 +0200 | [diff] [blame] | 58 | 'ContextManager', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 59 | '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 Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 72 | 'Awaitable', |
| 73 | 'AsyncIterator', |
| 74 | 'AsyncIterable', |
| 75 | 'Coroutine', |
| 76 | 'Collection', |
| 77 | 'AsyncGenerator', |
| 78 | 'AsyncContextManager', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 79 | |
| 80 | # Structural checks, a.k.a. protocols. |
| 81 | 'Reversible', |
| 82 | 'SupportsAbs', |
Ivan Levkivskyi | f06e021 | 2017-05-02 19:14:07 +0200 | [diff] [blame] | 83 | 'SupportsBytes', |
| 84 | 'SupportsComplex', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 85 | 'SupportsFloat', |
Paul Dagnelie | 4c7a46e | 2019-05-22 07:23:01 -0700 | [diff] [blame] | 86 | 'SupportsIndex', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 87 | 'SupportsInt', |
| 88 | 'SupportsRound', |
| 89 | |
| 90 | # Concrete collection types. |
Anthony Sottile | d30da5d | 2019-05-29 11:19:38 -0700 | [diff] [blame] | 91 | 'ChainMap', |
Ivan Levkivskyi | b692dc8 | 2017-02-13 22:50:14 +0100 | [diff] [blame] | 92 | 'Counter', |
Raymond Hettinger | 8049052 | 2017-01-16 22:42:37 -0800 | [diff] [blame] | 93 | 'Deque', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 94 | 'Dict', |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 95 | 'DefaultDict', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 96 | 'List', |
Anthony Sottile | d30da5d | 2019-05-29 11:19:38 -0700 | [diff] [blame] | 97 | 'OrderedDict', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 98 | 'Set', |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 99 | 'FrozenSet', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 100 | 'NamedTuple', # Not really a type. |
Ivan Levkivskyi | 135c6a5 | 2019-05-26 09:39:24 +0100 | [diff] [blame] | 101 | 'TypedDict', # Not really a type. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 102 | 'Generator', |
| 103 | |
| 104 | # One-off things. |
| 105 | 'AnyStr', |
| 106 | 'cast', |
Ivan Levkivskyi | f367242 | 2019-05-26 09:37:07 +0100 | [diff] [blame] | 107 | 'final', |
Ivan Levkivskyi | 4c23aff | 2019-05-31 00:10:07 +0100 | [diff] [blame] | 108 | 'get_args', |
| 109 | 'get_origin', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 110 | 'get_type_hints', |
Patrick Reader | 0705ec8 | 2020-09-16 05:58:32 +0100 | [diff] [blame] | 111 | 'is_typeddict', |
Guido van Rossum | 91185fe | 2016-06-08 11:19:11 -0700 | [diff] [blame] | 112 | 'NewType', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 113 | 'no_type_check', |
| 114 | 'no_type_check_decorator', |
aetracht | 4573820 | 2018-03-19 14:41:32 -0400 | [diff] [blame] | 115 | 'NoReturn', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 116 | 'overload', |
Ivan Levkivskyi | 74d7f76 | 2019-05-28 08:40:15 +0100 | [diff] [blame] | 117 | 'runtime_checkable', |
Guido van Rossum | 0e0563c | 2016-04-05 14:54:25 -0700 | [diff] [blame] | 118 | 'Text', |
Guido van Rossum | 91185fe | 2016-06-08 11:19:11 -0700 | [diff] [blame] | 119 | 'TYPE_CHECKING', |
Mikhail Golubev | 4f3c250 | 2020-10-08 00:44:31 +0300 | [diff] [blame] | 120 | 'TypeAlias', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 121 | ] |
| 122 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 123 | # The pseudo-submodules 're' and 'io' are part of the public |
| 124 | # namespace, but excluded from __all__ because they might stomp on |
| 125 | # legitimate imports of those modules. |
| 126 | |
kj | 463c7d3 | 2020-12-14 02:38:24 +0800 | [diff] [blame] | 127 | |
| 128 | def _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 Zakharenko | 0e61dff | 2018-05-22 20:32:10 -0700 | [diff] [blame] | 137 | def _type_check(arg, msg, is_argument=True): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 138 | """Check that the argument is a type, and return it (internal helper). |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 139 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 140 | 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 144 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 145 | "Union[arg, ...]: arg should be a type." |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 146 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 147 | We append the repr() of the actual value (truncated to 100 chars). |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 148 | """ |
Ivan Levkivskyi | 74d7f76 | 2019-05-28 08:40:15 +0100 | [diff] [blame] | 149 | invalid_generic_forms = (Generic, Protocol) |
Nina Zakharenko | 0e61dff | 2018-05-22 20:32:10 -0700 | [diff] [blame] | 150 | if is_argument: |
Ivan Levkivskyi | f367242 | 2019-05-26 09:37:07 +0100 | [diff] [blame] | 151 | invalid_generic_forms = invalid_generic_forms + (ClassVar, Final) |
Nina Zakharenko | 2d2d3b1 | 2018-05-16 12:27:03 -0400 | [diff] [blame] | 152 | |
kj | 463c7d3 | 2020-12-14 02:38:24 +0800 | [diff] [blame] | 153 | arg = _type_convert(arg) |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 154 | if (isinstance(arg, _GenericAlias) and |
Nina Zakharenko | 2d2d3b1 | 2018-05-16 12:27:03 -0400 | [diff] [blame] | 155 | arg.__origin__ in invalid_generic_forms): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 156 | raise TypeError(f"{arg} is not valid as type argument") |
Serhiy Storchaka | 40ded94 | 2020-04-23 21:26:48 +0300 | [diff] [blame] | 157 | if arg in (Any, NoReturn): |
| 158 | return arg |
| 159 | if isinstance(arg, _SpecialForm) or arg in (Generic, Protocol): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 160 | raise TypeError(f"Plain {arg} is not valid as type argument") |
kj | 73607be | 2020-12-24 12:33:48 +0800 | [diff] [blame] | 161 | if isinstance(arg, (type, TypeVar, ForwardRef, types.Union, ParamSpec)): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 162 | return arg |
| 163 | if not callable(arg): |
| 164 | raise TypeError(f"{msg} Got {arg!r:.100}.") |
| 165 | return arg |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 166 | |
| 167 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 168 | def _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 | """ |
kj | 1f7dfb2 | 2020-11-02 02:13:38 +0800 | [diff] [blame] | 176 | if isinstance(obj, types.GenericAlias): |
| 177 | return repr(obj) |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 178 | 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 | |
| 189 | def _collect_type_vars(types): |
kj | 73607be | 2020-12-24 12:33:48 +0800 | [diff] [blame] | 190 | """Collect all type variable-like variables contained |
| 191 | in types in order of first appearance (lexicographic order). For example:: |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 192 | |
| 193 | _collect_type_vars((T, List[S, T])) == (T, S) |
| 194 | """ |
| 195 | tvars = [] |
| 196 | for t in types: |
kj | 73607be | 2020-12-24 12:33:48 +0800 | [diff] [blame] | 197 | if isinstance(t, _TypeVarLike) and t not in tvars: |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 198 | tvars.append(t) |
Serhiy Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 199 | if isinstance(t, (_GenericAlias, GenericAlias)): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 200 | tvars.extend([t for t in t.__parameters__ if t not in tvars]) |
| 201 | return tuple(tvars) |
| 202 | |
| 203 | |
Serhiy Storchaka | fcb2856 | 2020-05-10 11:53:16 +0300 | [diff] [blame] | 204 | def _check_generic(cls, parameters, elen): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 205 | """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 Storchaka | fcb2856 | 2020-05-10 11:53:16 +0300 | [diff] [blame] | 208 | if not elen: |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 209 | raise TypeError(f"{cls} is not a generic class") |
| 210 | alen = len(parameters) |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 211 | if alen != elen: |
| 212 | raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};" |
| 213 | f" actual {alen}, expected {elen}") |
| 214 | |
kj | 73607be | 2020-12-24 12:33:48 +0800 | [diff] [blame] | 215 | def _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 Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 230 | |
Yurii Karabas | f03d318 | 2020-11-17 04:23:19 +0200 | [diff] [blame] | 231 | def _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 Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 245 | def _remove_dups_flatten(parameters): |
Ivan Levkivskyi | f65e31f | 2018-05-18 16:00:38 -0700 | [diff] [blame] | 246 | """An internal helper for Union creation and substitution: flatten Unions |
| 247 | among parameters, then remove duplicates. |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 248 | """ |
| 249 | # Flatten out Union[Union[...], ...]. |
| 250 | params = [] |
| 251 | for p in parameters: |
Maggie Moss | 1b4552c | 2020-09-09 13:23:24 -0700 | [diff] [blame] | 252 | if isinstance(p, (_UnionGenericAlias, types.Union)): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 253 | 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 Karabas | f03d318 | 2020-11-17 04:23:19 +0200 | [diff] [blame] | 258 | |
| 259 | return tuple(_deduplicate(params)) |
| 260 | |
| 261 | |
| 262 | def _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 Levkivskyi | f65e31f | 2018-05-18 16:00:38 -0700 | [diff] [blame] | 270 | return tuple(params) |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 271 | |
| 272 | |
| 273 | _cleanups = [] |
| 274 | |
| 275 | |
Yurii Karabas | f03d318 | 2020-11-17 04:23:19 +0200 | [diff] [blame] | 276 | def _tp_cache(func=None, /, *, typed=False): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 277 | """Internal wrapper caching __getitem__ of generic types with a fallback to |
| 278 | original function for non-hashable arguments. |
| 279 | """ |
Yurii Karabas | f03d318 | 2020-11-17 04:23:19 +0200 | [diff] [blame] | 280 | def decorator(func): |
| 281 | cached = functools.lru_cache(typed=typed)(func) |
| 282 | _cleanups.append(cached.cache_clear) |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 283 | |
Yurii Karabas | f03d318 | 2020-11-17 04:23:19 +0200 | [diff] [blame] | 284 | @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 Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 292 | |
Yurii Karabas | f03d318 | 2020-11-17 04:23:19 +0200 | [diff] [blame] | 293 | if func is not None: |
| 294 | return decorator(func) |
| 295 | |
| 296 | return decorator |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 297 | |
wyfo | 653f420 | 2020-07-22 21:47:28 +0200 | [diff] [blame] | 298 | def _eval_type(t, globalns, localns, recursive_guard=frozenset()): |
Graham Bleaney | 84ef33c | 2020-09-08 18:41:10 -0400 | [diff] [blame] | 299 | """Evaluate all forward references in the given type t. |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 300 | For use of globalns and localns see the docstring for get_type_hints(). |
wyfo | 653f420 | 2020-07-22 21:47:28 +0200 | [diff] [blame] | 301 | recursive_guard is used to prevent prevent infinite recursion |
| 302 | with recursive ForwardRef. |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 303 | """ |
| 304 | if isinstance(t, ForwardRef): |
wyfo | 653f420 | 2020-07-22 21:47:28 +0200 | [diff] [blame] | 305 | return t._evaluate(globalns, localns, recursive_guard) |
Serhiy Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 306 | if isinstance(t, (_GenericAlias, GenericAlias)): |
wyfo | 653f420 | 2020-07-22 21:47:28 +0200 | [diff] [blame] | 307 | ev_args = tuple(_eval_type(a, globalns, localns, recursive_guard) for a in t.__args__) |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 308 | if ev_args == t.__args__: |
| 309 | return t |
Serhiy Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 310 | if isinstance(t, GenericAlias): |
| 311 | return GenericAlias(t.__origin__, ev_args) |
| 312 | else: |
| 313 | return t.copy_with(ev_args) |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 314 | return t |
| 315 | |
| 316 | |
| 317 | class _Final: |
| 318 | """Mixin to prohibit subclassing""" |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 319 | |
Guido van Rossum | 83ec302 | 2017-01-17 20:43:28 -0800 | [diff] [blame] | 320 | __slots__ = ('__weakref__',) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 321 | |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 322 | def __init_subclass__(self, /, *args, **kwds): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 323 | if '_root' not in kwds: |
| 324 | raise TypeError("Cannot subclass special typing classes") |
| 325 | |
Ivan Levkivskyi | 8349403 | 2018-03-26 23:01:12 +0100 | [diff] [blame] | 326 | class _Immutable: |
| 327 | """Mixin to indicate that object should not be copied.""" |
Serhiy Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 328 | __slots__ = () |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 329 | |
Ivan Levkivskyi | 8349403 | 2018-03-26 23:01:12 +0100 | [diff] [blame] | 330 | def __copy__(self): |
| 331 | return self |
| 332 | |
| 333 | def __deepcopy__(self, memo): |
| 334 | return self |
| 335 | |
| 336 | |
Serhiy Storchaka | 40ded94 | 2020-04-23 21:26:48 +0300 | [diff] [blame] | 337 | # Internal indicator of special typing constructs. |
| 338 | # See __doc__ instance attribute for specific docs. |
| 339 | class _SpecialForm(_Final, _root=True): |
| 340 | __slots__ = ('_name', '__doc__', '_getitem') |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 341 | |
Serhiy Storchaka | 40ded94 | 2020-04-23 21:26:48 +0300 | [diff] [blame] | 342 | def __init__(self, getitem): |
| 343 | self._getitem = getitem |
| 344 | self._name = getitem.__name__ |
| 345 | self.__doc__ = getitem.__doc__ |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 346 | |
Serhiy Storchaka | 40ded94 | 2020-04-23 21:26:48 +0300 | [diff] [blame] | 347 | def __mro_entries__(self, bases): |
| 348 | raise TypeError(f"Cannot subclass {self!r}") |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 349 | |
| 350 | def __repr__(self): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 351 | return 'typing.' + self._name |
| 352 | |
Ivan Levkivskyi | 8349403 | 2018-03-26 23:01:12 +0100 | [diff] [blame] | 353 | def __reduce__(self): |
| 354 | return self._name |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 355 | |
| 356 | def __call__(self, *args, **kwds): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 357 | 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 Storchaka | 40ded94 | 2020-04-23 21:26:48 +0300 | [diff] [blame] | 367 | return self._getitem(self, parameters) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 368 | |
Yurii Karabas | f03d318 | 2020-11-17 04:23:19 +0200 | [diff] [blame] | 369 | |
| 370 | class _LiteralSpecialForm(_SpecialForm, _root=True): |
| 371 | @_tp_cache(typed=True) |
| 372 | def __getitem__(self, parameters): |
| 373 | return self._getitem(self, parameters) |
| 374 | |
| 375 | |
Serhiy Storchaka | 40ded94 | 2020-04-23 21:26:48 +0300 | [diff] [blame] | 376 | @_SpecialForm |
| 377 | def Any(self, parameters): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 378 | """Special type indicating an unconstrained type. |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 379 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 380 | - Any is compatible with every type. |
| 381 | - Any assumed to have all methods. |
| 382 | - All values assumed to be instances of Any. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 383 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 384 | 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 Storchaka | 40ded94 | 2020-04-23 21:26:48 +0300 | [diff] [blame] | 387 | """ |
| 388 | raise TypeError(f"{self} is not subscriptable") |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 389 | |
Serhiy Storchaka | 40ded94 | 2020-04-23 21:26:48 +0300 | [diff] [blame] | 390 | @_SpecialForm |
| 391 | def NoReturn(self, parameters): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 392 | """Special type indicating functions that never return. |
| 393 | Example:: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 394 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 395 | 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 Storchaka | 40ded94 | 2020-04-23 21:26:48 +0300 | [diff] [blame] | 402 | """ |
| 403 | raise TypeError(f"{self} is not subscriptable") |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 404 | |
Serhiy Storchaka | 40ded94 | 2020-04-23 21:26:48 +0300 | [diff] [blame] | 405 | @_SpecialForm |
| 406 | def ClassVar(self, parameters): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 407 | """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 Storchaka | 40ded94 | 2020-04-23 21:26:48 +0300 | [diff] [blame] | 421 | """ |
| 422 | item = _type_check(parameters, f'{self} accepts only single type.') |
| 423 | return _GenericAlias(self, (item,)) |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 424 | |
Serhiy Storchaka | 40ded94 | 2020-04-23 21:26:48 +0300 | [diff] [blame] | 425 | @_SpecialForm |
| 426 | def Final(self, parameters): |
Ivan Levkivskyi | f367242 | 2019-05-26 09:37:07 +0100 | [diff] [blame] | 427 | """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 Storchaka | 40ded94 | 2020-04-23 21:26:48 +0300 | [diff] [blame] | 442 | """ |
| 443 | item = _type_check(parameters, f'{self} accepts only single type.') |
| 444 | return _GenericAlias(self, (item,)) |
Ivan Levkivskyi | f367242 | 2019-05-26 09:37:07 +0100 | [diff] [blame] | 445 | |
Serhiy Storchaka | 40ded94 | 2020-04-23 21:26:48 +0300 | [diff] [blame] | 446 | @_SpecialForm |
| 447 | def Union(self, parameters): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 448 | """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 Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 470 | - You cannot subclass or instantiate a union. |
| 471 | - You can use Optional[X] as a shorthand for Union[X, None]. |
Serhiy Storchaka | 40ded94 | 2020-04-23 21:26:48 +0300 | [diff] [blame] | 472 | """ |
| 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 Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 482 | return _UnionGenericAlias(self, parameters) |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 483 | |
Serhiy Storchaka | 40ded94 | 2020-04-23 21:26:48 +0300 | [diff] [blame] | 484 | @_SpecialForm |
| 485 | def Optional(self, parameters): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 486 | """Optional type. |
| 487 | |
| 488 | Optional[X] is equivalent to Union[X, None]. |
Serhiy Storchaka | 40ded94 | 2020-04-23 21:26:48 +0300 | [diff] [blame] | 489 | """ |
| 490 | arg = _type_check(parameters, f"{self} requires a single type.") |
| 491 | return Union[arg, type(None)] |
Guido van Rossum | b7dedc8 | 2016-10-29 12:44:29 -0700 | [diff] [blame] | 492 | |
Yurii Karabas | f03d318 | 2020-11-17 04:23:19 +0200 | [diff] [blame] | 493 | @_LiteralSpecialForm |
Serhiy Storchaka | 40ded94 | 2020-04-23 21:26:48 +0300 | [diff] [blame] | 494 | def Literal(self, parameters): |
Ivan Levkivskyi | b891c46 | 2019-05-26 09:37:48 +0100 | [diff] [blame] | 495 | """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 Storchaka | 40ded94 | 2020-04-23 21:26:48 +0300 | [diff] [blame] | 511 | 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 Karabas | f03d318 | 2020-11-17 04:23:19 +0200 | [diff] [blame] | 517 | 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 Levkivskyi | b891c46 | 2019-05-26 09:37:48 +0100 | [diff] [blame] | 528 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 529 | |
Mikhail Golubev | 4f3c250 | 2020-10-08 00:44:31 +0300 | [diff] [blame] | 530 | @_SpecialForm |
| 531 | def 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 | |
kj | 73607be | 2020-12-24 12:33:48 +0800 | [diff] [blame] | 545 | @_SpecialForm |
| 546 | def 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 Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 568 | class ForwardRef(_Final, _root=True): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 569 | """Internal wrapper to hold a forward reference.""" |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 570 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 571 | __slots__ = ('__forward_arg__', '__forward_code__', |
Nina Zakharenko | 2d2d3b1 | 2018-05-16 12:27:03 -0400 | [diff] [blame] | 572 | '__forward_evaluated__', '__forward_value__', |
| 573 | '__forward_is_argument__') |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 574 | |
Nina Zakharenko | 0e61dff | 2018-05-22 20:32:10 -0700 | [diff] [blame] | 575 | def __init__(self, arg, is_argument=True): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 576 | if not isinstance(arg, str): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 577 | raise TypeError(f"Forward reference must be a string -- got {arg!r}") |
Batuhan Taskaya | 044a104 | 2020-10-06 23:03:02 +0300 | [diff] [blame] | 578 | |
| 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 585 | try: |
| 586 | code = compile(arg, '<string>', 'eval') |
| 587 | except SyntaxError: |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 588 | raise SyntaxError(f"Forward reference must be an expression -- got {arg!r}") |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 589 | self.__forward_arg__ = arg |
| 590 | self.__forward_code__ = code |
| 591 | self.__forward_evaluated__ = False |
| 592 | self.__forward_value__ = None |
Nina Zakharenko | 2d2d3b1 | 2018-05-16 12:27:03 -0400 | [diff] [blame] | 593 | self.__forward_is_argument__ = is_argument |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 594 | |
wyfo | 653f420 | 2020-07-22 21:47:28 +0200 | [diff] [blame] | 595 | def _evaluate(self, globalns, localns, recursive_guard): |
| 596 | if self.__forward_arg__ in recursive_guard: |
| 597 | return self |
Guido van Rossum | dad1790 | 2016-11-10 08:29:18 -0800 | [diff] [blame] | 598 | if not self.__forward_evaluated__ or localns is not globalns: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 599 | 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 |
wyfo | 653f420 | 2020-07-22 21:47:28 +0200 | [diff] [blame] | 605 | type_ =_type_check( |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 606 | eval(self.__forward_code__, globalns, localns), |
Nina Zakharenko | 2d2d3b1 | 2018-05-16 12:27:03 -0400 | [diff] [blame] | 607 | "Forward references must evaluate to types.", |
wyfo | 653f420 | 2020-07-22 21:47:28 +0200 | [diff] [blame] | 608 | 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 613 | self.__forward_evaluated__ = True |
| 614 | return self.__forward_value__ |
| 615 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 616 | def __eq__(self, other): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 617 | if not isinstance(other, ForwardRef): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 618 | return NotImplemented |
plokmijnuhby | e082e7c | 2019-09-13 20:40:54 +0100 | [diff] [blame] | 619 | 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 Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 623 | |
| 624 | def __hash__(self): |
plokmijnuhby | e082e7c | 2019-09-13 20:40:54 +0100 | [diff] [blame] | 625 | return hash(self.__forward_arg__) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 626 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 627 | def __repr__(self): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 628 | return f'ForwardRef({self.__forward_arg__!r})' |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 629 | |
kj | 73607be | 2020-12-24 12:33:48 +0800 | [diff] [blame] | 630 | class _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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 644 | |
kj | 73607be | 2020-12-24 12:33:48 +0800 | [diff] [blame] | 645 | 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 | |
| 664 | class TypeVar( _Final, _Immutable, _TypeVarLike, _root=True): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 665 | """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 Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 677 | def repeat(x: T, n: int) -> List[T]: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 678 | '''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 Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 690 | At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 691 | |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 692 | Type variables defined with covariant=True or contravariant=True |
João D. Ferreira | 86bfed3 | 2018-07-07 16:41:20 +0100 | [diff] [blame] | 693 | can be used to declare covariant or contravariant generic types. |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 694 | See PEP 484 for more details. By default generic types are invariant |
| 695 | in all type variables. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 696 | |
| 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 Levkivskyi | 8349403 | 2018-03-26 23:01:12 +0100 | [diff] [blame] | 704 | |
| 705 | Note that only type variables defined in global scope can be pickled. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 706 | """ |
| 707 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 708 | __slots__ = ('__name__', '__bound__', '__constraints__', |
Serhiy Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 709 | '__covariant__', '__contravariant__', '__dict__') |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 710 | |
| 711 | def __init__(self, name, *constraints, bound=None, |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 712 | covariant=False, contravariant=False): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 713 | self.__name__ = name |
kj | 73607be | 2020-12-24 12:33:48 +0800 | [diff] [blame] | 714 | super().__init__(bound, covariant, contravariant) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 715 | 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) |
HongWeipeng | a25a04f | 2020-04-21 04:01:53 +0800 | [diff] [blame] | 721 | try: |
| 722 | def_mod = sys._getframe(1).f_globals.get('__name__', '__main__') # for pickling |
| 723 | except (AttributeError, ValueError): |
| 724 | def_mod = None |
Serhiy Storchaka | 09f3221 | 2018-05-26 21:19:26 +0300 | [diff] [blame] | 725 | if def_mod != 'typing': |
| 726 | self.__module__ = def_mod |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 727 | |
Maggie Moss | 1b4552c | 2020-09-09 13:23:24 -0700 | [diff] [blame] | 728 | |
kj | 73607be | 2020-12-24 12:33:48 +0800 | [diff] [blame] | 729 | class ParamSpec(_Final, _Immutable, _TypeVarLike, _root=True): |
| 730 | """Parameter specification variable. |
Maggie Moss | 1b4552c | 2020-09-09 13:23:24 -0700 | [diff] [blame] | 731 | |
kj | 73607be | 2020-12-24 12:33:48 +0800 | [diff] [blame] | 732 | Usage:: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 733 | |
kj | 73607be | 2020-12-24 12:33:48 +0800 | [diff] [blame] | 734 | 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 Levkivskyi | 8349403 | 2018-03-26 23:01:12 +0100 | [diff] [blame] | 790 | |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 791 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 792 | def _is_dunder(attr): |
| 793 | return attr.startswith('__') and attr.endswith('__') |
Guido van Rossum | 83ec302 | 2017-01-17 20:43:28 -0800 | [diff] [blame] | 794 | |
Serhiy Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 795 | class _BaseGenericAlias(_Final, _root=True): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 796 | """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 Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 803 | """ |
Serhiy Storchaka | fcb2856 | 2020-05-10 11:53:16 +0300 | [diff] [blame] | 804 | def __init__(self, origin, *, inst=True, name=None): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 805 | self._inst = inst |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 806 | self._name = name |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 807 | self.__origin__ = origin |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 808 | self.__slots__ = None # This is not documented. |
Serhiy Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 809 | |
| 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 Storchaka | fcb2856 | 2020-05-10 11:53:16 +0300 | [diff] [blame] | 841 | if _is_dunder(attr) or attr in ('_name', '_inst', '_nparams'): |
Serhiy Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 842 | 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 Storchaka | fcb2856 | 2020-05-10 11:53:16 +0300 | [diff] [blame] | 854 | # 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 Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 865 | class _GenericAlias(_BaseGenericAlias, _root=True): |
Serhiy Storchaka | fcb2856 | 2020-05-10 11:53:16 +0300 | [diff] [blame] | 866 | 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 Moss | 1b4552c | 2020-09-09 13:23:24 -0700 | [diff] [blame] | 886 | def __or__(self, right): |
| 887 | return Union[self, right] |
| 888 | |
| 889 | def __ror__(self, right): |
| 890 | return Union[self, right] |
| 891 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 892 | @_tp_cache |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 893 | def __getitem__(self, params): |
Ivan Levkivskyi | 74d7f76 | 2019-05-28 08:40:15 +0100 | [diff] [blame] | 894 | if self.__origin__ in (Generic, Protocol): |
| 895 | # Can't subscript Generic[...] or Protocol[...]. |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 896 | raise TypeError(f"Cannot subscript already-subscripted {self}") |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 897 | if not isinstance(params, tuple): |
| 898 | params = (params,) |
kj | 73607be | 2020-12-24 12:33:48 +0800 | [diff] [blame] | 899 | 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 Storchaka | fcb2856 | 2020-05-10 11:53:16 +0300 | [diff] [blame] | 902 | _check_generic(self, params, len(self.__parameters__)) |
Serhiy Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 903 | |
| 904 | subst = dict(zip(self.__parameters__, params)) |
| 905 | new_args = [] |
| 906 | for arg in self.__args__: |
kj | 73607be | 2020-12-24 12:33:48 +0800 | [diff] [blame] | 907 | if isinstance(arg, _TypeVarLike): |
Serhiy Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 908 | arg = subst[arg] |
Serhiy Storchaka | fcb2856 | 2020-05-10 11:53:16 +0300 | [diff] [blame] | 909 | elif isinstance(arg, (_GenericAlias, GenericAlias)): |
Serhiy Storchaka | 0122d48 | 2020-05-10 13:39:40 +0300 | [diff] [blame] | 910 | subparams = arg.__parameters__ |
| 911 | if subparams: |
| 912 | subargs = tuple(subst[x] for x in subparams) |
| 913 | arg = arg[subargs] |
kj | 73607be | 2020-12-24 12:33:48 +0800 | [diff] [blame] | 914 | # 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 Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 919 | return self.copy_with(tuple(new_args)) |
Ivan Levkivskyi | b692dc8 | 2017-02-13 22:50:14 +0100 | [diff] [blame] | 920 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 921 | def copy_with(self, params): |
Serhiy Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 922 | return self.__class__(self.__origin__, params, name=self._name, inst=self._inst) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 923 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 924 | def __repr__(self): |
Serhiy Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 925 | 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 Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 931 | |
Serhiy Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 932 | 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 Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 941 | |
| 942 | def __mro_entries__(self, bases): |
| 943 | if self._name: # generic version of an ABC or built-in class |
Serhiy Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 944 | return super().__mro_entries__(bases) |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 945 | if self.__origin__ is Generic: |
Ivan Levkivskyi | 74d7f76 | 2019-05-28 08:40:15 +0100 | [diff] [blame] | 946 | if Protocol in bases: |
| 947 | return () |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 948 | i = bases.index(self) |
| 949 | for b in bases[i+1:]: |
Serhiy Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 950 | if isinstance(b, _BaseGenericAlias) and b is not self: |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 951 | return () |
| 952 | return (self.__origin__,) |
| 953 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 954 | |
Serhiy Storchaka | fcb2856 | 2020-05-10 11:53:16 +0300 | [diff] [blame] | 955 | # _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 Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 959 | class _SpecialGenericAlias(_BaseGenericAlias, _root=True): |
Serhiy Storchaka | fcb2856 | 2020-05-10 11:53:16 +0300 | [diff] [blame] | 960 | def __init__(self, origin, nparams, *, inst=True, name=None): |
Serhiy Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 961 | if name is None: |
| 962 | name = origin.__name__ |
Serhiy Storchaka | fcb2856 | 2020-05-10 11:53:16 +0300 | [diff] [blame] | 963 | super().__init__(origin, inst=inst, name=name) |
| 964 | self._nparams = nparams |
Serhiy Storchaka | 2fbc57a | 2020-05-10 15:14:27 +0300 | [diff] [blame] | 965 | 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 Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 969 | |
Serhiy Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 970 | @_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 Storchaka | fcb2856 | 2020-05-10 11:53:16 +0300 | [diff] [blame] | 976 | _check_generic(self, params, self._nparams) |
Serhiy Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 977 | 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 Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 985 | |
| 986 | def __subclasscheck__(self, cls): |
Serhiy Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 987 | 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 Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 992 | |
Ivan Levkivskyi | 8349403 | 2018-03-26 23:01:12 +0100 | [diff] [blame] | 993 | def __reduce__(self): |
Serhiy Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 994 | return self._name |
Ivan Levkivskyi | 8349403 | 2018-03-26 23:01:12 +0100 | [diff] [blame] | 995 | |
Maggie Moss | 1b4552c | 2020-09-09 13:23:24 -0700 | [diff] [blame] | 996 | def __or__(self, right): |
| 997 | return Union[self, right] |
| 998 | |
| 999 | def __ror__(self, right): |
| 1000 | return Union[self, right] |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1001 | |
Serhiy Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 1002 | class _CallableGenericAlias(_GenericAlias, _root=True): |
| 1003 | def __repr__(self): |
| 1004 | assert self._name == 'Callable' |
kj | 73607be | 2020-12-24 12:33:48 +0800 | [diff] [blame] | 1005 | args = self.__args__ |
| 1006 | if len(args) == 2 and (args[0] is Ellipsis |
| 1007 | or isinstance(args[0], (ParamSpec, _ConcatenateGenericAlias))): |
Serhiy Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 1008 | return super().__repr__() |
| 1009 | return (f'typing.Callable' |
kj | 73607be | 2020-12-24 12:33:48 +0800 | [diff] [blame] | 1010 | f'[[{", ".join([_type_repr(a) for a in args[:-1]])}], ' |
| 1011 | f'{_type_repr(args[-1])}]') |
Serhiy Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 1012 | |
| 1013 | def __reduce__(self): |
| 1014 | args = self.__args__ |
kj | 73607be | 2020-12-24 12:33:48 +0800 | [diff] [blame] | 1015 | if not (len(args) == 2 and (args[0] is Ellipsis |
| 1016 | or isinstance(args[0], (ParamSpec, _ConcatenateGenericAlias)))): |
Serhiy Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 1017 | args = list(args[:-1]), args[-1] |
| 1018 | return operator.getitem, (Callable, args) |
| 1019 | |
| 1020 | |
| 1021 | class _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 Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1026 | def __getitem__(self, params): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1027 | 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 |
kj | 463c7d3 | 2020-12-14 02:38:24 +0800 | [diff] [blame] | 1031 | # 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 Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1035 | params = (tuple(args), result) |
kj | 463c7d3 | 2020-12-14 02:38:24 +0800 | [diff] [blame] | 1036 | else: |
| 1037 | params = (args, result) |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1038 | return self.__getitem_inner__(params) |
| 1039 | |
| 1040 | @_tp_cache |
| 1041 | def __getitem_inner__(self, params): |
Serhiy Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 1042 | 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)) |
kj | 463c7d3 | 2020-12-14 02:38:24 +0800 | [diff] [blame] | 1047 | if not isinstance(args, tuple): |
| 1048 | args = (args,) |
| 1049 | args = tuple(_type_convert(arg) for arg in args) |
Serhiy Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 1050 | params = args + (result,) |
| 1051 | return self.copy_with(params) |
| 1052 | |
| 1053 | |
| 1054 | class _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 | |
| 1070 | class _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 Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1090 | |
Maggie Moss | 1b4552c | 2020-09-09 13:23:24 -0700 | [diff] [blame] | 1091 | 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 Karabas | f03d318 | 2020-11-17 04:23:19 +0200 | [diff] [blame] | 1100 | def _value_and_type_iter(parameters): |
| 1101 | return ((p, type(p)) for p in parameters) |
| 1102 | |
| 1103 | |
| 1104 | class _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 Karabas | 1b54077 | 2020-11-19 18:17:38 +0200 | [diff] [blame] | 1113 | return hash(frozenset(_value_and_type_iter(self.__args__))) |
Yurii Karabas | f03d318 | 2020-11-17 04:23:19 +0200 | [diff] [blame] | 1114 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1115 | |
kj | 73607be | 2020-12-24 12:33:48 +0800 | [diff] [blame] | 1116 | class _ConcatenateGenericAlias(_GenericAlias, _root=True): |
| 1117 | pass |
| 1118 | |
| 1119 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1120 | class Generic: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1121 | """Abstract base class for generic types. |
| 1122 | |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 1123 | A generic type is typically declared by inheriting from |
| 1124 | this class parameterized with one or more type variables. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1125 | 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 Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1134 | def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1135 | try: |
| 1136 | return mapping[key] |
| 1137 | except KeyError: |
| 1138 | return default |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1139 | """ |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1140 | __slots__ = () |
Ivan Levkivskyi | 74d7f76 | 2019-05-28 08:40:15 +0100 | [diff] [blame] | 1141 | _is_protocol = False |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1142 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1143 | @_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") |
kj | 73607be | 2020-12-24 12:33:48 +0800 | [diff] [blame] | 1150 | params = tuple(_type_convert(p) for p in params) |
Ivan Levkivskyi | 74d7f76 | 2019-05-28 08:40:15 +0100 | [diff] [blame] | 1151 | if cls in (Generic, Protocol): |
| 1152 | # Generic and Protocol can only be subscripted with unique type variables. |
kj | 73607be | 2020-12-24 12:33:48 +0800 | [diff] [blame] | 1153 | if not all(isinstance(p, _TypeVarLike) for p in params): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1154 | raise TypeError( |
kj | 73607be | 2020-12-24 12:33:48 +0800 | [diff] [blame] | 1155 | f"Parameters to {cls.__name__}[...] must all be type variables " |
| 1156 | f"or parameter specification variables.") |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1157 | if len(set(params)) != len(params): |
| 1158 | raise TypeError( |
Ivan Levkivskyi | 74d7f76 | 2019-05-28 08:40:15 +0100 | [diff] [blame] | 1159 | f"Parameters to {cls.__name__}[...] must all be unique") |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1160 | else: |
| 1161 | # Subscripting a regular Generic subclass. |
kj | 73607be | 2020-12-24 12:33:48 +0800 | [diff] [blame] | 1162 | if any(isinstance(t, ParamSpec) for t in cls.__parameters__): |
| 1163 | params = _prepare_paramspec_params(cls, params) |
Serhiy Storchaka | fcb2856 | 2020-05-10 11:53:16 +0300 | [diff] [blame] | 1164 | _check_generic(cls, params, len(cls.__parameters__)) |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1165 | return _GenericAlias(cls, params) |
| 1166 | |
| 1167 | def __init_subclass__(cls, *args, **kwargs): |
Ivan Levkivskyi | ee566fe | 2018-04-04 17:00:15 +0100 | [diff] [blame] | 1168 | super().__init_subclass__(*args, **kwargs) |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1169 | tvars = [] |
| 1170 | if '__orig_bases__' in cls.__dict__: |
| 1171 | error = Generic in cls.__orig_bases__ |
| 1172 | else: |
Ivan Levkivskyi | 74d7f76 | 2019-05-28 08:40:15 +0100 | [diff] [blame] | 1173 | error = Generic in cls.__bases__ and cls.__name__ != 'Protocol' |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1174 | 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 Levkivskyi | 74d7f76 | 2019-05-28 08:40:15 +0100 | [diff] [blame] | 1191 | if gvars is not None: |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1192 | 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 Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1201 | |
| 1202 | |
| 1203 | class _TypingEmpty: |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 1204 | """Internal placeholder for () or []. Used by TupleMeta and CallableMeta |
| 1205 | to allow empty list/tuple in specific places, without allowing them |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1206 | to sneak in where prohibited. |
| 1207 | """ |
| 1208 | |
| 1209 | |
| 1210 | class _TypingEllipsis: |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 1211 | """Internal placeholder for ... (ellipsis).""" |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1212 | |
| 1213 | |
Ivan Levkivskyi | 74d7f76 | 2019-05-28 08:40:15 +0100 | [diff] [blame] | 1214 | _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 Rossum | 48b069a | 2020-04-07 09:50:06 -0700 | [diff] [blame] | 1219 | '__subclasshook__', '__weakref__', '__class_getitem__'] |
Ivan Levkivskyi | 74d7f76 | 2019-05-28 08:40:15 +0100 | [diff] [blame] | 1220 | |
| 1221 | # These special attributes will be not collected as protocol members. |
| 1222 | EXCLUDED_ATTRIBUTES = _TYPING_INTERNALS + _SPECIAL_NAMES + ['_MutableMapping__marker'] |
| 1223 | |
| 1224 | |
| 1225 | def _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 | |
| 1242 | def _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 | |
| 1247 | def _no_init(self, *args, **kwargs): |
| 1248 | if type(self)._is_protocol: |
| 1249 | raise TypeError('Protocols cannot be instantiated') |
| 1250 | |
| 1251 | |
Ross | c1af128 | 2020-12-29 11:55:28 +0000 | [diff] [blame] | 1252 | def _allow_reckless_class_checks(): |
Nickolena Fisher | cfaf4c0 | 2020-04-26 12:49:11 -0500 | [diff] [blame] | 1253 | """Allow instance and class checks for special stdlib modules. |
Ivan Levkivskyi | 74d7f76 | 2019-05-28 08:40:15 +0100 | [diff] [blame] | 1254 | |
| 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 Stinner | 0e95bbf | 2020-08-12 10:53:12 +0200 | [diff] [blame] | 1264 | _PROTO_ALLOWLIST = { |
Divij Rajkumar | 692a0dc | 2019-09-12 11:13:51 +0100 | [diff] [blame] | 1265 | 'collections.abc': [ |
| 1266 | 'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable', |
| 1267 | 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible', |
| 1268 | ], |
| 1269 | 'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'], |
| 1270 | } |
Ivan Levkivskyi | 74d7f76 | 2019-05-28 08:40:15 +0100 | [diff] [blame] | 1271 | |
| 1272 | |
| 1273 | class _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 | |
| 1293 | class 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): |
Ross | c1af128 | 2020-12-29 11:55:28 +0000 | [diff] [blame] | 1341 | if _allow_reckless_class_checks(): |
Ivan Levkivskyi | 74d7f76 | 2019-05-28 08:40:15 +0100 | [diff] [blame] | 1342 | 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): |
Ross | c1af128 | 2020-12-29 11:55:28 +0000 | [diff] [blame] | 1346 | if _allow_reckless_class_checks(): |
Ivan Levkivskyi | 74d7f76 | 2019-05-28 08:40:15 +0100 | [diff] [blame] | 1347 | 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 Stinner | 0e95bbf | 2020-08-12 10:53:12 +0200 | [diff] [blame] | 1383 | base.__module__ in _PROTO_ALLOWLIST and |
| 1384 | base.__name__ in _PROTO_ALLOWLIST[base.__module__] or |
Ivan Levkivskyi | 74d7f76 | 2019-05-28 08:40:15 +0100 | [diff] [blame] | 1385 | 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 Stasiak | cf5b109 | 2020-02-05 02:10:19 +0100 | [diff] [blame] | 1391 | class _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 Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 1425 | return (self.__origin__ == other.__origin__ |
| 1426 | and self.__metadata__ == other.__metadata__) |
Jakub Stasiak | cf5b109 | 2020-02-05 02:10:19 +0100 | [diff] [blame] | 1427 | |
| 1428 | def __hash__(self): |
| 1429 | return hash((self.__origin__, self.__metadata__)) |
| 1430 | |
| 1431 | |
| 1432 | class 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 Levkivskyi | 74d7f76 | 2019-05-28 08:40:15 +0100 | [diff] [blame] | 1485 | def 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1510 | def 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 | |
| 1521 | def _get_defaults(func): |
| 1522 | """Internal helper to extract the default arguments, by name.""" |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1523 | try: |
| 1524 | code = func.__code__ |
| 1525 | except AttributeError: |
| 1526 | # Some built-in functions don't have __code__, __defaults__, etc. |
| 1527 | return {} |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1528 | pos_count = code.co_argcount |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1529 | arg_names = code.co_varnames |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1530 | 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 Levkivskyi | b692dc8 | 2017-02-13 22:50:14 +0100 | [diff] [blame] | 1541 | _allowed_types = (types.FunctionType, types.BuiltinFunctionType, |
| 1542 | types.MethodType, types.ModuleType, |
Ivan Levkivskyi | f06e021 | 2017-05-02 19:14:07 +0200 | [diff] [blame] | 1543 | WrapperDescriptorType, MethodWrapperType, MethodDescriptorType) |
Ivan Levkivskyi | b692dc8 | 2017-02-13 22:50:14 +0100 | [diff] [blame] | 1544 | |
| 1545 | |
Jakub Stasiak | cf5b109 | 2020-02-05 02:10:19 +0100 | [diff] [blame] | 1546 | def get_type_hints(obj, globalns=None, localns=None, include_extras=False): |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1547 | """Return type hints for an object. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1548 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1549 | This is often the same as obj.__annotations__, but it handles |
Jakub Stasiak | cf5b109 | 2020-02-05 02:10:19 +0100 | [diff] [blame] | 1550 | 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1553 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1554 | 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1557 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1558 | 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1561 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1562 | 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1565 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1566 | - If no dict arguments are passed, an attempt is made to use the |
Łukasz Langa | f350a26 | 2017-09-14 14:33:00 -0400 | [diff] [blame] | 1567 | 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 Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1570 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1571 | - If one dict argument is passed, it is used for both globals and |
| 1572 | locals. |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1573 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1574 | - If two dict arguments are passed, they specify globals and |
| 1575 | locals, respectively. |
| 1576 | """ |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1577 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1578 | if getattr(obj, '__no_type_check__', None): |
| 1579 | return {} |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1580 | # Classes require a special treatment. |
| 1581 | if isinstance(obj, type): |
| 1582 | hints = {} |
| 1583 | for base in reversed(obj.__mro__): |
Łukasz Langa | f350a26 | 2017-09-14 14:33:00 -0400 | [diff] [blame] | 1584 | if globalns is None: |
| 1585 | base_globals = sys.modules[base.__module__].__dict__ |
| 1586 | else: |
| 1587 | base_globals = globalns |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1588 | 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 Zakharenko | 0e61dff | 2018-05-22 20:32:10 -0700 | [diff] [blame] | 1593 | value = ForwardRef(value, is_argument=False) |
Łukasz Langa | f350a26 | 2017-09-14 14:33:00 -0400 | [diff] [blame] | 1594 | value = _eval_type(value, base_globals, localns) |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1595 | hints[name] = value |
Jakub Stasiak | cf5b109 | 2020-02-05 02:10:19 +0100 | [diff] [blame] | 1596 | return hints if include_extras else {k: _strip_annotations(t) for k, t in hints.items()} |
Łukasz Langa | f350a26 | 2017-09-14 14:33:00 -0400 | [diff] [blame] | 1597 | |
| 1598 | if globalns is None: |
| 1599 | if isinstance(obj, types.ModuleType): |
| 1600 | globalns = obj.__dict__ |
| 1601 | else: |
benedwards14 | 0aca3a3 | 2019-11-21 17:24:58 +0000 | [diff] [blame] | 1602 | nsobj = obj |
| 1603 | # Find globalns for the unwrapped object. |
| 1604 | while hasattr(nsobj, '__wrapped__'): |
| 1605 | nsobj = nsobj.__wrapped__ |
| 1606 | globalns = getattr(nsobj, '__globals__', {}) |
Łukasz Langa | f350a26 | 2017-09-14 14:33:00 -0400 | [diff] [blame] | 1607 | if localns is None: |
| 1608 | localns = globalns |
| 1609 | elif localns is None: |
| 1610 | localns = globalns |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1611 | hints = getattr(obj, '__annotations__', None) |
| 1612 | if hints is None: |
| 1613 | # Return empty annotations for something that _could_ have them. |
Ivan Levkivskyi | b692dc8 | 2017-02-13 22:50:14 +0100 | [diff] [blame] | 1614 | if isinstance(obj, _allowed_types): |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1615 | return {} |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1616 | 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 Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1625 | value = ForwardRef(value) |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1626 | 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 Stasiak | cf5b109 | 2020-02-05 02:10:19 +0100 | [diff] [blame] | 1630 | return hints if include_extras else {k: _strip_annotations(t) for k, t in hints.items()} |
| 1631 | |
| 1632 | |
| 1633 | def _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 Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 1642 | return t.copy_with(stripped_args) |
Serhiy Storchaka | 68b352a | 2020-04-26 21:21:08 +0300 | [diff] [blame] | 1643 | 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 Stasiak | cf5b109 | 2020-02-05 02:10:19 +0100 | [diff] [blame] | 1648 | return t |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1649 | |
| 1650 | |
Ivan Levkivskyi | 4c23aff | 2019-05-31 00:10:07 +0100 | [diff] [blame] | 1651 | def get_origin(tp): |
| 1652 | """Get the unsubscripted version of a type. |
| 1653 | |
Jakub Stasiak | 38aaaaa | 2020-02-07 02:15:12 +0100 | [diff] [blame] | 1654 | This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar |
| 1655 | and Annotated. Return None for unsupported types. Examples:: |
Ivan Levkivskyi | 4c23aff | 2019-05-31 00:10:07 +0100 | [diff] [blame] | 1656 | |
| 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 Stasiak | cf5b109 | 2020-02-05 02:10:19 +0100 | [diff] [blame] | 1665 | if isinstance(tp, _AnnotatedAlias): |
| 1666 | return Annotated |
Serhiy Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 1667 | if isinstance(tp, (_BaseGenericAlias, GenericAlias)): |
Ivan Levkivskyi | 4c23aff | 2019-05-31 00:10:07 +0100 | [diff] [blame] | 1668 | return tp.__origin__ |
| 1669 | if tp is Generic: |
| 1670 | return Generic |
Ken Jin | efb1f09 | 2020-12-29 10:26:19 +0800 | [diff] [blame] | 1671 | if isinstance(tp, types.Union): |
| 1672 | return types.Union |
Ivan Levkivskyi | 4c23aff | 2019-05-31 00:10:07 +0100 | [diff] [blame] | 1673 | return None |
| 1674 | |
| 1675 | |
| 1676 | def 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 Stasiak | cf5b109 | 2020-02-05 02:10:19 +0100 | [diff] [blame] | 1687 | if isinstance(tp, _AnnotatedAlias): |
| 1688 | return (tp.__origin__,) + tp.__metadata__ |
Ken Jin | 4140f10 | 2020-12-29 04:06:19 +0800 | [diff] [blame] | 1689 | if isinstance(tp, (_GenericAlias, GenericAlias)): |
Ivan Levkivskyi | 4c23aff | 2019-05-31 00:10:07 +0100 | [diff] [blame] | 1690 | res = tp.__args__ |
Ken Jin | efb1f09 | 2020-12-29 10:26:19 +0800 | [diff] [blame] | 1691 | if (tp.__origin__ is collections.abc.Callable |
| 1692 | and not (res[0] is Ellipsis |
| 1693 | or isinstance(res[0], (ParamSpec, _ConcatenateGenericAlias)))): |
Ivan Levkivskyi | 4c23aff | 2019-05-31 00:10:07 +0100 | [diff] [blame] | 1694 | res = (list(res[:-1]), res[-1]) |
| 1695 | return res |
Ken Jin | efb1f09 | 2020-12-29 10:26:19 +0800 | [diff] [blame] | 1696 | if isinstance(tp, types.Union): |
| 1697 | return tp.__args__ |
Ivan Levkivskyi | 4c23aff | 2019-05-31 00:10:07 +0100 | [diff] [blame] | 1698 | return () |
| 1699 | |
| 1700 | |
Patrick Reader | 0705ec8 | 2020-09-16 05:58:32 +0100 | [diff] [blame] | 1701 | def 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1715 | def 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 Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1719 | applies recursively to all methods and classes defined in that class |
| 1720 | (but not to methods defined in its superclasses or subclasses). |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1721 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1722 | This mutates the function(s) or class(es) in place. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1723 | """ |
| 1724 | if isinstance(arg, type): |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1725 | arg_attrs = arg.__dict__.copy() |
| 1726 | for attr, val in arg.__dict__.items(): |
Ivan Levkivskyi | 65bc620 | 2017-09-14 01:25:15 +0200 | [diff] [blame] | 1727 | if val in arg.__bases__ + (arg,): |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1728 | arg_attrs.pop(attr) |
| 1729 | for obj in arg_attrs.values(): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1730 | if isinstance(obj, types.FunctionType): |
| 1731 | obj.__no_type_check__ = True |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1732 | if isinstance(obj, type): |
| 1733 | no_type_check(obj) |
| 1734 | try: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1735 | arg.__no_type_check__ = True |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 1736 | except TypeError: # built-in classes |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1737 | pass |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1738 | return arg |
| 1739 | |
| 1740 | |
| 1741 | def 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 Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1757 | def _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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1766 | def overload(func): |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1767 | """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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1793 | |
| 1794 | |
Ivan Levkivskyi | f367242 | 2019-05-26 09:37:07 +0100 | [diff] [blame] | 1795 | def 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 Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1821 | # Some unconstrained type variables. These are used by the container types. |
| 1822 | # (These are not for export.) |
| 1823 | T = TypeVar('T') # Any type. |
| 1824 | KT = TypeVar('KT') # Key type. |
| 1825 | VT = TypeVar('VT') # Value type. |
| 1826 | T_co = TypeVar('T_co', covariant=True) # Any type covariant containers. |
| 1827 | V_co = TypeVar('V_co', covariant=True) # Any type covariant containers. |
| 1828 | VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers. |
| 1829 | T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant. |
| 1830 | # Internal type variable used for Type[]. |
| 1831 | CT_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!) |
| 1835 | AnyStr = TypeVar('AnyStr', bytes, str) |
| 1836 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1837 | |
| 1838 | # Various ABCs mimicking those in collections.abc. |
Serhiy Storchaka | c1c7d8e | 2020-05-07 04:09:33 +0300 | [diff] [blame] | 1839 | _alias = _SpecialGenericAlias |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1840 | |
Serhiy Storchaka | fcb2856 | 2020-05-10 11:53:16 +0300 | [diff] [blame] | 1841 | Hashable = _alias(collections.abc.Hashable, 0) # Not generic. |
| 1842 | Awaitable = _alias(collections.abc.Awaitable, 1) |
| 1843 | Coroutine = _alias(collections.abc.Coroutine, 3) |
| 1844 | AsyncIterable = _alias(collections.abc.AsyncIterable, 1) |
| 1845 | AsyncIterator = _alias(collections.abc.AsyncIterator, 1) |
| 1846 | Iterable = _alias(collections.abc.Iterable, 1) |
| 1847 | Iterator = _alias(collections.abc.Iterator, 1) |
| 1848 | Reversible = _alias(collections.abc.Reversible, 1) |
| 1849 | Sized = _alias(collections.abc.Sized, 0) # Not generic. |
| 1850 | Container = _alias(collections.abc.Container, 1) |
| 1851 | Collection = _alias(collections.abc.Collection, 1) |
| 1852 | Callable = _CallableType(collections.abc.Callable, 2) |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1853 | Callable.__doc__ = \ |
| 1854 | """Callable type; Callable[[int], str] is a function of (int) -> str. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1855 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1856 | 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1859 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1860 | There is no syntax to indicate optional or keyword arguments, |
| 1861 | such function types are rarely used as callback types. |
| 1862 | """ |
Serhiy Storchaka | fcb2856 | 2020-05-10 11:53:16 +0300 | [diff] [blame] | 1863 | AbstractSet = _alias(collections.abc.Set, 1, name='AbstractSet') |
| 1864 | MutableSet = _alias(collections.abc.MutableSet, 1) |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1865 | # NOTE: Mapping is only covariant in the value type. |
Serhiy Storchaka | fcb2856 | 2020-05-10 11:53:16 +0300 | [diff] [blame] | 1866 | Mapping = _alias(collections.abc.Mapping, 2) |
| 1867 | MutableMapping = _alias(collections.abc.MutableMapping, 2) |
| 1868 | Sequence = _alias(collections.abc.Sequence, 1) |
| 1869 | MutableSequence = _alias(collections.abc.MutableSequence, 1) |
| 1870 | ByteString = _alias(collections.abc.ByteString, 0) # Not generic |
| 1871 | # Tuple accepts variable number of parameters. |
| 1872 | Tuple = _TupleType(tuple, -1, inst=False, name='Tuple') |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1873 | Tuple.__doc__ = \ |
| 1874 | """Tuple type; Tuple[X, Y] is the cross-product type of X and Y. |
Guido van Rossum | 62fe1bb | 2016-10-29 16:05:26 -0700 | [diff] [blame] | 1875 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1876 | 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 Rossum | 62fe1bb | 2016-10-29 16:05:26 -0700 | [diff] [blame] | 1879 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1880 | To specify a variable-length tuple of homogeneous type, use Tuple[T, ...]. |
| 1881 | """ |
Serhiy Storchaka | fcb2856 | 2020-05-10 11:53:16 +0300 | [diff] [blame] | 1882 | List = _alias(list, 1, inst=False, name='List') |
| 1883 | Deque = _alias(collections.deque, 1, name='Deque') |
| 1884 | Set = _alias(set, 1, inst=False, name='Set') |
| 1885 | FrozenSet = _alias(frozenset, 1, inst=False, name='FrozenSet') |
| 1886 | MappingView = _alias(collections.abc.MappingView, 1) |
| 1887 | KeysView = _alias(collections.abc.KeysView, 1) |
| 1888 | ItemsView = _alias(collections.abc.ItemsView, 2) |
| 1889 | ValuesView = _alias(collections.abc.ValuesView, 1) |
| 1890 | ContextManager = _alias(contextlib.AbstractContextManager, 1, name='ContextManager') |
| 1891 | AsyncContextManager = _alias(contextlib.AbstractAsyncContextManager, 1, name='AsyncContextManager') |
| 1892 | Dict = _alias(dict, 2, inst=False, name='Dict') |
| 1893 | DefaultDict = _alias(collections.defaultdict, 2, name='DefaultDict') |
| 1894 | OrderedDict = _alias(collections.OrderedDict, 2) |
| 1895 | Counter = _alias(collections.Counter, 1) |
| 1896 | ChainMap = _alias(collections.ChainMap, 2) |
| 1897 | Generator = _alias(collections.abc.Generator, 3) |
| 1898 | AsyncGenerator = _alias(collections.abc.AsyncGenerator, 2) |
| 1899 | Type = _alias(type, 1, inst=False, name='Type') |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1900 | Type.__doc__ = \ |
| 1901 | """A special construct usable to annotate class objects. |
Guido van Rossum | 62fe1bb | 2016-10-29 16:05:26 -0700 | [diff] [blame] | 1902 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1903 | For example, suppose we have the following classes:: |
Guido van Rossum | 62fe1bb | 2016-10-29 16:05:26 -0700 | [diff] [blame] | 1904 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1905 | class User: ... # Abstract base for User classes |
| 1906 | class BasicUser(User): ... |
| 1907 | class ProUser(User): ... |
| 1908 | class TeamUser(User): ... |
Guido van Rossum | f17c200 | 2015-12-03 17:31:24 -0800 | [diff] [blame] | 1909 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1910 | 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 Rossum | f17c200 | 2015-12-03 17:31:24 -0800 | [diff] [blame] | 1912 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1913 | 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 Rossum | f17c200 | 2015-12-03 17:31:24 -0800 | [diff] [blame] | 1918 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1919 | joe = new_user(BasicUser) |
Guido van Rossum | f17c200 | 2015-12-03 17:31:24 -0800 | [diff] [blame] | 1920 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1921 | At this point the type checker knows that joe has type BasicUser. |
| 1922 | """ |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1923 | |
| 1924 | |
Ivan Levkivskyi | 74d7f76 | 2019-05-28 08:40:15 +0100 | [diff] [blame] | 1925 | @runtime_checkable |
| 1926 | class SupportsInt(Protocol): |
Serhiy Storchaka | 8252c52 | 2019-10-08 16:30:17 +0300 | [diff] [blame] | 1927 | """An ABC with one abstract method __int__.""" |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1928 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1929 | |
| 1930 | @abstractmethod |
| 1931 | def __int__(self) -> int: |
| 1932 | pass |
| 1933 | |
| 1934 | |
Ivan Levkivskyi | 74d7f76 | 2019-05-28 08:40:15 +0100 | [diff] [blame] | 1935 | @runtime_checkable |
| 1936 | class SupportsFloat(Protocol): |
Serhiy Storchaka | 8252c52 | 2019-10-08 16:30:17 +0300 | [diff] [blame] | 1937 | """An ABC with one abstract method __float__.""" |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1938 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1939 | |
| 1940 | @abstractmethod |
| 1941 | def __float__(self) -> float: |
| 1942 | pass |
| 1943 | |
| 1944 | |
Ivan Levkivskyi | 74d7f76 | 2019-05-28 08:40:15 +0100 | [diff] [blame] | 1945 | @runtime_checkable |
| 1946 | class SupportsComplex(Protocol): |
Serhiy Storchaka | 8252c52 | 2019-10-08 16:30:17 +0300 | [diff] [blame] | 1947 | """An ABC with one abstract method __complex__.""" |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1948 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1949 | |
| 1950 | @abstractmethod |
| 1951 | def __complex__(self) -> complex: |
| 1952 | pass |
| 1953 | |
| 1954 | |
Ivan Levkivskyi | 74d7f76 | 2019-05-28 08:40:15 +0100 | [diff] [blame] | 1955 | @runtime_checkable |
| 1956 | class SupportsBytes(Protocol): |
Serhiy Storchaka | 8252c52 | 2019-10-08 16:30:17 +0300 | [diff] [blame] | 1957 | """An ABC with one abstract method __bytes__.""" |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1958 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1959 | |
| 1960 | @abstractmethod |
| 1961 | def __bytes__(self) -> bytes: |
| 1962 | pass |
| 1963 | |
| 1964 | |
Ivan Levkivskyi | 74d7f76 | 2019-05-28 08:40:15 +0100 | [diff] [blame] | 1965 | @runtime_checkable |
| 1966 | class SupportsIndex(Protocol): |
Serhiy Storchaka | 8252c52 | 2019-10-08 16:30:17 +0300 | [diff] [blame] | 1967 | """An ABC with one abstract method __index__.""" |
Paul Dagnelie | 4c7a46e | 2019-05-22 07:23:01 -0700 | [diff] [blame] | 1968 | __slots__ = () |
| 1969 | |
| 1970 | @abstractmethod |
| 1971 | def __index__(self) -> int: |
| 1972 | pass |
| 1973 | |
| 1974 | |
Ivan Levkivskyi | 74d7f76 | 2019-05-28 08:40:15 +0100 | [diff] [blame] | 1975 | @runtime_checkable |
| 1976 | class SupportsAbs(Protocol[T_co]): |
Serhiy Storchaka | 8252c52 | 2019-10-08 16:30:17 +0300 | [diff] [blame] | 1977 | """An ABC with one abstract method __abs__ that is covariant in its return type.""" |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1978 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1979 | |
| 1980 | @abstractmethod |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1981 | def __abs__(self) -> T_co: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1982 | pass |
| 1983 | |
| 1984 | |
Ivan Levkivskyi | 74d7f76 | 2019-05-28 08:40:15 +0100 | [diff] [blame] | 1985 | @runtime_checkable |
| 1986 | class SupportsRound(Protocol[T_co]): |
Serhiy Storchaka | 8252c52 | 2019-10-08 16:30:17 +0300 | [diff] [blame] | 1987 | """An ABC with one abstract method __round__ that is covariant in its return type.""" |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1988 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1989 | |
| 1990 | @abstractmethod |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1991 | def __round__(self, ndigits: int = 0) -> T_co: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1992 | pass |
| 1993 | |
| 1994 | |
Serhiy Storchaka | a2ec069 | 2020-04-08 10:59:04 +0300 | [diff] [blame] | 1995 | def _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 Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2002 | return nm_tpl |
| 2003 | |
| 2004 | |
Ivan Levkivskyi | b692dc8 | 2017-02-13 22:50:14 +0100 | [diff] [blame] | 2005 | # attributes prohibited to set in NamedTuple class syntax |
Serhiy Storchaka | a2ec069 | 2020-04-08 10:59:04 +0300 | [diff] [blame] | 2006 | _prohibited = frozenset({'__new__', '__init__', '__slots__', '__getnewargs__', |
| 2007 | '_fields', '_field_defaults', |
| 2008 | '_make', '_replace', '_asdict', '_source'}) |
Ivan Levkivskyi | b692dc8 | 2017-02-13 22:50:14 +0100 | [diff] [blame] | 2009 | |
Serhiy Storchaka | a2ec069 | 2020-04-08 10:59:04 +0300 | [diff] [blame] | 2010 | _special = frozenset({'__module__', '__name__', '__annotations__'}) |
Ivan Levkivskyi | b692dc8 | 2017-02-13 22:50:14 +0100 | [diff] [blame] | 2011 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2012 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2013 | class NamedTupleMeta(type): |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2014 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2015 | def __new__(cls, typename, bases, ns): |
Serhiy Storchaka | a2ec069 | 2020-04-08 10:59:04 +0300 | [diff] [blame] | 2016 | assert bases[0] is _NamedTuple |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2017 | types = ns.get('__annotations__', {}) |
Serhiy Storchaka | a2ec069 | 2020-04-08 10:59:04 +0300 | [diff] [blame] | 2018 | default_names = [] |
Guido van Rossum | 3c268be | 2017-01-18 08:03:50 -0800 | [diff] [blame] | 2019 | for field_name in types: |
| 2020 | if field_name in ns: |
Serhiy Storchaka | a2ec069 | 2020-04-08 10:59:04 +0300 | [diff] [blame] | 2021 | 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 Rossum | 95919c0 | 2017-01-22 17:47:20 -0800 | [diff] [blame] | 2030 | # update from user namespace without overriding special namedtuple attributes |
| 2031 | for key in ns: |
Ivan Levkivskyi | b692dc8 | 2017-02-13 22:50:14 +0100 | [diff] [blame] | 2032 | 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 Rossum | 95919c0 | 2017-01-22 17:47:20 -0800 | [diff] [blame] | 2035 | setattr(nm_tpl, key, ns[key]) |
Guido van Rossum | 3c268be | 2017-01-18 08:03:50 -0800 | [diff] [blame] | 2036 | return nm_tpl |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2037 | |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 2038 | |
Serhiy Storchaka | a2ec069 | 2020-04-08 10:59:04 +0300 | [diff] [blame] | 2039 | def NamedTuple(typename, fields=None, /, **kwargs): |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2040 | """Typed version of namedtuple. |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2041 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2042 | Usage in Python versions >= 3.6:: |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2043 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2044 | class Employee(NamedTuple): |
| 2045 | name: str |
| 2046 | id: int |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2047 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2048 | This is equivalent to:: |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2049 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2050 | Employee = collections.namedtuple('Employee', ['name', 'id']) |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2051 | |
Raymond Hettinger | f7b57df | 2019-03-18 09:53:56 -0700 | [diff] [blame] | 2052 | 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 Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2056 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2057 | Employee = NamedTuple('Employee', name=str, id=int) |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2058 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2059 | In Python versions <= 3.5 use:: |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2060 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2061 | Employee = NamedTuple('Employee', [('name', str), ('id', int)]) |
| 2062 | """ |
Serhiy Storchaka | a2ec069 | 2020-04-08 10:59:04 +0300 | [diff] [blame] | 2063 | 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 Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2073 | |
Serhiy Storchaka | a2ec069 | 2020-04-08 10:59:04 +0300 | [diff] [blame] | 2074 | _NamedTuple = type.__new__(NamedTupleMeta, 'NamedTuple', (), {}) |
| 2075 | |
| 2076 | def _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 | |
| 2082 | NamedTuple.__mro_entries__ = _namedtuple_mro_entries |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2083 | |
| 2084 | |
Ivan Levkivskyi | 135c6a5 | 2019-05-26 09:39:24 +0100 | [diff] [blame] | 2085 | class _TypedDictMeta(type): |
| 2086 | def __new__(cls, name, bases, ns, total=True): |
| 2087 | """Create new typed dict class object. |
| 2088 | |
Serhiy Storchaka | f228bf2 | 2020-04-08 11:03:27 +0300 | [diff] [blame] | 2089 | This method is called when TypedDict is subclassed, |
| 2090 | or when TypedDict is instantiated. This way |
Ivan Levkivskyi | 135c6a5 | 2019-05-26 09:39:24 +0100 | [diff] [blame] | 2091 | TypedDict supports all three syntax forms described in its docstring. |
Serhiy Storchaka | f228bf2 | 2020-04-08 11:03:27 +0300 | [diff] [blame] | 2092 | Subclasses and instances of TypedDict return actual dictionaries. |
Ivan Levkivskyi | 135c6a5 | 2019-05-26 09:39:24 +0100 | [diff] [blame] | 2093 | """ |
Serhiy Storchaka | f228bf2 | 2020-04-08 11:03:27 +0300 | [diff] [blame] | 2094 | 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 Levkivskyi | 135c6a5 | 2019-05-26 09:39:24 +0100 | [diff] [blame] | 2099 | |
Vlad Emelianov | 10e87e5 | 2020-02-13 20:53:29 +0100 | [diff] [blame] | 2100 | annotations = {} |
| 2101 | own_annotations = ns.get('__annotations__', {}) |
| 2102 | own_annotation_keys = set(own_annotations.keys()) |
Ivan Levkivskyi | 135c6a5 | 2019-05-26 09:39:24 +0100 | [diff] [blame] | 2103 | msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type" |
Vlad Emelianov | 10e87e5 | 2020-02-13 20:53:29 +0100 | [diff] [blame] | 2104 | 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-Dodds | 665ad3d | 2019-11-24 21:48:48 +1100 | [diff] [blame] | 2109 | |
Ivan Levkivskyi | 135c6a5 | 2019-05-26 09:39:24 +0100 | [diff] [blame] | 2110 | for base in bases: |
Vlad Emelianov | 10e87e5 | 2020-02-13 20:53:29 +0100 | [diff] [blame] | 2111 | 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-Dodds | 665ad3d | 2019-11-24 21:48:48 +1100 | [diff] [blame] | 2114 | |
Vlad Emelianov | 10e87e5 | 2020-02-13 20:53:29 +0100 | [diff] [blame] | 2115 | 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 Levkivskyi | 135c6a5 | 2019-05-26 09:39:24 +0100 | [diff] [blame] | 2124 | if not hasattr(tp_dict, '__total__'): |
| 2125 | tp_dict.__total__ = total |
| 2126 | return tp_dict |
| 2127 | |
Serhiy Storchaka | f228bf2 | 2020-04-08 11:03:27 +0300 | [diff] [blame] | 2128 | __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 Levkivskyi | 135c6a5 | 2019-05-26 09:39:24 +0100 | [diff] [blame] | 2135 | |
| 2136 | |
Serhiy Storchaka | f228bf2 | 2020-04-08 11:03:27 +0300 | [diff] [blame] | 2137 | def TypedDict(typename, fields=None, /, *, total=True, **kwargs): |
Ivan Levkivskyi | 135c6a5 | 2019-05-26 09:39:24 +0100 | [diff] [blame] | 2138 | """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-Dodds | 665ad3d | 2019-11-24 21:48:48 +1100 | [diff] [blame] | 2156 | 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 Levkivskyi | 135c6a5 | 2019-05-26 09:39:24 +0100 | [diff] [blame] | 2159 | |
| 2160 | Point2D = TypedDict('Point2D', x=int, y=int, label=str) |
| 2161 | Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) |
| 2162 | |
ananthan-123 | ab6423f | 2020-02-19 10:03:05 +0530 | [diff] [blame] | 2163 | 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 Levkivskyi | 135c6a5 | 2019-05-26 09:39:24 +0100 | [diff] [blame] | 2176 | 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 Storchaka | f228bf2 | 2020-04-08 11:03:27 +0300 | [diff] [blame] | 2179 | 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önholm | 67b769f | 2020-12-10 23:49:05 +0200 | [diff] [blame] | 2185 | ns = {'__annotations__': dict(fields)} |
Serhiy Storchaka | f228bf2 | 2020-04-08 11:03:27 +0300 | [diff] [blame] | 2186 | 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önholm | 67b769f | 2020-12-10 23:49:05 +0200 | [diff] [blame] | 2192 | return _TypedDictMeta(typename, (), ns, total=total) |
Serhiy Storchaka | f228bf2 | 2020-04-08 11:03:27 +0300 | [diff] [blame] | 2193 | |
| 2194 | _TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {}) |
| 2195 | TypedDict.__mro_entries__ = lambda bases: (_TypedDict,) |
Ivan Levkivskyi | 135c6a5 | 2019-05-26 09:39:24 +0100 | [diff] [blame] | 2196 | |
| 2197 | |
Guido van Rossum | 91185fe | 2016-06-08 11:19:11 -0700 | [diff] [blame] | 2198 | def 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 Rossum | 0e0563c | 2016-04-05 14:54:25 -0700 | [diff] [blame] | 2225 | # Python-version-specific alias (Python 2: unicode; Python 3: str) |
| 2226 | Text = str |
| 2227 | |
| 2228 | |
Guido van Rossum | 91185fe | 2016-06-08 11:19:11 -0700 | [diff] [blame] | 2229 | # Constant that's True when type checking, but False here. |
| 2230 | TYPE_CHECKING = False |
| 2231 | |
| 2232 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2233 | class 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 Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 2246 | __slots__ = () |
| 2247 | |
HongWeipeng | 6ce03ec | 2019-09-27 15:54:26 +0800 | [diff] [blame] | 2248 | @property |
| 2249 | @abstractmethod |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2250 | def mode(self) -> str: |
| 2251 | pass |
| 2252 | |
HongWeipeng | 6ce03ec | 2019-09-27 15:54:26 +0800 | [diff] [blame] | 2253 | @property |
| 2254 | @abstractmethod |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2255 | def name(self) -> str: |
| 2256 | pass |
| 2257 | |
| 2258 | @abstractmethod |
| 2259 | def close(self) -> None: |
| 2260 | pass |
| 2261 | |
Shantanu | 2e6569b | 2020-01-29 18:52:36 -0800 | [diff] [blame] | 2262 | @property |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2263 | @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 | |
| 2332 | class BinaryIO(IO[bytes]): |
| 2333 | """Typed version of the return of open() in binary mode.""" |
| 2334 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 2335 | __slots__ = () |
| 2336 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2337 | @abstractmethod |
| 2338 | def write(self, s: Union[bytes, bytearray]) -> int: |
| 2339 | pass |
| 2340 | |
| 2341 | @abstractmethod |
| 2342 | def __enter__(self) -> 'BinaryIO': |
| 2343 | pass |
| 2344 | |
| 2345 | |
| 2346 | class TextIO(IO[str]): |
| 2347 | """Typed version of the return of open() in text mode.""" |
| 2348 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 2349 | __slots__ = () |
| 2350 | |
HongWeipeng | 6ce03ec | 2019-09-27 15:54:26 +0800 | [diff] [blame] | 2351 | @property |
| 2352 | @abstractmethod |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2353 | def buffer(self) -> BinaryIO: |
| 2354 | pass |
| 2355 | |
HongWeipeng | 6ce03ec | 2019-09-27 15:54:26 +0800 | [diff] [blame] | 2356 | @property |
| 2357 | @abstractmethod |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2358 | def encoding(self) -> str: |
| 2359 | pass |
| 2360 | |
HongWeipeng | 6ce03ec | 2019-09-27 15:54:26 +0800 | [diff] [blame] | 2361 | @property |
| 2362 | @abstractmethod |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 2363 | def errors(self) -> Optional[str]: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2364 | pass |
| 2365 | |
HongWeipeng | 6ce03ec | 2019-09-27 15:54:26 +0800 | [diff] [blame] | 2366 | @property |
| 2367 | @abstractmethod |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2368 | def line_buffering(self) -> bool: |
| 2369 | pass |
| 2370 | |
HongWeipeng | 6ce03ec | 2019-09-27 15:54:26 +0800 | [diff] [blame] | 2371 | @property |
| 2372 | @abstractmethod |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2373 | def newlines(self) -> Any: |
| 2374 | pass |
| 2375 | |
| 2376 | @abstractmethod |
| 2377 | def __enter__(self) -> 'TextIO': |
| 2378 | pass |
| 2379 | |
| 2380 | |
| 2381 | class 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 Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 2389 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2390 | io.__name__ = __name__ + '.io' |
| 2391 | sys.modules[io.__name__] = io |
| 2392 | |
Serhiy Storchaka | fcb2856 | 2020-05-10 11:53:16 +0300 | [diff] [blame] | 2393 | Pattern = _alias(stdlib_re.Pattern, 1) |
| 2394 | Match = _alias(stdlib_re.Match, 1) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2395 | |
| 2396 | class re: |
| 2397 | """Wrapper namespace for re type aliases.""" |
| 2398 | |
| 2399 | __all__ = ['Pattern', 'Match'] |
| 2400 | Pattern = Pattern |
| 2401 | Match = Match |
| 2402 | |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 2403 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2404 | re.__name__ = __name__ + '.re' |
| 2405 | sys.modules[re.__name__] = re |