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