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