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