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: |
| 5 | * Imports and exports, all public names should be explicitelly added to __all__. |
| 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. |
| 12 | * The public counterpart of the generics API consists of two classes: Generic and Protocol |
| 13 | (the latter is currently private, but will be made public after PEP 544 acceptance). |
| 14 | * Public helper functions: get_type_hints, overload, cast, no_type_check, |
| 15 | no_type_check_decorator. |
| 16 | * Generic aliases for collections.abc ABCs and few additional protocols. |
| 17 | * Special types: NewType, NamedTuple, TypedDict (may be added soon). |
| 18 | * Wrapper submodules for re and io related types. |
| 19 | """ |
| 20 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 21 | import abc |
| 22 | from abc import abstractmethod, abstractproperty |
| 23 | import collections |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 24 | import collections.abc |
Brett Cannon | f3ad042 | 2016-04-15 10:51:30 -0700 | [diff] [blame] | 25 | import contextlib |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 26 | import functools |
| 27 | import re as stdlib_re # Avoid confusion with the re we export. |
| 28 | import sys |
| 29 | import types |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 30 | from types import WrapperDescriptorType, MethodWrapperType, MethodDescriptorType |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 31 | |
| 32 | # Please keep __all__ alphabetized within each category. |
| 33 | __all__ = [ |
| 34 | # Super-special typing primitives. |
| 35 | 'Any', |
| 36 | 'Callable', |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 37 | 'ClassVar', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 38 | 'Generic', |
| 39 | 'Optional', |
Guido van Rossum | eb9aca3 | 2016-05-24 16:38:22 -0700 | [diff] [blame] | 40 | 'Tuple', |
| 41 | 'Type', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 42 | 'TypeVar', |
| 43 | 'Union', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 44 | |
| 45 | # ABCs (from collections.abc). |
| 46 | 'AbstractSet', # collections.abc.Set. |
| 47 | 'ByteString', |
| 48 | 'Container', |
Ivan Levkivskyi | 29fda8d | 2017-06-10 21:57:56 +0200 | [diff] [blame] | 49 | 'ContextManager', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 50 | 'Hashable', |
| 51 | 'ItemsView', |
| 52 | 'Iterable', |
| 53 | 'Iterator', |
| 54 | 'KeysView', |
| 55 | 'Mapping', |
| 56 | 'MappingView', |
| 57 | 'MutableMapping', |
| 58 | 'MutableSequence', |
| 59 | 'MutableSet', |
| 60 | 'Sequence', |
| 61 | 'Sized', |
| 62 | 'ValuesView', |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 63 | 'Awaitable', |
| 64 | 'AsyncIterator', |
| 65 | 'AsyncIterable', |
| 66 | 'Coroutine', |
| 67 | 'Collection', |
| 68 | 'AsyncGenerator', |
| 69 | 'AsyncContextManager', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 70 | |
| 71 | # Structural checks, a.k.a. protocols. |
| 72 | 'Reversible', |
| 73 | 'SupportsAbs', |
Ivan Levkivskyi | f06e021 | 2017-05-02 19:14:07 +0200 | [diff] [blame] | 74 | 'SupportsBytes', |
| 75 | 'SupportsComplex', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 76 | 'SupportsFloat', |
| 77 | 'SupportsInt', |
| 78 | 'SupportsRound', |
| 79 | |
| 80 | # Concrete collection types. |
Ivan Levkivskyi | b692dc8 | 2017-02-13 22:50:14 +0100 | [diff] [blame] | 81 | 'Counter', |
Raymond Hettinger | 8049052 | 2017-01-16 22:42:37 -0800 | [diff] [blame] | 82 | 'Deque', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 83 | 'Dict', |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 84 | 'DefaultDict', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 85 | 'List', |
| 86 | 'Set', |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 87 | 'FrozenSet', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 88 | 'NamedTuple', # Not really a type. |
| 89 | 'Generator', |
| 90 | |
| 91 | # One-off things. |
| 92 | 'AnyStr', |
| 93 | 'cast', |
| 94 | 'get_type_hints', |
Guido van Rossum | 91185fe | 2016-06-08 11:19:11 -0700 | [diff] [blame] | 95 | 'NewType', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 96 | 'no_type_check', |
| 97 | 'no_type_check_decorator', |
aetracht | 4573820 | 2018-03-19 14:41:32 -0400 | [diff] [blame] | 98 | 'NoReturn', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 99 | 'overload', |
Guido van Rossum | 0e0563c | 2016-04-05 14:54:25 -0700 | [diff] [blame] | 100 | 'Text', |
Guido van Rossum | 91185fe | 2016-06-08 11:19:11 -0700 | [diff] [blame] | 101 | 'TYPE_CHECKING', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 102 | ] |
| 103 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 104 | # The pseudo-submodules 're' and 'io' are part of the public |
| 105 | # namespace, but excluded from __all__ because they might stomp on |
| 106 | # legitimate imports of those modules. |
| 107 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 108 | |
Nina Zakharenko | 2d2d3b1 | 2018-05-16 12:27:03 -0400 | [diff] [blame] | 109 | def _type_check(arg, msg, is_argument=False): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 110 | """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] | 111 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 112 | As a special case, accept None and return type(None) instead. Also wrap strings |
| 113 | into ForwardRef instances. Consider several corner cases, for example plain |
| 114 | special forms like Union are not valid, while Union[int, str] is OK, etc. |
| 115 | The msg argument is a human-readable error message, e.g:: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 116 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 117 | "Union[arg, ...]: arg should be a type." |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 118 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 119 | 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] | 120 | """ |
Nina Zakharenko | 2d2d3b1 | 2018-05-16 12:27:03 -0400 | [diff] [blame] | 121 | invalid_generic_forms = (Generic, _Protocol) |
| 122 | if not is_argument: |
| 123 | invalid_generic_forms = invalid_generic_forms + (ClassVar, ) |
| 124 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 125 | if arg is None: |
| 126 | return type(None) |
| 127 | if isinstance(arg, str): |
| 128 | return ForwardRef(arg) |
| 129 | if (isinstance(arg, _GenericAlias) and |
Nina Zakharenko | 2d2d3b1 | 2018-05-16 12:27:03 -0400 | [diff] [blame] | 130 | arg.__origin__ in invalid_generic_forms): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 131 | raise TypeError(f"{arg} is not valid as type argument") |
| 132 | if (isinstance(arg, _SpecialForm) and arg is not Any or |
| 133 | arg in (Generic, _Protocol)): |
| 134 | raise TypeError(f"Plain {arg} is not valid as type argument") |
| 135 | if isinstance(arg, (type, TypeVar, ForwardRef)): |
| 136 | return arg |
| 137 | if not callable(arg): |
| 138 | raise TypeError(f"{msg} Got {arg!r:.100}.") |
| 139 | return arg |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 140 | |
| 141 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 142 | def _type_repr(obj): |
| 143 | """Return the repr() of an object, special-casing types (internal helper). |
| 144 | |
| 145 | If obj is a type, we return a shorter version than the default |
| 146 | type.__repr__, based on the module and qualified name, which is |
| 147 | typically enough to uniquely identify a type. For everything |
| 148 | else, we fall back on repr(obj). |
| 149 | """ |
| 150 | if isinstance(obj, type): |
| 151 | if obj.__module__ == 'builtins': |
| 152 | return obj.__qualname__ |
| 153 | return f'{obj.__module__}.{obj.__qualname__}' |
| 154 | if obj is ...: |
| 155 | return('...') |
| 156 | if isinstance(obj, types.FunctionType): |
| 157 | return obj.__name__ |
| 158 | return repr(obj) |
| 159 | |
| 160 | |
| 161 | def _collect_type_vars(types): |
| 162 | """Collect all type variable contained in types in order of |
| 163 | first appearance (lexicographic order). For example:: |
| 164 | |
| 165 | _collect_type_vars((T, List[S, T])) == (T, S) |
| 166 | """ |
| 167 | tvars = [] |
| 168 | for t in types: |
| 169 | if isinstance(t, TypeVar) and t not in tvars: |
| 170 | tvars.append(t) |
| 171 | if isinstance(t, _GenericAlias) and not t._special: |
| 172 | tvars.extend([t for t in t.__parameters__ if t not in tvars]) |
| 173 | return tuple(tvars) |
| 174 | |
| 175 | |
| 176 | def _subs_tvars(tp, tvars, subs): |
| 177 | """Substitute type variables 'tvars' with substitutions 'subs'. |
| 178 | These two must have the same length. |
| 179 | """ |
| 180 | if not isinstance(tp, _GenericAlias): |
| 181 | return tp |
| 182 | new_args = list(tp.__args__) |
| 183 | for a, arg in enumerate(tp.__args__): |
| 184 | if isinstance(arg, TypeVar): |
| 185 | for i, tvar in enumerate(tvars): |
| 186 | if arg == tvar: |
| 187 | new_args[a] = subs[i] |
| 188 | else: |
| 189 | new_args[a] = _subs_tvars(arg, tvars, subs) |
| 190 | if tp.__origin__ is Union: |
| 191 | return Union[tuple(new_args)] |
| 192 | return tp.copy_with(tuple(new_args)) |
| 193 | |
| 194 | |
| 195 | def _check_generic(cls, parameters): |
| 196 | """Check correct count for parameters of a generic cls (internal helper). |
| 197 | This gives a nice error message in case of count mismatch. |
| 198 | """ |
| 199 | if not cls.__parameters__: |
| 200 | raise TypeError(f"{cls} is not a generic class") |
| 201 | alen = len(parameters) |
| 202 | elen = len(cls.__parameters__) |
| 203 | if alen != elen: |
| 204 | raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};" |
| 205 | f" actual {alen}, expected {elen}") |
| 206 | |
| 207 | |
| 208 | def _remove_dups_flatten(parameters): |
Ivan Levkivskyi | f65e31f | 2018-05-18 16:00:38 -0700 | [diff] [blame^] | 209 | """An internal helper for Union creation and substitution: flatten Unions |
| 210 | among parameters, then remove duplicates. |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 211 | """ |
| 212 | # Flatten out Union[Union[...], ...]. |
| 213 | params = [] |
| 214 | for p in parameters: |
| 215 | if isinstance(p, _GenericAlias) and p.__origin__ is Union: |
| 216 | params.extend(p.__args__) |
| 217 | elif isinstance(p, tuple) and len(p) > 0 and p[0] is Union: |
| 218 | params.extend(p[1:]) |
| 219 | else: |
| 220 | params.append(p) |
| 221 | # Weed out strict duplicates, preserving the first of each occurrence. |
| 222 | all_params = set(params) |
| 223 | if len(all_params) < len(params): |
| 224 | new_params = [] |
| 225 | for t in params: |
| 226 | if t in all_params: |
| 227 | new_params.append(t) |
| 228 | all_params.remove(t) |
| 229 | params = new_params |
| 230 | assert not all_params, all_params |
Ivan Levkivskyi | f65e31f | 2018-05-18 16:00:38 -0700 | [diff] [blame^] | 231 | return tuple(params) |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 232 | |
| 233 | |
| 234 | _cleanups = [] |
| 235 | |
| 236 | |
| 237 | def _tp_cache(func): |
| 238 | """Internal wrapper caching __getitem__ of generic types with a fallback to |
| 239 | original function for non-hashable arguments. |
| 240 | """ |
| 241 | cached = functools.lru_cache()(func) |
| 242 | _cleanups.append(cached.cache_clear) |
| 243 | |
| 244 | @functools.wraps(func) |
| 245 | def inner(*args, **kwds): |
| 246 | try: |
| 247 | return cached(*args, **kwds) |
| 248 | except TypeError: |
| 249 | pass # All real errors (not unhashable args) are raised below. |
| 250 | return func(*args, **kwds) |
| 251 | return inner |
| 252 | |
| 253 | |
| 254 | def _eval_type(t, globalns, localns): |
| 255 | """Evaluate all forward reverences in the given type t. |
| 256 | For use of globalns and localns see the docstring for get_type_hints(). |
| 257 | """ |
| 258 | if isinstance(t, ForwardRef): |
| 259 | return t._evaluate(globalns, localns) |
| 260 | if isinstance(t, _GenericAlias): |
| 261 | ev_args = tuple(_eval_type(a, globalns, localns) for a in t.__args__) |
| 262 | if ev_args == t.__args__: |
| 263 | return t |
| 264 | res = t.copy_with(ev_args) |
| 265 | res._special = t._special |
| 266 | return res |
| 267 | return t |
| 268 | |
| 269 | |
| 270 | class _Final: |
| 271 | """Mixin to prohibit subclassing""" |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 272 | |
Guido van Rossum | 83ec302 | 2017-01-17 20:43:28 -0800 | [diff] [blame] | 273 | __slots__ = ('__weakref__',) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 274 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 275 | def __init_subclass__(self, *args, **kwds): |
| 276 | if '_root' not in kwds: |
| 277 | raise TypeError("Cannot subclass special typing classes") |
| 278 | |
Ivan Levkivskyi | 8349403 | 2018-03-26 23:01:12 +0100 | [diff] [blame] | 279 | class _Immutable: |
| 280 | """Mixin to indicate that object should not be copied.""" |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 281 | |
Ivan Levkivskyi | 8349403 | 2018-03-26 23:01:12 +0100 | [diff] [blame] | 282 | def __copy__(self): |
| 283 | return self |
| 284 | |
| 285 | def __deepcopy__(self, memo): |
| 286 | return self |
| 287 | |
| 288 | |
| 289 | class _SpecialForm(_Final, _Immutable, _root=True): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 290 | """Internal indicator of special typing constructs. |
| 291 | See _doc instance attribute for specific docs. |
| 292 | """ |
| 293 | |
| 294 | __slots__ = ('_name', '_doc') |
| 295 | |
| 296 | def __getstate__(self): |
| 297 | return {'name': self._name, 'doc': self._doc} |
| 298 | |
| 299 | def __setstate__(self, state): |
| 300 | self._name = state['name'] |
| 301 | self._doc = state['doc'] |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 302 | |
| 303 | def __new__(cls, *args, **kwds): |
| 304 | """Constructor. |
| 305 | |
| 306 | This only exists to give a better error message in case |
| 307 | someone tries to subclass a special typing object (not a good idea). |
| 308 | """ |
| 309 | if (len(args) == 3 and |
| 310 | isinstance(args[0], str) and |
| 311 | isinstance(args[1], tuple)): |
| 312 | # Close enough. |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 313 | raise TypeError(f"Cannot subclass {cls!r}") |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 314 | return super().__new__(cls) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 315 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 316 | def __init__(self, name, doc): |
| 317 | self._name = name |
| 318 | self._doc = doc |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 319 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 320 | def __eq__(self, other): |
| 321 | if not isinstance(other, _SpecialForm): |
| 322 | return NotImplemented |
| 323 | return self._name == other._name |
| 324 | |
| 325 | def __hash__(self): |
| 326 | return hash((self._name,)) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 327 | |
| 328 | def __repr__(self): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 329 | return 'typing.' + self._name |
| 330 | |
Ivan Levkivskyi | 8349403 | 2018-03-26 23:01:12 +0100 | [diff] [blame] | 331 | def __reduce__(self): |
| 332 | return self._name |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 333 | |
| 334 | def __call__(self, *args, **kwds): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 335 | raise TypeError(f"Cannot instantiate {self!r}") |
| 336 | |
| 337 | def __instancecheck__(self, obj): |
| 338 | raise TypeError(f"{self} cannot be used with isinstance()") |
| 339 | |
| 340 | def __subclasscheck__(self, cls): |
| 341 | raise TypeError(f"{self} cannot be used with issubclass()") |
| 342 | |
| 343 | @_tp_cache |
| 344 | def __getitem__(self, parameters): |
| 345 | if self._name == 'ClassVar': |
| 346 | item = _type_check(parameters, 'ClassVar accepts only single type.') |
| 347 | return _GenericAlias(self, (item,)) |
| 348 | if self._name == 'Union': |
| 349 | if parameters == (): |
| 350 | raise TypeError("Cannot take a Union of no types.") |
| 351 | if not isinstance(parameters, tuple): |
| 352 | parameters = (parameters,) |
| 353 | msg = "Union[arg, ...]: each arg must be a type." |
| 354 | parameters = tuple(_type_check(p, msg) for p in parameters) |
| 355 | parameters = _remove_dups_flatten(parameters) |
| 356 | if len(parameters) == 1: |
| 357 | return parameters[0] |
| 358 | return _GenericAlias(self, parameters) |
| 359 | if self._name == 'Optional': |
| 360 | arg = _type_check(parameters, "Optional[t] requires a single type.") |
| 361 | return Union[arg, type(None)] |
| 362 | raise TypeError(f"{self} is not subscriptable") |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 363 | |
| 364 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 365 | Any = _SpecialForm('Any', doc= |
| 366 | """Special type indicating an unconstrained type. |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 367 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 368 | - Any is compatible with every type. |
| 369 | - Any assumed to have all methods. |
| 370 | - All values assumed to be instances of Any. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 371 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 372 | Note that all the above statements are true from the point of view of |
| 373 | static type checkers. At runtime, Any should not be used with instance |
| 374 | or class checks. |
| 375 | """) |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 376 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 377 | NoReturn = _SpecialForm('NoReturn', doc= |
| 378 | """Special type indicating functions that never return. |
| 379 | Example:: |
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 | from typing import NoReturn |
| 382 | |
| 383 | def stop() -> NoReturn: |
| 384 | raise Exception('no way') |
| 385 | |
| 386 | This type is invalid in other positions, e.g., ``List[NoReturn]`` |
| 387 | will fail in static type checkers. |
| 388 | """) |
| 389 | |
| 390 | ClassVar = _SpecialForm('ClassVar', doc= |
| 391 | """Special type construct to mark class variables. |
| 392 | |
| 393 | An annotation wrapped in ClassVar indicates that a given |
| 394 | attribute is intended to be used as a class variable and |
| 395 | should not be set on instances of that class. Usage:: |
| 396 | |
| 397 | class Starship: |
| 398 | stats: ClassVar[Dict[str, int]] = {} # class variable |
| 399 | damage: int = 10 # instance variable |
| 400 | |
| 401 | ClassVar accepts only types and cannot be further subscribed. |
| 402 | |
| 403 | Note that ClassVar is not a class itself, and should not |
| 404 | be used with isinstance() or issubclass(). |
| 405 | """) |
| 406 | |
| 407 | Union = _SpecialForm('Union', doc= |
| 408 | """Union type; Union[X, Y] means either X or Y. |
| 409 | |
| 410 | To define a union, use e.g. Union[int, str]. Details: |
| 411 | - The arguments must be types and there must be at least one. |
| 412 | - None as an argument is a special case and is replaced by |
| 413 | type(None). |
| 414 | - Unions of unions are flattened, e.g.:: |
| 415 | |
| 416 | Union[Union[int, str], float] == Union[int, str, float] |
| 417 | |
| 418 | - Unions of a single argument vanish, e.g.:: |
| 419 | |
| 420 | Union[int] == int # The constructor actually returns int |
| 421 | |
| 422 | - Redundant arguments are skipped, e.g.:: |
| 423 | |
| 424 | Union[int, str, int] == Union[int, str] |
| 425 | |
| 426 | - When comparing unions, the argument order is ignored, e.g.:: |
| 427 | |
| 428 | Union[int, str] == Union[str, int] |
| 429 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 430 | - You cannot subclass or instantiate a union. |
| 431 | - You can use Optional[X] as a shorthand for Union[X, None]. |
| 432 | """) |
| 433 | |
| 434 | Optional = _SpecialForm('Optional', doc= |
| 435 | """Optional type. |
| 436 | |
| 437 | Optional[X] is equivalent to Union[X, None]. |
| 438 | """) |
Guido van Rossum | b7dedc8 | 2016-10-29 12:44:29 -0700 | [diff] [blame] | 439 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 440 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 441 | class ForwardRef(_Final, _root=True): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 442 | """Internal wrapper to hold a forward reference.""" |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 443 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 444 | __slots__ = ('__forward_arg__', '__forward_code__', |
Nina Zakharenko | 2d2d3b1 | 2018-05-16 12:27:03 -0400 | [diff] [blame] | 445 | '__forward_evaluated__', '__forward_value__', |
| 446 | '__forward_is_argument__') |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 447 | |
Nina Zakharenko | 2d2d3b1 | 2018-05-16 12:27:03 -0400 | [diff] [blame] | 448 | def __init__(self, arg, is_argument=False): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 449 | if not isinstance(arg, str): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 450 | 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] | 451 | try: |
| 452 | code = compile(arg, '<string>', 'eval') |
| 453 | except SyntaxError: |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 454 | 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] | 455 | self.__forward_arg__ = arg |
| 456 | self.__forward_code__ = code |
| 457 | self.__forward_evaluated__ = False |
| 458 | self.__forward_value__ = None |
Nina Zakharenko | 2d2d3b1 | 2018-05-16 12:27:03 -0400 | [diff] [blame] | 459 | self.__forward_is_argument__ = is_argument |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 460 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 461 | def _evaluate(self, globalns, localns): |
Guido van Rossum | dad1790 | 2016-11-10 08:29:18 -0800 | [diff] [blame] | 462 | if not self.__forward_evaluated__ or localns is not globalns: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 463 | if globalns is None and localns is None: |
| 464 | globalns = localns = {} |
| 465 | elif globalns is None: |
| 466 | globalns = localns |
| 467 | elif localns is None: |
| 468 | localns = globalns |
| 469 | self.__forward_value__ = _type_check( |
| 470 | eval(self.__forward_code__, globalns, localns), |
Nina Zakharenko | 2d2d3b1 | 2018-05-16 12:27:03 -0400 | [diff] [blame] | 471 | "Forward references must evaluate to types.", |
| 472 | is_argument=self.__forward_is_argument__) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 473 | self.__forward_evaluated__ = True |
| 474 | return self.__forward_value__ |
| 475 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 476 | def __eq__(self, other): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 477 | if not isinstance(other, ForwardRef): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 478 | return NotImplemented |
| 479 | return (self.__forward_arg__ == other.__forward_arg__ and |
Guido van Rossum | c7b9295 | 2016-11-10 08:24:06 -0800 | [diff] [blame] | 480 | self.__forward_value__ == other.__forward_value__) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 481 | |
| 482 | def __hash__(self): |
Guido van Rossum | c7b9295 | 2016-11-10 08:24:06 -0800 | [diff] [blame] | 483 | return hash((self.__forward_arg__, self.__forward_value__)) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 484 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 485 | def __repr__(self): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 486 | return f'ForwardRef({self.__forward_arg__!r})' |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 487 | |
| 488 | |
Ivan Levkivskyi | 8349403 | 2018-03-26 23:01:12 +0100 | [diff] [blame] | 489 | def _find_name(mod, name): |
| 490 | return getattr(sys.modules[mod], name) |
| 491 | |
| 492 | |
| 493 | class TypeVar(_Final, _Immutable, _root=True): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 494 | """Type variable. |
| 495 | |
| 496 | Usage:: |
| 497 | |
| 498 | T = TypeVar('T') # Can be anything |
| 499 | A = TypeVar('A', str, bytes) # Must be str or bytes |
| 500 | |
| 501 | Type variables exist primarily for the benefit of static type |
| 502 | checkers. They serve as the parameters for generic types as well |
| 503 | as for generic function definitions. See class Generic for more |
| 504 | information on generic types. Generic functions work as follows: |
| 505 | |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 506 | def repeat(x: T, n: int) -> List[T]: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 507 | '''Return a list containing n references to x.''' |
| 508 | return [x]*n |
| 509 | |
| 510 | def longest(x: A, y: A) -> A: |
| 511 | '''Return the longest of two strings.''' |
| 512 | return x if len(x) >= len(y) else y |
| 513 | |
| 514 | The latter example's signature is essentially the overloading |
| 515 | of (str, str) -> str and (bytes, bytes) -> bytes. Also note |
| 516 | that if the arguments are instances of some subclass of str, |
| 517 | the return type is still plain str. |
| 518 | |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 519 | 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] | 520 | |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 521 | Type variables defined with covariant=True or contravariant=True |
| 522 | can be used do declare covariant or contravariant generic types. |
| 523 | See PEP 484 for more details. By default generic types are invariant |
| 524 | in all type variables. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 525 | |
| 526 | Type variables can be introspected. e.g.: |
| 527 | |
| 528 | T.__name__ == 'T' |
| 529 | T.__constraints__ == () |
| 530 | T.__covariant__ == False |
| 531 | T.__contravariant__ = False |
| 532 | A.__constraints__ == (str, bytes) |
Ivan Levkivskyi | 8349403 | 2018-03-26 23:01:12 +0100 | [diff] [blame] | 533 | |
| 534 | 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] | 535 | """ |
| 536 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 537 | __slots__ = ('__name__', '__bound__', '__constraints__', |
Ivan Levkivskyi | 8349403 | 2018-03-26 23:01:12 +0100 | [diff] [blame] | 538 | '__covariant__', '__contravariant__', '_def_mod') |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 539 | |
| 540 | def __init__(self, name, *constraints, bound=None, |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 541 | covariant=False, contravariant=False): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 542 | self.__name__ = name |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 543 | if covariant and contravariant: |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 544 | raise ValueError("Bivariant types are not supported.") |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 545 | self.__covariant__ = bool(covariant) |
| 546 | self.__contravariant__ = bool(contravariant) |
| 547 | if constraints and bound is not None: |
| 548 | raise TypeError("Constraints cannot be combined with bound=...") |
| 549 | if constraints and len(constraints) == 1: |
| 550 | raise TypeError("A single constraint is not allowed") |
| 551 | msg = "TypeVar(name, constraint, ...): constraints must be types." |
| 552 | self.__constraints__ = tuple(_type_check(t, msg) for t in constraints) |
| 553 | if bound: |
| 554 | self.__bound__ = _type_check(bound, "Bound must be a type.") |
| 555 | else: |
| 556 | self.__bound__ = None |
Ivan Levkivskyi | 8349403 | 2018-03-26 23:01:12 +0100 | [diff] [blame] | 557 | self._def_mod = sys._getframe(1).f_globals['__name__'] # for pickling |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 558 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 559 | def __getstate__(self): |
| 560 | return {'name': self.__name__, |
| 561 | 'bound': self.__bound__, |
| 562 | 'constraints': self.__constraints__, |
| 563 | 'co': self.__covariant__, |
| 564 | 'contra': self.__contravariant__} |
| 565 | |
| 566 | def __setstate__(self, state): |
| 567 | self.__name__ = state['name'] |
| 568 | self.__bound__ = state['bound'] |
| 569 | self.__constraints__ = state['constraints'] |
| 570 | self.__covariant__ = state['co'] |
| 571 | self.__contravariant__ = state['contra'] |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 572 | |
| 573 | def __repr__(self): |
| 574 | if self.__covariant__: |
| 575 | prefix = '+' |
| 576 | elif self.__contravariant__: |
| 577 | prefix = '-' |
| 578 | else: |
| 579 | prefix = '~' |
| 580 | return prefix + self.__name__ |
| 581 | |
Ivan Levkivskyi | 8349403 | 2018-03-26 23:01:12 +0100 | [diff] [blame] | 582 | def __reduce__(self): |
| 583 | return (_find_name, (self._def_mod, self.__name__)) |
| 584 | |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 585 | |
Guido van Rossum | 83ec302 | 2017-01-17 20:43:28 -0800 | [diff] [blame] | 586 | # Special typing constructs Union, Optional, Generic, Callable and Tuple |
| 587 | # use three special attributes for internal bookkeeping of generic types: |
| 588 | # * __parameters__ is a tuple of unique free type parameters of a generic |
| 589 | # type, for example, Dict[T, T].__parameters__ == (T,); |
| 590 | # * __origin__ keeps a reference to a type that was subscripted, |
Ivan Levkivskyi | 43d12a6 | 2018-05-09 02:23:46 +0100 | [diff] [blame] | 591 | # e.g., Union[T, int].__origin__ == Union, or the non-generic version of |
| 592 | # the type. |
Guido van Rossum | 83ec302 | 2017-01-17 20:43:28 -0800 | [diff] [blame] | 593 | # * __args__ is a tuple of all arguments used in subscripting, |
| 594 | # e.g., Dict[T, int].__args__ == (T, int). |
| 595 | |
Ivan Levkivskyi | 2a363d2 | 2018-04-05 01:25:15 +0100 | [diff] [blame] | 596 | |
| 597 | # Mapping from non-generic type names that have a generic alias in typing |
| 598 | # but with a different name. |
| 599 | _normalize_alias = {'list': 'List', |
| 600 | 'tuple': 'Tuple', |
| 601 | 'dict': 'Dict', |
| 602 | 'set': 'Set', |
| 603 | 'frozenset': 'FrozenSet', |
| 604 | 'deque': 'Deque', |
| 605 | 'defaultdict': 'DefaultDict', |
| 606 | 'type': 'Type', |
| 607 | 'Set': 'AbstractSet'} |
| 608 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 609 | def _is_dunder(attr): |
| 610 | return attr.startswith('__') and attr.endswith('__') |
Guido van Rossum | 83ec302 | 2017-01-17 20:43:28 -0800 | [diff] [blame] | 611 | |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 612 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 613 | class _GenericAlias(_Final, _root=True): |
| 614 | """The central part of internal API. |
| 615 | |
| 616 | This represents a generic version of type 'origin' with type arguments 'params'. |
| 617 | There are two kind of these aliases: user defined and special. The special ones |
| 618 | are wrappers around builtin collections and ABCs in collections.abc. These must |
| 619 | have 'name' always set. If 'inst' is False, then the alias can't be instantiated, |
| 620 | this is used by e.g. typing.List and typing.Dict. |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 621 | """ |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 622 | def __init__(self, origin, params, *, inst=True, special=False, name=None): |
| 623 | self._inst = inst |
| 624 | self._special = special |
| 625 | if special and name is None: |
| 626 | orig_name = origin.__name__ |
Ivan Levkivskyi | 2a363d2 | 2018-04-05 01:25:15 +0100 | [diff] [blame] | 627 | name = _normalize_alias.get(orig_name, orig_name) |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 628 | self._name = name |
| 629 | if not isinstance(params, tuple): |
| 630 | params = (params,) |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 631 | self.__origin__ = origin |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 632 | self.__args__ = tuple(... if a is _TypingEllipsis else |
| 633 | () if a is _TypingEmpty else |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 634 | a for a in params) |
| 635 | self.__parameters__ = _collect_type_vars(params) |
| 636 | self.__slots__ = None # This is not documented. |
| 637 | if not name: |
| 638 | self.__module__ = origin.__module__ |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 639 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 640 | @_tp_cache |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 641 | def __getitem__(self, params): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 642 | if self.__origin__ in (Generic, _Protocol): |
| 643 | # Can't subscript Generic[...] or _Protocol[...]. |
| 644 | raise TypeError(f"Cannot subscript already-subscripted {self}") |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 645 | if not isinstance(params, tuple): |
| 646 | params = (params,) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 647 | msg = "Parameters to generic types must be types." |
| 648 | params = tuple(_type_check(p, msg) for p in params) |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 649 | _check_generic(self, params) |
| 650 | return _subs_tvars(self, self.__parameters__, params) |
Ivan Levkivskyi | b692dc8 | 2017-02-13 22:50:14 +0100 | [diff] [blame] | 651 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 652 | def copy_with(self, params): |
| 653 | # We don't copy self._special. |
| 654 | return _GenericAlias(self.__origin__, params, name=self._name, inst=self._inst) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 655 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 656 | def __repr__(self): |
| 657 | if (self._name != 'Callable' or |
| 658 | len(self.__args__) == 2 and self.__args__[0] is Ellipsis): |
| 659 | if self._name: |
| 660 | name = 'typing.' + self._name |
| 661 | else: |
| 662 | name = _type_repr(self.__origin__) |
| 663 | if not self._special: |
| 664 | args = f'[{", ".join([_type_repr(a) for a in self.__args__])}]' |
| 665 | else: |
| 666 | args = '' |
| 667 | return (f'{name}{args}') |
| 668 | if self._special: |
| 669 | return 'typing.Callable' |
| 670 | return (f'typing.Callable' |
| 671 | f'[[{", ".join([_type_repr(a) for a in self.__args__[:-1]])}], ' |
| 672 | f'{_type_repr(self.__args__[-1])}]') |
| 673 | |
| 674 | def __eq__(self, other): |
| 675 | if not isinstance(other, _GenericAlias): |
| 676 | return NotImplemented |
| 677 | if self.__origin__ != other.__origin__: |
Ivan Levkivskyi | b692dc8 | 2017-02-13 22:50:14 +0100 | [diff] [blame] | 678 | return False |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 679 | if self.__origin__ is Union and other.__origin__ is Union: |
| 680 | return frozenset(self.__args__) == frozenset(other.__args__) |
| 681 | return self.__args__ == other.__args__ |
Ivan Levkivskyi | b692dc8 | 2017-02-13 22:50:14 +0100 | [diff] [blame] | 682 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 683 | def __hash__(self): |
| 684 | if self.__origin__ is Union: |
| 685 | return hash((Union, frozenset(self.__args__))) |
| 686 | return hash((self.__origin__, self.__args__)) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 687 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 688 | def __call__(self, *args, **kwargs): |
| 689 | if not self._inst: |
| 690 | raise TypeError(f"Type {self._name} cannot be instantiated; " |
| 691 | f"use {self._name.lower()}() instead") |
| 692 | result = self.__origin__(*args, **kwargs) |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 693 | try: |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 694 | result.__orig_class__ = self |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 695 | except AttributeError: |
| 696 | pass |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 697 | return result |
| 698 | |
| 699 | def __mro_entries__(self, bases): |
| 700 | if self._name: # generic version of an ABC or built-in class |
| 701 | res = [] |
| 702 | if self.__origin__ not in bases: |
| 703 | res.append(self.__origin__) |
| 704 | i = bases.index(self) |
| 705 | if not any(isinstance(b, _GenericAlias) or issubclass(b, Generic) |
| 706 | for b in bases[i+1:]): |
| 707 | res.append(Generic) |
| 708 | return tuple(res) |
| 709 | if self.__origin__ is Generic: |
| 710 | i = bases.index(self) |
| 711 | for b in bases[i+1:]: |
| 712 | if isinstance(b, _GenericAlias) and b is not self: |
| 713 | return () |
| 714 | return (self.__origin__,) |
| 715 | |
| 716 | def __getattr__(self, attr): |
Ville Skyttä | 61f82e0 | 2018-04-20 23:08:45 +0300 | [diff] [blame] | 717 | # We are careful for copy and pickle. |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 718 | # Also for simplicity we just don't relay all dunder names |
| 719 | if '__origin__' in self.__dict__ and not _is_dunder(attr): |
| 720 | return getattr(self.__origin__, attr) |
| 721 | raise AttributeError(attr) |
| 722 | |
| 723 | def __setattr__(self, attr, val): |
| 724 | if _is_dunder(attr) or attr in ('_name', '_inst', '_special'): |
| 725 | super().__setattr__(attr, val) |
| 726 | else: |
| 727 | setattr(self.__origin__, attr, val) |
| 728 | |
| 729 | def __instancecheck__(self, obj): |
| 730 | return self.__subclasscheck__(type(obj)) |
| 731 | |
| 732 | def __subclasscheck__(self, cls): |
| 733 | if self._special: |
| 734 | if not isinstance(cls, _GenericAlias): |
| 735 | return issubclass(cls, self.__origin__) |
| 736 | if cls._special: |
| 737 | return issubclass(cls.__origin__, self.__origin__) |
| 738 | raise TypeError("Subscripted generics cannot be used with" |
| 739 | " class and instance checks") |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 740 | |
Ivan Levkivskyi | 8349403 | 2018-03-26 23:01:12 +0100 | [diff] [blame] | 741 | def __reduce__(self): |
| 742 | if self._special: |
| 743 | return self._name |
| 744 | return super().__reduce__() |
| 745 | |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 746 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 747 | class _VariadicGenericAlias(_GenericAlias, _root=True): |
| 748 | """Same as _GenericAlias above but for variadic aliases. Currently, |
| 749 | this is used only by special internal aliases: Tuple and Callable. |
| 750 | """ |
| 751 | def __getitem__(self, params): |
| 752 | if self._name != 'Callable' or not self._special: |
| 753 | return self.__getitem_inner__(params) |
| 754 | if not isinstance(params, tuple) or len(params) != 2: |
| 755 | raise TypeError("Callable must be used as " |
| 756 | "Callable[[arg, ...], result].") |
| 757 | args, result = params |
| 758 | if args is Ellipsis: |
| 759 | params = (Ellipsis, result) |
| 760 | else: |
| 761 | if not isinstance(args, list): |
| 762 | raise TypeError(f"Callable[args, result]: args must be a list." |
| 763 | f" Got {args}") |
| 764 | params = (tuple(args), result) |
| 765 | return self.__getitem_inner__(params) |
| 766 | |
| 767 | @_tp_cache |
| 768 | def __getitem_inner__(self, params): |
| 769 | if self.__origin__ is tuple and self._special: |
| 770 | if params == (): |
| 771 | return self.copy_with((_TypingEmpty,)) |
| 772 | if not isinstance(params, tuple): |
| 773 | params = (params,) |
| 774 | if len(params) == 2 and params[1] is ...: |
| 775 | msg = "Tuple[t, ...]: t must be a type." |
| 776 | p = _type_check(params[0], msg) |
| 777 | return self.copy_with((p, _TypingEllipsis)) |
| 778 | msg = "Tuple[t0, t1, ...]: each t must be a type." |
| 779 | params = tuple(_type_check(p, msg) for p in params) |
| 780 | return self.copy_with(params) |
| 781 | if self.__origin__ is collections.abc.Callable and self._special: |
| 782 | args, result = params |
| 783 | msg = "Callable[args, result]: result must be a type." |
| 784 | result = _type_check(result, msg) |
| 785 | if args is Ellipsis: |
| 786 | return self.copy_with((_TypingEllipsis, result)) |
| 787 | msg = "Callable[[arg, ...], result]: each arg must be a type." |
| 788 | args = tuple(_type_check(arg, msg) for arg in args) |
| 789 | params = args + (result,) |
| 790 | return self.copy_with(params) |
| 791 | return super().__getitem__(params) |
| 792 | |
| 793 | |
| 794 | class Generic: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 795 | """Abstract base class for generic types. |
| 796 | |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 797 | A generic type is typically declared by inheriting from |
| 798 | this class parameterized with one or more type variables. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 799 | For example, a generic mapping type might be defined as:: |
| 800 | |
| 801 | class Mapping(Generic[KT, VT]): |
| 802 | def __getitem__(self, key: KT) -> VT: |
| 803 | ... |
| 804 | # Etc. |
| 805 | |
| 806 | This class can then be used as follows:: |
| 807 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 808 | 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] | 809 | try: |
| 810 | return mapping[key] |
| 811 | except KeyError: |
| 812 | return default |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 813 | """ |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 814 | __slots__ = () |
| 815 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 816 | def __new__(cls, *args, **kwds): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 817 | if cls is Generic: |
Guido van Rossum | 62fe1bb | 2016-10-29 16:05:26 -0700 | [diff] [blame] | 818 | raise TypeError("Type Generic cannot be instantiated; " |
| 819 | "it can be used only as a base class") |
Ivan Levkivskyi | b551e9f | 2018-05-10 23:10:10 -0400 | [diff] [blame] | 820 | 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] | 821 | obj = super().__new__(cls) |
| 822 | else: |
| 823 | obj = super().__new__(cls, *args, **kwds) |
| 824 | return obj |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 825 | |
| 826 | @_tp_cache |
| 827 | def __class_getitem__(cls, params): |
| 828 | if not isinstance(params, tuple): |
| 829 | params = (params,) |
| 830 | if not params and cls is not Tuple: |
| 831 | raise TypeError( |
| 832 | f"Parameter list to {cls.__qualname__}[...] cannot be empty") |
| 833 | msg = "Parameters to generic types must be types." |
| 834 | params = tuple(_type_check(p, msg) for p in params) |
| 835 | if cls is Generic: |
| 836 | # Generic can only be subscripted with unique type variables. |
| 837 | if not all(isinstance(p, TypeVar) for p in params): |
| 838 | raise TypeError( |
| 839 | "Parameters to Generic[...] must all be type variables") |
| 840 | if len(set(params)) != len(params): |
| 841 | raise TypeError( |
| 842 | "Parameters to Generic[...] must all be unique") |
| 843 | elif cls is _Protocol: |
| 844 | # _Protocol is internal at the moment, just skip the check |
| 845 | pass |
| 846 | else: |
| 847 | # Subscripting a regular Generic subclass. |
| 848 | _check_generic(cls, params) |
| 849 | return _GenericAlias(cls, params) |
| 850 | |
| 851 | def __init_subclass__(cls, *args, **kwargs): |
Ivan Levkivskyi | ee566fe | 2018-04-04 17:00:15 +0100 | [diff] [blame] | 852 | super().__init_subclass__(*args, **kwargs) |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 853 | tvars = [] |
| 854 | if '__orig_bases__' in cls.__dict__: |
| 855 | error = Generic in cls.__orig_bases__ |
| 856 | else: |
| 857 | error = Generic in cls.__bases__ and cls.__name__ != '_Protocol' |
| 858 | if error: |
| 859 | raise TypeError("Cannot inherit from plain Generic") |
| 860 | if '__orig_bases__' in cls.__dict__: |
| 861 | tvars = _collect_type_vars(cls.__orig_bases__) |
| 862 | # Look for Generic[T1, ..., Tn]. |
| 863 | # If found, tvars must be a subset of it. |
| 864 | # If not found, tvars is it. |
| 865 | # Also check for and reject plain Generic, |
| 866 | # and reject multiple Generic[...]. |
| 867 | gvars = None |
| 868 | for base in cls.__orig_bases__: |
| 869 | if (isinstance(base, _GenericAlias) and |
| 870 | base.__origin__ is Generic): |
| 871 | if gvars is not None: |
| 872 | raise TypeError( |
| 873 | "Cannot inherit from Generic[...] multiple types.") |
| 874 | gvars = base.__parameters__ |
| 875 | if gvars is None: |
| 876 | gvars = tvars |
| 877 | else: |
| 878 | tvarset = set(tvars) |
| 879 | gvarset = set(gvars) |
| 880 | if not tvarset <= gvarset: |
| 881 | s_vars = ', '.join(str(t) for t in tvars if t not in gvarset) |
| 882 | s_args = ', '.join(str(g) for g in gvars) |
| 883 | raise TypeError(f"Some type variables ({s_vars}) are" |
| 884 | f" not listed in Generic[{s_args}]") |
| 885 | tvars = gvars |
| 886 | cls.__parameters__ = tuple(tvars) |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 887 | |
| 888 | |
| 889 | class _TypingEmpty: |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 890 | """Internal placeholder for () or []. Used by TupleMeta and CallableMeta |
| 891 | to allow empty list/tuple in specific places, without allowing them |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 892 | to sneak in where prohibited. |
| 893 | """ |
| 894 | |
| 895 | |
| 896 | class _TypingEllipsis: |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 897 | """Internal placeholder for ... (ellipsis).""" |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 898 | |
| 899 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 900 | def cast(typ, val): |
| 901 | """Cast a value to a type. |
| 902 | |
| 903 | This returns the value unchanged. To the type checker this |
| 904 | signals that the return value has the designated type, but at |
| 905 | runtime we intentionally don't check anything (we want this |
| 906 | to be as fast as possible). |
| 907 | """ |
| 908 | return val |
| 909 | |
| 910 | |
| 911 | def _get_defaults(func): |
| 912 | """Internal helper to extract the default arguments, by name.""" |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 913 | try: |
| 914 | code = func.__code__ |
| 915 | except AttributeError: |
| 916 | # Some built-in functions don't have __code__, __defaults__, etc. |
| 917 | return {} |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 918 | pos_count = code.co_argcount |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 919 | arg_names = code.co_varnames |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 920 | arg_names = arg_names[:pos_count] |
| 921 | defaults = func.__defaults__ or () |
| 922 | kwdefaults = func.__kwdefaults__ |
| 923 | res = dict(kwdefaults) if kwdefaults else {} |
| 924 | pos_offset = pos_count - len(defaults) |
| 925 | for name, value in zip(arg_names[pos_offset:], defaults): |
| 926 | assert name not in res |
| 927 | res[name] = value |
| 928 | return res |
| 929 | |
| 930 | |
Ivan Levkivskyi | b692dc8 | 2017-02-13 22:50:14 +0100 | [diff] [blame] | 931 | _allowed_types = (types.FunctionType, types.BuiltinFunctionType, |
| 932 | types.MethodType, types.ModuleType, |
Ivan Levkivskyi | f06e021 | 2017-05-02 19:14:07 +0200 | [diff] [blame] | 933 | WrapperDescriptorType, MethodWrapperType, MethodDescriptorType) |
Ivan Levkivskyi | b692dc8 | 2017-02-13 22:50:14 +0100 | [diff] [blame] | 934 | |
| 935 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 936 | def get_type_hints(obj, globalns=None, localns=None): |
| 937 | """Return type hints for an object. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 938 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 939 | This is often the same as obj.__annotations__, but it handles |
| 940 | forward references encoded as string literals, and if necessary |
| 941 | adds Optional[t] if a default value equal to None is set. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 942 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 943 | The argument may be a module, class, method, or function. The annotations |
| 944 | are returned as a dictionary. For classes, annotations include also |
| 945 | inherited members. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 946 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 947 | TypeError is raised if the argument is not of a type that can contain |
| 948 | annotations, and an empty dictionary is returned if no annotations are |
| 949 | present. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 950 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 951 | BEWARE -- the behavior of globalns and localns is counterintuitive |
| 952 | (unless you are familiar with how eval() and exec() work). The |
| 953 | search order is locals first, then globals. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 954 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 955 | - 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] | 956 | globals from obj (or the respective module's globals for classes), |
| 957 | and these are also used as the locals. If the object does not appear |
| 958 | to have globals, an empty dictionary is used. |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 959 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 960 | - If one dict argument is passed, it is used for both globals and |
| 961 | locals. |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 962 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 963 | - If two dict arguments are passed, they specify globals and |
| 964 | locals, respectively. |
| 965 | """ |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 966 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 967 | if getattr(obj, '__no_type_check__', None): |
| 968 | return {} |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 969 | # Classes require a special treatment. |
| 970 | if isinstance(obj, type): |
| 971 | hints = {} |
| 972 | for base in reversed(obj.__mro__): |
Łukasz Langa | f350a26 | 2017-09-14 14:33:00 -0400 | [diff] [blame] | 973 | if globalns is None: |
| 974 | base_globals = sys.modules[base.__module__].__dict__ |
| 975 | else: |
| 976 | base_globals = globalns |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 977 | ann = base.__dict__.get('__annotations__', {}) |
| 978 | for name, value in ann.items(): |
| 979 | if value is None: |
| 980 | value = type(None) |
| 981 | if isinstance(value, str): |
Nina Zakharenko | 2d2d3b1 | 2018-05-16 12:27:03 -0400 | [diff] [blame] | 982 | value = ForwardRef(value, is_argument=True) |
Łukasz Langa | f350a26 | 2017-09-14 14:33:00 -0400 | [diff] [blame] | 983 | value = _eval_type(value, base_globals, localns) |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 984 | hints[name] = value |
| 985 | return hints |
Łukasz Langa | f350a26 | 2017-09-14 14:33:00 -0400 | [diff] [blame] | 986 | |
| 987 | if globalns is None: |
| 988 | if isinstance(obj, types.ModuleType): |
| 989 | globalns = obj.__dict__ |
| 990 | else: |
| 991 | globalns = getattr(obj, '__globals__', {}) |
| 992 | if localns is None: |
| 993 | localns = globalns |
| 994 | elif localns is None: |
| 995 | localns = globalns |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 996 | hints = getattr(obj, '__annotations__', None) |
| 997 | if hints is None: |
| 998 | # Return empty annotations for something that _could_ have them. |
Ivan Levkivskyi | b692dc8 | 2017-02-13 22:50:14 +0100 | [diff] [blame] | 999 | if isinstance(obj, _allowed_types): |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1000 | return {} |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1001 | else: |
| 1002 | raise TypeError('{!r} is not a module, class, method, ' |
| 1003 | 'or function.'.format(obj)) |
| 1004 | defaults = _get_defaults(obj) |
| 1005 | hints = dict(hints) |
| 1006 | for name, value in hints.items(): |
| 1007 | if value is None: |
| 1008 | value = type(None) |
| 1009 | if isinstance(value, str): |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1010 | value = ForwardRef(value) |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1011 | value = _eval_type(value, globalns, localns) |
| 1012 | if name in defaults and defaults[name] is None: |
| 1013 | value = Optional[value] |
| 1014 | hints[name] = value |
| 1015 | return hints |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1016 | |
| 1017 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1018 | def no_type_check(arg): |
| 1019 | """Decorator to indicate that annotations are not type hints. |
| 1020 | |
| 1021 | 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] | 1022 | applies recursively to all methods and classes defined in that class |
| 1023 | (but not to methods defined in its superclasses or subclasses). |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1024 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1025 | This mutates the function(s) or class(es) in place. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1026 | """ |
| 1027 | if isinstance(arg, type): |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1028 | arg_attrs = arg.__dict__.copy() |
| 1029 | for attr, val in arg.__dict__.items(): |
Ivan Levkivskyi | 65bc620 | 2017-09-14 01:25:15 +0200 | [diff] [blame] | 1030 | if val in arg.__bases__ + (arg,): |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1031 | arg_attrs.pop(attr) |
| 1032 | for obj in arg_attrs.values(): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1033 | if isinstance(obj, types.FunctionType): |
| 1034 | obj.__no_type_check__ = True |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1035 | if isinstance(obj, type): |
| 1036 | no_type_check(obj) |
| 1037 | try: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1038 | arg.__no_type_check__ = True |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 1039 | except TypeError: # built-in classes |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1040 | pass |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1041 | return arg |
| 1042 | |
| 1043 | |
| 1044 | def no_type_check_decorator(decorator): |
| 1045 | """Decorator to give another decorator the @no_type_check effect. |
| 1046 | |
| 1047 | This wraps the decorator with something that wraps the decorated |
| 1048 | function in @no_type_check. |
| 1049 | """ |
| 1050 | |
| 1051 | @functools.wraps(decorator) |
| 1052 | def wrapped_decorator(*args, **kwds): |
| 1053 | func = decorator(*args, **kwds) |
| 1054 | func = no_type_check(func) |
| 1055 | return func |
| 1056 | |
| 1057 | return wrapped_decorator |
| 1058 | |
| 1059 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1060 | def _overload_dummy(*args, **kwds): |
| 1061 | """Helper for @overload to raise when called.""" |
| 1062 | raise NotImplementedError( |
| 1063 | "You should not call an overloaded function. " |
| 1064 | "A series of @overload-decorated functions " |
| 1065 | "outside a stub module should always be followed " |
| 1066 | "by an implementation that is not @overload-ed.") |
| 1067 | |
| 1068 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1069 | def overload(func): |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1070 | """Decorator for overloaded functions/methods. |
| 1071 | |
| 1072 | In a stub file, place two or more stub definitions for the same |
| 1073 | function in a row, each decorated with @overload. For example: |
| 1074 | |
| 1075 | @overload |
| 1076 | def utf8(value: None) -> None: ... |
| 1077 | @overload |
| 1078 | def utf8(value: bytes) -> bytes: ... |
| 1079 | @overload |
| 1080 | def utf8(value: str) -> bytes: ... |
| 1081 | |
| 1082 | In a non-stub file (i.e. a regular .py file), do the same but |
| 1083 | follow it with an implementation. The implementation should *not* |
| 1084 | be decorated with @overload. For example: |
| 1085 | |
| 1086 | @overload |
| 1087 | def utf8(value: None) -> None: ... |
| 1088 | @overload |
| 1089 | def utf8(value: bytes) -> bytes: ... |
| 1090 | @overload |
| 1091 | def utf8(value: str) -> bytes: ... |
| 1092 | def utf8(value): |
| 1093 | # implementation goes here |
| 1094 | """ |
| 1095 | return _overload_dummy |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1096 | |
| 1097 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1098 | class _ProtocolMeta(type): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1099 | """Internal metaclass for _Protocol. |
| 1100 | |
| 1101 | This exists so _Protocol classes can be generic without deriving |
| 1102 | from Generic. |
| 1103 | """ |
| 1104 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1105 | def __instancecheck__(self, obj): |
Guido van Rossum | ca4b252 | 2016-11-19 10:32:41 -0800 | [diff] [blame] | 1106 | if _Protocol not in self.__bases__: |
| 1107 | return super().__instancecheck__(obj) |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1108 | raise TypeError("Protocols cannot be used with isinstance().") |
| 1109 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1110 | def __subclasscheck__(self, cls): |
| 1111 | if not self._is_protocol: |
| 1112 | # No structural checks since this isn't a protocol. |
| 1113 | return NotImplemented |
| 1114 | |
| 1115 | if self is _Protocol: |
| 1116 | # Every class is a subclass of the empty protocol. |
| 1117 | return True |
| 1118 | |
| 1119 | # Find all attributes defined in the protocol. |
| 1120 | attrs = self._get_protocol_attrs() |
| 1121 | |
| 1122 | for attr in attrs: |
| 1123 | if not any(attr in d.__dict__ for d in cls.__mro__): |
| 1124 | return False |
| 1125 | return True |
| 1126 | |
| 1127 | def _get_protocol_attrs(self): |
| 1128 | # Get all Protocol base classes. |
| 1129 | protocol_bases = [] |
| 1130 | for c in self.__mro__: |
| 1131 | if getattr(c, '_is_protocol', False) and c.__name__ != '_Protocol': |
| 1132 | protocol_bases.append(c) |
| 1133 | |
| 1134 | # Get attributes included in protocol. |
| 1135 | attrs = set() |
| 1136 | for base in protocol_bases: |
| 1137 | for attr in base.__dict__.keys(): |
| 1138 | # Include attributes not defined in any non-protocol bases. |
| 1139 | for c in self.__mro__: |
| 1140 | if (c is not base and attr in c.__dict__ and |
| 1141 | not getattr(c, '_is_protocol', False)): |
| 1142 | break |
| 1143 | else: |
| 1144 | if (not attr.startswith('_abc_') and |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1145 | attr != '__abstractmethods__' and |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1146 | attr != '__annotations__' and |
| 1147 | attr != '__weakref__' and |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1148 | attr != '_is_protocol' and |
Ivan Levkivskyi | 65bc620 | 2017-09-14 01:25:15 +0200 | [diff] [blame] | 1149 | attr != '_gorg' and |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1150 | attr != '__dict__' and |
| 1151 | attr != '__args__' and |
| 1152 | attr != '__slots__' and |
| 1153 | attr != '_get_protocol_attrs' and |
| 1154 | attr != '__next_in_mro__' and |
| 1155 | attr != '__parameters__' and |
| 1156 | attr != '__origin__' and |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 1157 | attr != '__orig_bases__' and |
Guido van Rossum | 1cea70f | 2016-05-18 08:35:00 -0700 | [diff] [blame] | 1158 | attr != '__extra__' and |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1159 | attr != '__tree_hash__' and |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1160 | attr != '__module__'): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1161 | attrs.add(attr) |
| 1162 | |
| 1163 | return attrs |
| 1164 | |
| 1165 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1166 | class _Protocol(Generic, metaclass=_ProtocolMeta): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1167 | """Internal base class for protocol classes. |
| 1168 | |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 1169 | This implements a simple-minded structural issubclass check |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1170 | (similar but more general than the one-offs in collections.abc |
| 1171 | such as Hashable). |
| 1172 | """ |
| 1173 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1174 | __slots__ = () |
| 1175 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1176 | _is_protocol = True |
| 1177 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1178 | def __class_getitem__(cls, params): |
| 1179 | return super().__class_getitem__(params) |
| 1180 | |
| 1181 | |
| 1182 | # Some unconstrained type variables. These are used by the container types. |
| 1183 | # (These are not for export.) |
| 1184 | T = TypeVar('T') # Any type. |
| 1185 | KT = TypeVar('KT') # Key type. |
| 1186 | VT = TypeVar('VT') # Value type. |
| 1187 | T_co = TypeVar('T_co', covariant=True) # Any type covariant containers. |
| 1188 | V_co = TypeVar('V_co', covariant=True) # Any type covariant containers. |
| 1189 | VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers. |
| 1190 | T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant. |
| 1191 | # Internal type variable used for Type[]. |
| 1192 | CT_co = TypeVar('CT_co', covariant=True, bound=type) |
| 1193 | |
| 1194 | # A useful type variable with constraints. This represents string types. |
| 1195 | # (This one *is* for export!) |
| 1196 | AnyStr = TypeVar('AnyStr', bytes, str) |
| 1197 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1198 | |
| 1199 | # Various ABCs mimicking those in collections.abc. |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1200 | def _alias(origin, params, inst=True): |
| 1201 | return _GenericAlias(origin, params, special=True, inst=inst) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1202 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1203 | Hashable = _alias(collections.abc.Hashable, ()) # Not generic. |
| 1204 | Awaitable = _alias(collections.abc.Awaitable, T_co) |
| 1205 | Coroutine = _alias(collections.abc.Coroutine, (T_co, T_contra, V_co)) |
| 1206 | AsyncIterable = _alias(collections.abc.AsyncIterable, T_co) |
| 1207 | AsyncIterator = _alias(collections.abc.AsyncIterator, T_co) |
| 1208 | Iterable = _alias(collections.abc.Iterable, T_co) |
| 1209 | Iterator = _alias(collections.abc.Iterator, T_co) |
| 1210 | Reversible = _alias(collections.abc.Reversible, T_co) |
| 1211 | Sized = _alias(collections.abc.Sized, ()) # Not generic. |
| 1212 | Container = _alias(collections.abc.Container, T_co) |
| 1213 | Collection = _alias(collections.abc.Collection, T_co) |
| 1214 | Callable = _VariadicGenericAlias(collections.abc.Callable, (), special=True) |
| 1215 | Callable.__doc__ = \ |
| 1216 | """Callable type; Callable[[int], str] is a function of (int) -> str. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1217 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1218 | The subscription syntax must always be used with exactly two |
| 1219 | values: the argument list and the return type. The argument list |
| 1220 | 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] | 1221 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1222 | There is no syntax to indicate optional or keyword arguments, |
| 1223 | such function types are rarely used as callback types. |
| 1224 | """ |
| 1225 | AbstractSet = _alias(collections.abc.Set, T_co) |
| 1226 | MutableSet = _alias(collections.abc.MutableSet, T) |
| 1227 | # NOTE: Mapping is only covariant in the value type. |
| 1228 | Mapping = _alias(collections.abc.Mapping, (KT, VT_co)) |
| 1229 | MutableMapping = _alias(collections.abc.MutableMapping, (KT, VT)) |
| 1230 | Sequence = _alias(collections.abc.Sequence, T_co) |
| 1231 | MutableSequence = _alias(collections.abc.MutableSequence, T) |
| 1232 | ByteString = _alias(collections.abc.ByteString, ()) # Not generic |
| 1233 | Tuple = _VariadicGenericAlias(tuple, (), inst=False, special=True) |
| 1234 | Tuple.__doc__ = \ |
| 1235 | """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] | 1236 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1237 | Example: Tuple[T1, T2] is a tuple of two elements corresponding |
| 1238 | to type variables T1 and T2. Tuple[int, float, str] is a tuple |
| 1239 | of an int, a float and a string. |
Guido van Rossum | 62fe1bb | 2016-10-29 16:05:26 -0700 | [diff] [blame] | 1240 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1241 | To specify a variable-length tuple of homogeneous type, use Tuple[T, ...]. |
| 1242 | """ |
| 1243 | List = _alias(list, T, inst=False) |
| 1244 | Deque = _alias(collections.deque, T) |
| 1245 | Set = _alias(set, T, inst=False) |
| 1246 | FrozenSet = _alias(frozenset, T_co, inst=False) |
| 1247 | MappingView = _alias(collections.abc.MappingView, T_co) |
| 1248 | KeysView = _alias(collections.abc.KeysView, KT) |
| 1249 | ItemsView = _alias(collections.abc.ItemsView, (KT, VT_co)) |
| 1250 | ValuesView = _alias(collections.abc.ValuesView, VT_co) |
| 1251 | ContextManager = _alias(contextlib.AbstractContextManager, T_co) |
| 1252 | AsyncContextManager = _alias(contextlib.AbstractAsyncContextManager, T_co) |
| 1253 | Dict = _alias(dict, (KT, VT), inst=False) |
| 1254 | DefaultDict = _alias(collections.defaultdict, (KT, VT)) |
| 1255 | Counter = _alias(collections.Counter, T) |
| 1256 | ChainMap = _alias(collections.ChainMap, (KT, VT)) |
| 1257 | Generator = _alias(collections.abc.Generator, (T_co, T_contra, V_co)) |
| 1258 | AsyncGenerator = _alias(collections.abc.AsyncGenerator, (T_co, T_contra)) |
| 1259 | Type = _alias(type, CT_co, inst=False) |
| 1260 | Type.__doc__ = \ |
| 1261 | """A special construct usable to annotate class objects. |
Guido van Rossum | 62fe1bb | 2016-10-29 16:05:26 -0700 | [diff] [blame] | 1262 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1263 | For example, suppose we have the following classes:: |
Guido van Rossum | 62fe1bb | 2016-10-29 16:05:26 -0700 | [diff] [blame] | 1264 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1265 | class User: ... # Abstract base for User classes |
| 1266 | class BasicUser(User): ... |
| 1267 | class ProUser(User): ... |
| 1268 | class TeamUser(User): ... |
Guido van Rossum | f17c200 | 2015-12-03 17:31:24 -0800 | [diff] [blame] | 1269 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1270 | And a function that takes a class argument that's a subclass of |
| 1271 | User and returns an instance of the corresponding class:: |
Guido van Rossum | f17c200 | 2015-12-03 17:31:24 -0800 | [diff] [blame] | 1272 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1273 | U = TypeVar('U', bound=User) |
| 1274 | def new_user(user_class: Type[U]) -> U: |
| 1275 | user = user_class() |
| 1276 | # (Here we could write the user object to a database) |
| 1277 | return user |
Guido van Rossum | f17c200 | 2015-12-03 17:31:24 -0800 | [diff] [blame] | 1278 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1279 | joe = new_user(BasicUser) |
Guido van Rossum | f17c200 | 2015-12-03 17:31:24 -0800 | [diff] [blame] | 1280 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1281 | At this point the type checker knows that joe has type BasicUser. |
| 1282 | """ |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1283 | |
| 1284 | |
| 1285 | class SupportsInt(_Protocol): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1286 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1287 | |
| 1288 | @abstractmethod |
| 1289 | def __int__(self) -> int: |
| 1290 | pass |
| 1291 | |
| 1292 | |
| 1293 | class SupportsFloat(_Protocol): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1294 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1295 | |
| 1296 | @abstractmethod |
| 1297 | def __float__(self) -> float: |
| 1298 | pass |
| 1299 | |
| 1300 | |
| 1301 | class SupportsComplex(_Protocol): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1302 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1303 | |
| 1304 | @abstractmethod |
| 1305 | def __complex__(self) -> complex: |
| 1306 | pass |
| 1307 | |
| 1308 | |
| 1309 | class SupportsBytes(_Protocol): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1310 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1311 | |
| 1312 | @abstractmethod |
| 1313 | def __bytes__(self) -> bytes: |
| 1314 | pass |
| 1315 | |
| 1316 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1317 | class SupportsAbs(_Protocol[T_co]): |
| 1318 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1319 | |
| 1320 | @abstractmethod |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1321 | def __abs__(self) -> T_co: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1322 | pass |
| 1323 | |
| 1324 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1325 | class SupportsRound(_Protocol[T_co]): |
| 1326 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1327 | |
| 1328 | @abstractmethod |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1329 | def __round__(self, ndigits: int = 0) -> T_co: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1330 | pass |
| 1331 | |
| 1332 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1333 | def _make_nmtuple(name, types): |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 1334 | msg = "NamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a type" |
| 1335 | types = [(n, _type_check(t, msg)) for n, t in types] |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1336 | nm_tpl = collections.namedtuple(name, [n for n, t in types]) |
Guido van Rossum | 83ec302 | 2017-01-17 20:43:28 -0800 | [diff] [blame] | 1337 | # Prior to PEP 526, only _field_types attribute was assigned. |
| 1338 | # Now, both __annotations__ and _field_types are used to maintain compatibility. |
| 1339 | nm_tpl.__annotations__ = nm_tpl._field_types = collections.OrderedDict(types) |
Guido van Rossum | 557d1eb | 2015-11-19 08:16:31 -0800 | [diff] [blame] | 1340 | try: |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1341 | nm_tpl.__module__ = sys._getframe(2).f_globals.get('__name__', '__main__') |
Guido van Rossum | 557d1eb | 2015-11-19 08:16:31 -0800 | [diff] [blame] | 1342 | except (AttributeError, ValueError): |
| 1343 | pass |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1344 | return nm_tpl |
| 1345 | |
| 1346 | |
Ivan Levkivskyi | b692dc8 | 2017-02-13 22:50:14 +0100 | [diff] [blame] | 1347 | # attributes prohibited to set in NamedTuple class syntax |
| 1348 | _prohibited = ('__new__', '__init__', '__slots__', '__getnewargs__', |
| 1349 | '_fields', '_field_defaults', '_field_types', |
Ivan Levkivskyi | f06e021 | 2017-05-02 19:14:07 +0200 | [diff] [blame] | 1350 | '_make', '_replace', '_asdict', '_source') |
Ivan Levkivskyi | b692dc8 | 2017-02-13 22:50:14 +0100 | [diff] [blame] | 1351 | |
| 1352 | _special = ('__module__', '__name__', '__qualname__', '__annotations__') |
| 1353 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1354 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 1355 | class NamedTupleMeta(type): |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1356 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 1357 | def __new__(cls, typename, bases, ns): |
| 1358 | if ns.get('_root', False): |
| 1359 | return super().__new__(cls, typename, bases, ns) |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 1360 | types = ns.get('__annotations__', {}) |
Guido van Rossum | 3c268be | 2017-01-18 08:03:50 -0800 | [diff] [blame] | 1361 | nm_tpl = _make_nmtuple(typename, types.items()) |
| 1362 | defaults = [] |
| 1363 | defaults_dict = {} |
| 1364 | for field_name in types: |
| 1365 | if field_name in ns: |
| 1366 | default_value = ns[field_name] |
| 1367 | defaults.append(default_value) |
| 1368 | defaults_dict[field_name] = default_value |
| 1369 | elif defaults: |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 1370 | raise TypeError("Non-default namedtuple field {field_name} cannot " |
| 1371 | "follow default field(s) {default_names}" |
Guido van Rossum | 3c268be | 2017-01-18 08:03:50 -0800 | [diff] [blame] | 1372 | .format(field_name=field_name, |
| 1373 | default_names=', '.join(defaults_dict.keys()))) |
Ivan Levkivskyi | 43d12a6 | 2018-05-09 02:23:46 +0100 | [diff] [blame] | 1374 | nm_tpl.__new__.__annotations__ = collections.OrderedDict(types) |
Guido van Rossum | 3c268be | 2017-01-18 08:03:50 -0800 | [diff] [blame] | 1375 | nm_tpl.__new__.__defaults__ = tuple(defaults) |
| 1376 | nm_tpl._field_defaults = defaults_dict |
Guido van Rossum | 95919c0 | 2017-01-22 17:47:20 -0800 | [diff] [blame] | 1377 | # update from user namespace without overriding special namedtuple attributes |
| 1378 | for key in ns: |
Ivan Levkivskyi | b692dc8 | 2017-02-13 22:50:14 +0100 | [diff] [blame] | 1379 | if key in _prohibited: |
| 1380 | raise AttributeError("Cannot overwrite NamedTuple attribute " + key) |
| 1381 | 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] | 1382 | setattr(nm_tpl, key, ns[key]) |
Guido van Rossum | 3c268be | 2017-01-18 08:03:50 -0800 | [diff] [blame] | 1383 | return nm_tpl |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1384 | |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 1385 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 1386 | class NamedTuple(metaclass=NamedTupleMeta): |
| 1387 | """Typed version of namedtuple. |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1388 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 1389 | Usage in Python versions >= 3.6:: |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1390 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 1391 | class Employee(NamedTuple): |
| 1392 | name: str |
| 1393 | id: int |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1394 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 1395 | This is equivalent to:: |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1396 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 1397 | Employee = collections.namedtuple('Employee', ['name', 'id']) |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1398 | |
Guido van Rossum | 83ec302 | 2017-01-17 20:43:28 -0800 | [diff] [blame] | 1399 | The resulting class has extra __annotations__ and _field_types |
| 1400 | attributes, giving an ordered dict mapping field names to types. |
| 1401 | __annotations__ should be preferred, while _field_types |
| 1402 | is kept to maintain pre PEP 526 compatibility. (The field names |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 1403 | are in the _fields attribute, which is part of the namedtuple |
| 1404 | API.) Alternative equivalent keyword syntax is also accepted:: |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1405 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 1406 | Employee = NamedTuple('Employee', name=str, id=int) |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1407 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 1408 | In Python versions <= 3.5 use:: |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1409 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 1410 | Employee = NamedTuple('Employee', [('name', str), ('id', int)]) |
| 1411 | """ |
| 1412 | _root = True |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1413 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 1414 | def __new__(self, typename, fields=None, **kwargs): |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 1415 | if fields is None: |
| 1416 | fields = kwargs.items() |
| 1417 | elif kwargs: |
| 1418 | raise TypeError("Either list of fields or keywords" |
| 1419 | " can be provided to NamedTuple, not both") |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1420 | return _make_nmtuple(typename, fields) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1421 | |
| 1422 | |
Guido van Rossum | 91185fe | 2016-06-08 11:19:11 -0700 | [diff] [blame] | 1423 | def NewType(name, tp): |
| 1424 | """NewType creates simple unique types with almost zero |
| 1425 | runtime overhead. NewType(name, tp) is considered a subtype of tp |
| 1426 | by static type checkers. At runtime, NewType(name, tp) returns |
| 1427 | a dummy function that simply returns its argument. Usage:: |
| 1428 | |
| 1429 | UserId = NewType('UserId', int) |
| 1430 | |
| 1431 | def name_by_id(user_id: UserId) -> str: |
| 1432 | ... |
| 1433 | |
| 1434 | UserId('user') # Fails type check |
| 1435 | |
| 1436 | name_by_id(42) # Fails type check |
| 1437 | name_by_id(UserId(42)) # OK |
| 1438 | |
| 1439 | num = UserId(5) + 1 # type: int |
| 1440 | """ |
| 1441 | |
| 1442 | def new_type(x): |
| 1443 | return x |
| 1444 | |
| 1445 | new_type.__name__ = name |
| 1446 | new_type.__supertype__ = tp |
| 1447 | return new_type |
| 1448 | |
| 1449 | |
Guido van Rossum | 0e0563c | 2016-04-05 14:54:25 -0700 | [diff] [blame] | 1450 | # Python-version-specific alias (Python 2: unicode; Python 3: str) |
| 1451 | Text = str |
| 1452 | |
| 1453 | |
Guido van Rossum | 91185fe | 2016-06-08 11:19:11 -0700 | [diff] [blame] | 1454 | # Constant that's True when type checking, but False here. |
| 1455 | TYPE_CHECKING = False |
| 1456 | |
| 1457 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1458 | class IO(Generic[AnyStr]): |
| 1459 | """Generic base class for TextIO and BinaryIO. |
| 1460 | |
| 1461 | This is an abstract, generic version of the return of open(). |
| 1462 | |
| 1463 | NOTE: This does not distinguish between the different possible |
| 1464 | classes (text vs. binary, read vs. write vs. read/write, |
| 1465 | append-only, unbuffered). The TextIO and BinaryIO subclasses |
| 1466 | below capture the distinctions between text vs. binary, which is |
| 1467 | pervasive in the interface; however we currently do not offer a |
| 1468 | way to track the other distinctions in the type system. |
| 1469 | """ |
| 1470 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1471 | __slots__ = () |
| 1472 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1473 | @abstractproperty |
| 1474 | def mode(self) -> str: |
| 1475 | pass |
| 1476 | |
| 1477 | @abstractproperty |
| 1478 | def name(self) -> str: |
| 1479 | pass |
| 1480 | |
| 1481 | @abstractmethod |
| 1482 | def close(self) -> None: |
| 1483 | pass |
| 1484 | |
| 1485 | @abstractmethod |
| 1486 | def closed(self) -> bool: |
| 1487 | pass |
| 1488 | |
| 1489 | @abstractmethod |
| 1490 | def fileno(self) -> int: |
| 1491 | pass |
| 1492 | |
| 1493 | @abstractmethod |
| 1494 | def flush(self) -> None: |
| 1495 | pass |
| 1496 | |
| 1497 | @abstractmethod |
| 1498 | def isatty(self) -> bool: |
| 1499 | pass |
| 1500 | |
| 1501 | @abstractmethod |
| 1502 | def read(self, n: int = -1) -> AnyStr: |
| 1503 | pass |
| 1504 | |
| 1505 | @abstractmethod |
| 1506 | def readable(self) -> bool: |
| 1507 | pass |
| 1508 | |
| 1509 | @abstractmethod |
| 1510 | def readline(self, limit: int = -1) -> AnyStr: |
| 1511 | pass |
| 1512 | |
| 1513 | @abstractmethod |
| 1514 | def readlines(self, hint: int = -1) -> List[AnyStr]: |
| 1515 | pass |
| 1516 | |
| 1517 | @abstractmethod |
| 1518 | def seek(self, offset: int, whence: int = 0) -> int: |
| 1519 | pass |
| 1520 | |
| 1521 | @abstractmethod |
| 1522 | def seekable(self) -> bool: |
| 1523 | pass |
| 1524 | |
| 1525 | @abstractmethod |
| 1526 | def tell(self) -> int: |
| 1527 | pass |
| 1528 | |
| 1529 | @abstractmethod |
| 1530 | def truncate(self, size: int = None) -> int: |
| 1531 | pass |
| 1532 | |
| 1533 | @abstractmethod |
| 1534 | def writable(self) -> bool: |
| 1535 | pass |
| 1536 | |
| 1537 | @abstractmethod |
| 1538 | def write(self, s: AnyStr) -> int: |
| 1539 | pass |
| 1540 | |
| 1541 | @abstractmethod |
| 1542 | def writelines(self, lines: List[AnyStr]) -> None: |
| 1543 | pass |
| 1544 | |
| 1545 | @abstractmethod |
| 1546 | def __enter__(self) -> 'IO[AnyStr]': |
| 1547 | pass |
| 1548 | |
| 1549 | @abstractmethod |
| 1550 | def __exit__(self, type, value, traceback) -> None: |
| 1551 | pass |
| 1552 | |
| 1553 | |
| 1554 | class BinaryIO(IO[bytes]): |
| 1555 | """Typed version of the return of open() in binary mode.""" |
| 1556 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1557 | __slots__ = () |
| 1558 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1559 | @abstractmethod |
| 1560 | def write(self, s: Union[bytes, bytearray]) -> int: |
| 1561 | pass |
| 1562 | |
| 1563 | @abstractmethod |
| 1564 | def __enter__(self) -> 'BinaryIO': |
| 1565 | pass |
| 1566 | |
| 1567 | |
| 1568 | class TextIO(IO[str]): |
| 1569 | """Typed version of the return of open() in text mode.""" |
| 1570 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1571 | __slots__ = () |
| 1572 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1573 | @abstractproperty |
| 1574 | def buffer(self) -> BinaryIO: |
| 1575 | pass |
| 1576 | |
| 1577 | @abstractproperty |
| 1578 | def encoding(self) -> str: |
| 1579 | pass |
| 1580 | |
| 1581 | @abstractproperty |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1582 | def errors(self) -> Optional[str]: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1583 | pass |
| 1584 | |
| 1585 | @abstractproperty |
| 1586 | def line_buffering(self) -> bool: |
| 1587 | pass |
| 1588 | |
| 1589 | @abstractproperty |
| 1590 | def newlines(self) -> Any: |
| 1591 | pass |
| 1592 | |
| 1593 | @abstractmethod |
| 1594 | def __enter__(self) -> 'TextIO': |
| 1595 | pass |
| 1596 | |
| 1597 | |
| 1598 | class io: |
| 1599 | """Wrapper namespace for IO generic classes.""" |
| 1600 | |
| 1601 | __all__ = ['IO', 'TextIO', 'BinaryIO'] |
| 1602 | IO = IO |
| 1603 | TextIO = TextIO |
| 1604 | BinaryIO = BinaryIO |
| 1605 | |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 1606 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1607 | io.__name__ = __name__ + '.io' |
| 1608 | sys.modules[io.__name__] = io |
| 1609 | |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 1610 | Pattern = _alias(stdlib_re.Pattern, AnyStr) |
| 1611 | Match = _alias(stdlib_re.Match, AnyStr) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1612 | |
| 1613 | class re: |
| 1614 | """Wrapper namespace for re type aliases.""" |
| 1615 | |
| 1616 | __all__ = ['Pattern', 'Match'] |
| 1617 | Pattern = Pattern |
| 1618 | Match = Match |
| 1619 | |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 1620 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1621 | re.__name__ = __name__ + '.re' |
| 1622 | sys.modules[re.__name__] = re |