Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1 | import abc |
| 2 | from abc import abstractmethod, abstractproperty |
| 3 | import collections |
Brett Cannon | f3ad042 | 2016-04-15 10:51:30 -0700 | [diff] [blame] | 4 | import contextlib |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 5 | import functools |
| 6 | import re as stdlib_re # Avoid confusion with the re we export. |
| 7 | import sys |
| 8 | import types |
| 9 | try: |
| 10 | import collections.abc as collections_abc |
| 11 | except ImportError: |
| 12 | import collections as collections_abc # Fallback for PY3.2. |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 13 | if sys.version_info[:2] >= (3, 3): |
| 14 | from collections import ChainMap |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 15 | |
| 16 | |
| 17 | # Please keep __all__ alphabetized within each category. |
| 18 | __all__ = [ |
| 19 | # Super-special typing primitives. |
| 20 | 'Any', |
| 21 | 'Callable', |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 22 | 'ClassVar', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 23 | 'Generic', |
| 24 | 'Optional', |
Guido van Rossum | eb9aca3 | 2016-05-24 16:38:22 -0700 | [diff] [blame] | 25 | 'Tuple', |
| 26 | 'Type', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 27 | 'TypeVar', |
| 28 | 'Union', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 29 | |
| 30 | # ABCs (from collections.abc). |
| 31 | 'AbstractSet', # collections.abc.Set. |
| 32 | 'ByteString', |
| 33 | 'Container', |
| 34 | 'Hashable', |
| 35 | 'ItemsView', |
| 36 | 'Iterable', |
| 37 | 'Iterator', |
| 38 | 'KeysView', |
| 39 | 'Mapping', |
| 40 | 'MappingView', |
| 41 | 'MutableMapping', |
| 42 | 'MutableSequence', |
| 43 | 'MutableSet', |
| 44 | 'Sequence', |
| 45 | 'Sized', |
| 46 | 'ValuesView', |
Guido van Rossum | 62fe1bb | 2016-10-29 16:05:26 -0700 | [diff] [blame^] | 47 | # The following are added depending on presence |
| 48 | # of their non-generic counterparts in stdlib: |
| 49 | # Awaitable, |
| 50 | # AsyncIterator, |
| 51 | # AsyncIterable, |
| 52 | # Coroutine, |
| 53 | # Collection, |
| 54 | # ContextManager |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 55 | |
| 56 | # Structural checks, a.k.a. protocols. |
| 57 | 'Reversible', |
| 58 | 'SupportsAbs', |
| 59 | 'SupportsFloat', |
| 60 | 'SupportsInt', |
| 61 | 'SupportsRound', |
| 62 | |
| 63 | # Concrete collection types. |
| 64 | 'Dict', |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 65 | 'DefaultDict', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 66 | 'List', |
| 67 | 'Set', |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 68 | 'FrozenSet', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 69 | 'NamedTuple', # Not really a type. |
| 70 | 'Generator', |
| 71 | |
| 72 | # One-off things. |
| 73 | 'AnyStr', |
| 74 | 'cast', |
| 75 | 'get_type_hints', |
Guido van Rossum | 91185fe | 2016-06-08 11:19:11 -0700 | [diff] [blame] | 76 | 'NewType', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 77 | 'no_type_check', |
| 78 | 'no_type_check_decorator', |
| 79 | 'overload', |
Guido van Rossum | 0e0563c | 2016-04-05 14:54:25 -0700 | [diff] [blame] | 80 | 'Text', |
Guido van Rossum | 91185fe | 2016-06-08 11:19:11 -0700 | [diff] [blame] | 81 | 'TYPE_CHECKING', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 82 | ] |
| 83 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 84 | # The pseudo-submodules 're' and 'io' are part of the public |
| 85 | # namespace, but excluded from __all__ because they might stomp on |
| 86 | # legitimate imports of those modules. |
| 87 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 88 | |
| 89 | def _qualname(x): |
| 90 | if sys.version_info[:2] >= (3, 3): |
| 91 | return x.__qualname__ |
| 92 | else: |
| 93 | # Fall back to just name. |
| 94 | return x.__name__ |
| 95 | |
| 96 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 97 | def _trim_name(nm): |
| 98 | if nm.startswith('_') and nm not in ('_TypeAlias', |
| 99 | '_ForwardRef', '_TypingBase', '_FinalTypingBase'): |
| 100 | nm = nm[1:] |
| 101 | return nm |
| 102 | |
| 103 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 104 | class TypingMeta(type): |
| 105 | """Metaclass for every type defined below. |
| 106 | |
| 107 | This overrides __new__() to require an extra keyword parameter |
| 108 | '_root', which serves as a guard against naive subclassing of the |
| 109 | typing classes. Any legitimate class defined using a metaclass |
| 110 | derived from TypingMeta (including internal subclasses created by |
| 111 | e.g. Union[X, Y]) must pass _root=True. |
| 112 | |
| 113 | This also defines a dummy constructor (all the work is done in |
| 114 | __new__) and a nicer repr(). |
| 115 | """ |
| 116 | |
| 117 | _is_protocol = False |
| 118 | |
| 119 | def __new__(cls, name, bases, namespace, *, _root=False): |
| 120 | if not _root: |
| 121 | raise TypeError("Cannot subclass %s" % |
| 122 | (', '.join(map(_type_repr, bases)) or '()')) |
| 123 | return super().__new__(cls, name, bases, namespace) |
| 124 | |
| 125 | def __init__(self, *args, **kwds): |
| 126 | pass |
| 127 | |
| 128 | def _eval_type(self, globalns, localns): |
| 129 | """Override this in subclasses to interpret forward references. |
| 130 | |
| 131 | For example, Union['C'] is internally stored as |
| 132 | Union[_ForwardRef('C')], which should evaluate to _Union[C], |
| 133 | where C is an object found in globalns or localns (searching |
| 134 | localns first, of course). |
| 135 | """ |
| 136 | return self |
| 137 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 138 | def _get_type_vars(self, tvars): |
| 139 | pass |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 140 | |
| 141 | def __repr__(self): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 142 | qname = _trim_name(_qualname(self)) |
| 143 | return '%s.%s' % (self.__module__, qname) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 144 | |
| 145 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 146 | class _TypingBase(metaclass=TypingMeta, _root=True): |
| 147 | """Indicator of special typing constructs.""" |
| 148 | |
| 149 | __slots__ = () |
| 150 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 151 | def __init__(self, *args, **kwds): |
| 152 | pass |
| 153 | |
| 154 | def __new__(cls, *args, **kwds): |
| 155 | """Constructor. |
| 156 | |
| 157 | This only exists to give a better error message in case |
| 158 | someone tries to subclass a special typing object (not a good idea). |
| 159 | """ |
| 160 | if (len(args) == 3 and |
| 161 | isinstance(args[0], str) and |
| 162 | isinstance(args[1], tuple)): |
| 163 | # Close enough. |
| 164 | raise TypeError("Cannot subclass %r" % cls) |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 165 | return super().__new__(cls) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 166 | |
| 167 | # Things that are not classes also need these. |
| 168 | def _eval_type(self, globalns, localns): |
| 169 | return self |
| 170 | |
| 171 | def _get_type_vars(self, tvars): |
| 172 | pass |
| 173 | |
| 174 | def __repr__(self): |
| 175 | cls = type(self) |
| 176 | qname = _trim_name(_qualname(cls)) |
| 177 | return '%s.%s' % (cls.__module__, qname) |
| 178 | |
| 179 | def __call__(self, *args, **kwds): |
| 180 | raise TypeError("Cannot instantiate %r" % type(self)) |
| 181 | |
| 182 | |
| 183 | class _FinalTypingBase(_TypingBase, _root=True): |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 184 | """Mix-in class to prevent instantiation. |
| 185 | |
| 186 | Prevents instantiation unless _root=True is given in class call. |
| 187 | It is used to create pseudo-singleton instances Any, Union, Tuple, etc. |
| 188 | """ |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 189 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 190 | __slots__ = () |
| 191 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 192 | def __new__(cls, *args, _root=False, **kwds): |
| 193 | self = super().__new__(cls, *args, **kwds) |
| 194 | if _root is True: |
| 195 | return self |
| 196 | raise TypeError("Cannot instantiate %r" % cls) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 197 | |
Guido van Rossum | b7dedc8 | 2016-10-29 12:44:29 -0700 | [diff] [blame] | 198 | def __reduce__(self): |
| 199 | return _trim_name(type(self).__name__) |
| 200 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 201 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 202 | class _ForwardRef(_TypingBase, _root=True): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 203 | """Wrapper to hold a forward reference.""" |
| 204 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 205 | __slots__ = ('__forward_arg__', '__forward_code__', |
| 206 | '__forward_evaluated__', '__forward_value__', |
| 207 | '__forward_frame__') |
| 208 | |
| 209 | def __init__(self, arg): |
| 210 | super().__init__(arg) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 211 | if not isinstance(arg, str): |
| 212 | raise TypeError('ForwardRef must be a string -- got %r' % (arg,)) |
| 213 | try: |
| 214 | code = compile(arg, '<string>', 'eval') |
| 215 | except SyntaxError: |
| 216 | raise SyntaxError('ForwardRef must be an expression -- got %r' % |
| 217 | (arg,)) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 218 | self.__forward_arg__ = arg |
| 219 | self.__forward_code__ = code |
| 220 | self.__forward_evaluated__ = False |
| 221 | self.__forward_value__ = None |
| 222 | typing_globals = globals() |
| 223 | frame = sys._getframe(1) |
| 224 | while frame is not None and frame.f_globals is typing_globals: |
| 225 | frame = frame.f_back |
| 226 | assert frame is not None |
| 227 | self.__forward_frame__ = frame |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 228 | |
| 229 | def _eval_type(self, globalns, localns): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 230 | if not self.__forward_evaluated__: |
| 231 | if globalns is None and localns is None: |
| 232 | globalns = localns = {} |
| 233 | elif globalns is None: |
| 234 | globalns = localns |
| 235 | elif localns is None: |
| 236 | localns = globalns |
| 237 | self.__forward_value__ = _type_check( |
| 238 | eval(self.__forward_code__, globalns, localns), |
| 239 | "Forward references must evaluate to types.") |
| 240 | self.__forward_evaluated__ = True |
| 241 | return self.__forward_value__ |
| 242 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 243 | def __eq__(self, other): |
| 244 | if not isinstance(other, _ForwardRef): |
| 245 | return NotImplemented |
| 246 | return (self.__forward_arg__ == other.__forward_arg__ and |
| 247 | self.__forward_frame__ == other.__forward_frame__) |
| 248 | |
| 249 | def __hash__(self): |
| 250 | return hash((self.__forward_arg__, self.__forward_frame__)) |
| 251 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 252 | def __instancecheck__(self, obj): |
| 253 | raise TypeError("Forward references cannot be used with isinstance().") |
| 254 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 255 | def __subclasscheck__(self, cls): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 256 | raise TypeError("Forward references cannot be used with issubclass().") |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 257 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 258 | def __repr__(self): |
| 259 | return '_ForwardRef(%r)' % (self.__forward_arg__,) |
| 260 | |
| 261 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 262 | class _TypeAlias(_TypingBase, _root=True): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 263 | """Internal helper class for defining generic variants of concrete types. |
| 264 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 265 | Note that this is not a type; let's call it a pseudo-type. It cannot |
| 266 | be used in instance and subclass checks in parameterized form, i.e. |
| 267 | ``isinstance(42, Match[str])`` raises ``TypeError`` instead of returning |
| 268 | ``False``. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 269 | """ |
| 270 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 271 | __slots__ = ('name', 'type_var', 'impl_type', 'type_checker') |
| 272 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 273 | def __init__(self, name, type_var, impl_type, type_checker): |
| 274 | """Initializer. |
| 275 | |
| 276 | Args: |
| 277 | name: The name, e.g. 'Pattern'. |
| 278 | type_var: The type parameter, e.g. AnyStr, or the |
| 279 | specific type, e.g. str. |
| 280 | impl_type: The implementation type. |
| 281 | type_checker: Function that takes an impl_type instance. |
| 282 | and returns a value that should be a type_var instance. |
| 283 | """ |
| 284 | assert isinstance(name, str), repr(name) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 285 | assert isinstance(impl_type, type), repr(impl_type) |
| 286 | assert not isinstance(impl_type, TypingMeta), repr(impl_type) |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 287 | assert isinstance(type_var, (type, _TypingBase)), repr(type_var) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 288 | self.name = name |
| 289 | self.type_var = type_var |
| 290 | self.impl_type = impl_type |
| 291 | self.type_checker = type_checker |
| 292 | |
| 293 | def __repr__(self): |
| 294 | return "%s[%s]" % (self.name, _type_repr(self.type_var)) |
| 295 | |
| 296 | def __getitem__(self, parameter): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 297 | if not isinstance(self.type_var, TypeVar): |
| 298 | raise TypeError("%s cannot be further parameterized." % self) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 299 | if self.type_var.__constraints__ and isinstance(parameter, type): |
| 300 | if not issubclass(parameter, self.type_var.__constraints__): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 301 | raise TypeError("%s is not a valid substitution for %s." % |
| 302 | (parameter, self.type_var)) |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 303 | if isinstance(parameter, TypeVar) and parameter is not self.type_var: |
| 304 | raise TypeError("%s cannot be re-parameterized." % self) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 305 | return self.__class__(self.name, parameter, |
| 306 | self.impl_type, self.type_checker) |
| 307 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 308 | def __eq__(self, other): |
| 309 | if not isinstance(other, _TypeAlias): |
| 310 | return NotImplemented |
| 311 | return self.name == other.name and self.type_var == other.type_var |
| 312 | |
| 313 | def __hash__(self): |
| 314 | return hash((self.name, self.type_var)) |
| 315 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 316 | def __instancecheck__(self, obj): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 317 | if not isinstance(self.type_var, TypeVar): |
| 318 | raise TypeError("Parameterized type aliases cannot be used " |
| 319 | "with isinstance().") |
| 320 | return isinstance(obj, self.impl_type) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 321 | |
| 322 | def __subclasscheck__(self, cls): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 323 | if not isinstance(self.type_var, TypeVar): |
| 324 | raise TypeError("Parameterized type aliases cannot be used " |
| 325 | "with issubclass().") |
| 326 | return issubclass(cls, self.impl_type) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 327 | |
| 328 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 329 | def _get_type_vars(types, tvars): |
| 330 | for t in types: |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 331 | if isinstance(t, TypingMeta) or isinstance(t, _TypingBase): |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 332 | t._get_type_vars(tvars) |
| 333 | |
| 334 | |
| 335 | def _type_vars(types): |
| 336 | tvars = [] |
| 337 | _get_type_vars(types, tvars) |
| 338 | return tuple(tvars) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 339 | |
| 340 | |
| 341 | def _eval_type(t, globalns, localns): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 342 | if isinstance(t, TypingMeta) or isinstance(t, _TypingBase): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 343 | return t._eval_type(globalns, localns) |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 344 | return t |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 345 | |
| 346 | |
| 347 | def _type_check(arg, msg): |
| 348 | """Check that the argument is a type, and return it. |
| 349 | |
| 350 | As a special case, accept None and return type(None) instead. |
| 351 | Also, _TypeAlias instances (e.g. Match, Pattern) are acceptable. |
| 352 | |
| 353 | The msg argument is a human-readable error message, e.g. |
| 354 | |
| 355 | "Union[arg, ...]: arg should be a type." |
| 356 | |
| 357 | We append the repr() of the actual value (truncated to 100 chars). |
| 358 | """ |
| 359 | if arg is None: |
| 360 | return type(None) |
| 361 | if isinstance(arg, str): |
| 362 | arg = _ForwardRef(arg) |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 363 | if (isinstance(arg, _TypingBase) and type(arg).__name__ == '_ClassVar' or |
| 364 | not isinstance(arg, (type, _TypingBase)) and not callable(arg)): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 365 | raise TypeError(msg + " Got %.100r." % (arg,)) |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 366 | # Bare Union etc. are not valid as type arguments |
| 367 | if (type(arg).__name__ in ('_Union', '_Optional') |
| 368 | and not getattr(arg, '__origin__', None) |
| 369 | or isinstance(arg, TypingMeta) and _gorg(arg) in (Generic, _Protocol)): |
| 370 | raise TypeError("Plain %s is not valid as type argument" % arg) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 371 | return arg |
| 372 | |
| 373 | |
| 374 | def _type_repr(obj): |
| 375 | """Return the repr() of an object, special-casing types. |
| 376 | |
| 377 | If obj is a type, we return a shorter version than the default |
| 378 | type.__repr__, based on the module and qualified name, which is |
| 379 | typically enough to uniquely identify a type. For everything |
| 380 | else, we fall back on repr(obj). |
| 381 | """ |
| 382 | if isinstance(obj, type) and not isinstance(obj, TypingMeta): |
| 383 | if obj.__module__ == 'builtins': |
| 384 | return _qualname(obj) |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 385 | return '%s.%s' % (obj.__module__, _qualname(obj)) |
| 386 | if obj is ...: |
| 387 | return('...') |
| 388 | if isinstance(obj, types.FunctionType): |
| 389 | return obj.__name__ |
| 390 | return repr(obj) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 391 | |
| 392 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 393 | class _Any(_FinalTypingBase, _root=True): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 394 | """Special type indicating an unconstrained type. |
| 395 | |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 396 | - Any is compatible with every type. |
| 397 | - Any assumed to have all methods. |
| 398 | - All values assumed to be instances of Any. |
| 399 | |
| 400 | Note that all the above statements are true from the point of view of |
| 401 | static type checkers. At runtime, Any should not be used with instance |
| 402 | or class checks. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 403 | """ |
| 404 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 405 | __slots__ = () |
| 406 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 407 | def __instancecheck__(self, obj): |
| 408 | raise TypeError("Any cannot be used with isinstance().") |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 409 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 410 | def __subclasscheck__(self, cls): |
| 411 | raise TypeError("Any cannot be used with issubclass().") |
| 412 | |
| 413 | |
| 414 | Any = _Any(_root=True) |
| 415 | |
| 416 | |
| 417 | class TypeVar(_TypingBase, _root=True): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 418 | """Type variable. |
| 419 | |
| 420 | Usage:: |
| 421 | |
| 422 | T = TypeVar('T') # Can be anything |
| 423 | A = TypeVar('A', str, bytes) # Must be str or bytes |
| 424 | |
| 425 | Type variables exist primarily for the benefit of static type |
| 426 | checkers. They serve as the parameters for generic types as well |
| 427 | as for generic function definitions. See class Generic for more |
| 428 | information on generic types. Generic functions work as follows: |
| 429 | |
| 430 | def repeat(x: T, n: int) -> Sequence[T]: |
| 431 | '''Return a list containing n references to x.''' |
| 432 | return [x]*n |
| 433 | |
| 434 | def longest(x: A, y: A) -> A: |
| 435 | '''Return the longest of two strings.''' |
| 436 | return x if len(x) >= len(y) else y |
| 437 | |
| 438 | The latter example's signature is essentially the overloading |
| 439 | of (str, str) -> str and (bytes, bytes) -> bytes. Also note |
| 440 | that if the arguments are instances of some subclass of str, |
| 441 | the return type is still plain str. |
| 442 | |
| 443 | At runtime, isinstance(x, T) will raise TypeError. However, |
| 444 | issubclass(C, T) is true for any class C, and issubclass(str, A) |
| 445 | and issubclass(bytes, A) are true, and issubclass(int, A) is |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 446 | false. (TODO: Why is this needed? This may change. See #136.) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 447 | |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 448 | Type variables defined with covariant=True or contravariant=True |
| 449 | can be used do declare covariant or contravariant generic types. |
| 450 | See PEP 484 for more details. By default generic types are invariant |
| 451 | in all type variables. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 452 | |
| 453 | Type variables can be introspected. e.g.: |
| 454 | |
| 455 | T.__name__ == 'T' |
| 456 | T.__constraints__ == () |
| 457 | T.__covariant__ == False |
| 458 | T.__contravariant__ = False |
| 459 | A.__constraints__ == (str, bytes) |
| 460 | """ |
| 461 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 462 | __slots__ = ('__name__', '__bound__', '__constraints__', |
| 463 | '__covariant__', '__contravariant__') |
| 464 | |
| 465 | def __init__(self, name, *constraints, bound=None, |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 466 | covariant=False, contravariant=False): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 467 | super().__init__(name, *constraints, bound=bound, |
| 468 | covariant=covariant, contravariant=contravariant) |
| 469 | self.__name__ = name |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 470 | if covariant and contravariant: |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 471 | raise ValueError("Bivariant types are not supported.") |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 472 | self.__covariant__ = bool(covariant) |
| 473 | self.__contravariant__ = bool(contravariant) |
| 474 | if constraints and bound is not None: |
| 475 | raise TypeError("Constraints cannot be combined with bound=...") |
| 476 | if constraints and len(constraints) == 1: |
| 477 | raise TypeError("A single constraint is not allowed") |
| 478 | msg = "TypeVar(name, constraint, ...): constraints must be types." |
| 479 | self.__constraints__ = tuple(_type_check(t, msg) for t in constraints) |
| 480 | if bound: |
| 481 | self.__bound__ = _type_check(bound, "Bound must be a type.") |
| 482 | else: |
| 483 | self.__bound__ = None |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 484 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 485 | def _get_type_vars(self, tvars): |
| 486 | if self not in tvars: |
| 487 | tvars.append(self) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 488 | |
| 489 | def __repr__(self): |
| 490 | if self.__covariant__: |
| 491 | prefix = '+' |
| 492 | elif self.__contravariant__: |
| 493 | prefix = '-' |
| 494 | else: |
| 495 | prefix = '~' |
| 496 | return prefix + self.__name__ |
| 497 | |
| 498 | def __instancecheck__(self, instance): |
| 499 | raise TypeError("Type variables cannot be used with isinstance().") |
| 500 | |
| 501 | def __subclasscheck__(self, cls): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 502 | raise TypeError("Type variables cannot be used with issubclass().") |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 503 | |
| 504 | |
| 505 | # Some unconstrained type variables. These are used by the container types. |
Guido van Rossum | eb9aca3 | 2016-05-24 16:38:22 -0700 | [diff] [blame] | 506 | # (These are not for export.) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 507 | T = TypeVar('T') # Any type. |
| 508 | KT = TypeVar('KT') # Key type. |
| 509 | VT = TypeVar('VT') # Value type. |
| 510 | T_co = TypeVar('T_co', covariant=True) # Any type covariant containers. |
| 511 | V_co = TypeVar('V_co', covariant=True) # Any type covariant containers. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 512 | VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers. |
| 513 | T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant. |
| 514 | |
| 515 | # A useful type variable with constraints. This represents string types. |
Guido van Rossum | eb9aca3 | 2016-05-24 16:38:22 -0700 | [diff] [blame] | 516 | # (This one *is* for export!) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 517 | AnyStr = TypeVar('AnyStr', bytes, str) |
| 518 | |
| 519 | |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 520 | def _replace_arg(arg, tvars, args): |
| 521 | """ A helper fuunction: replace arg if it is a type variable |
| 522 | found in tvars with corresponding substitution from args or |
| 523 | with corresponding substitution sub-tree if arg is a generic type. |
| 524 | """ |
| 525 | |
| 526 | if tvars is None: |
| 527 | tvars = [] |
| 528 | if hasattr(arg, '_subs_tree'): |
| 529 | return arg._subs_tree(tvars, args) |
| 530 | if isinstance(arg, TypeVar): |
| 531 | for i, tvar in enumerate(tvars): |
| 532 | if arg == tvar: |
| 533 | return args[i] |
| 534 | return arg |
| 535 | |
| 536 | |
| 537 | def _subs_tree(cls, tvars=None, args=None): |
| 538 | """ Calculate substitution tree for generic cls after |
| 539 | replacing its type parameters with substitutions in tvars -> args (if any). |
| 540 | Repeat the same cyclicaly following __origin__'s. |
| 541 | """ |
| 542 | |
| 543 | if cls.__origin__ is None: |
| 544 | return cls |
| 545 | # Make of chain of origins (i.e. cls -> cls.__origin__) |
| 546 | current = cls.__origin__ |
| 547 | orig_chain = [] |
| 548 | while current.__origin__ is not None: |
| 549 | orig_chain.append(current) |
| 550 | current = current.__origin__ |
| 551 | # Replace type variables in __args__ if asked ... |
| 552 | tree_args = [] |
| 553 | for arg in cls.__args__: |
| 554 | tree_args.append(_replace_arg(arg, tvars, args)) |
| 555 | # ... then continue replacing down the origin chain. |
| 556 | for ocls in orig_chain: |
| 557 | new_tree_args = [] |
| 558 | for i, arg in enumerate(ocls.__args__): |
| 559 | new_tree_args.append(_replace_arg(arg, ocls.__parameters__, tree_args)) |
| 560 | tree_args = new_tree_args |
| 561 | return tree_args |
| 562 | |
| 563 | |
| 564 | def _remove_dups_flatten(parameters): |
| 565 | """ A helper for Union creation and substitution: flatten Union's |
| 566 | among parameters, then remove duplicates and strict subclasses. |
| 567 | """ |
| 568 | |
| 569 | # Flatten out Union[Union[...], ...]. |
| 570 | params = [] |
| 571 | for p in parameters: |
| 572 | if isinstance(p, _Union) and p.__origin__ is Union: |
| 573 | params.extend(p.__args__) |
| 574 | elif isinstance(p, tuple) and len(p) > 0 and p[0] is Union: |
| 575 | params.extend(p[1:]) |
| 576 | else: |
| 577 | params.append(p) |
| 578 | # Weed out strict duplicates, preserving the first of each occurrence. |
| 579 | all_params = set(params) |
| 580 | if len(all_params) < len(params): |
| 581 | new_params = [] |
| 582 | for t in params: |
| 583 | if t in all_params: |
| 584 | new_params.append(t) |
| 585 | all_params.remove(t) |
| 586 | params = new_params |
| 587 | assert not all_params, all_params |
| 588 | # Weed out subclasses. |
| 589 | # E.g. Union[int, Employee, Manager] == Union[int, Employee]. |
| 590 | # If object is present it will be sole survivor among proper classes. |
| 591 | # Never discard type variables. |
| 592 | # (In particular, Union[str, AnyStr] != AnyStr.) |
| 593 | all_params = set(params) |
| 594 | for t1 in params: |
| 595 | if not isinstance(t1, type): |
| 596 | continue |
| 597 | if any(isinstance(t2, type) and issubclass(t1, t2) |
| 598 | for t2 in all_params - {t1} |
| 599 | if not (isinstance(t2, GenericMeta) and |
| 600 | t2.__origin__ is not None)): |
| 601 | all_params.remove(t1) |
| 602 | return tuple(t for t in params if t in all_params) |
| 603 | |
| 604 | |
| 605 | def _check_generic(cls, parameters): |
| 606 | # Check correct count for parameters of a generic cls. |
| 607 | if not cls.__parameters__: |
| 608 | raise TypeError("%s is not a generic class" % repr(cls)) |
| 609 | alen = len(parameters) |
| 610 | elen = len(cls.__parameters__) |
| 611 | if alen != elen: |
| 612 | raise TypeError("Too %s parameters for %s; actual %s, expected %s" % |
| 613 | ("many" if alen > elen else "few", repr(cls), alen, elen)) |
| 614 | |
| 615 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 616 | def _tp_cache(func): |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 617 | """ Caching for __getitem__ of generic types with a fallback to |
| 618 | original function for non-hashable arguments. |
| 619 | """ |
| 620 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 621 | cached = functools.lru_cache()(func) |
| 622 | @functools.wraps(func) |
| 623 | def inner(*args, **kwds): |
| 624 | try: |
| 625 | return cached(*args, **kwds) |
| 626 | except TypeError: |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 627 | pass # All real errors (not unhashable args) are raised below. |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 628 | return func(*args, **kwds) |
| 629 | return inner |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 630 | |
| 631 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 632 | class _Union(_FinalTypingBase, _root=True): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 633 | """Union type; Union[X, Y] means either X or Y. |
| 634 | |
| 635 | To define a union, use e.g. Union[int, str]. Details: |
| 636 | |
| 637 | - The arguments must be types and there must be at least one. |
| 638 | |
| 639 | - None as an argument is a special case and is replaced by |
| 640 | type(None). |
| 641 | |
| 642 | - Unions of unions are flattened, e.g.:: |
| 643 | |
| 644 | Union[Union[int, str], float] == Union[int, str, float] |
| 645 | |
| 646 | - Unions of a single argument vanish, e.g.:: |
| 647 | |
| 648 | Union[int] == int # The constructor actually returns int |
| 649 | |
| 650 | - Redundant arguments are skipped, e.g.:: |
| 651 | |
| 652 | Union[int, str, int] == Union[int, str] |
| 653 | |
| 654 | - When comparing unions, the argument order is ignored, e.g.:: |
| 655 | |
| 656 | Union[int, str] == Union[str, int] |
| 657 | |
| 658 | - When two arguments have a subclass relationship, the least |
| 659 | derived argument is kept, e.g.:: |
| 660 | |
| 661 | class Employee: pass |
| 662 | class Manager(Employee): pass |
| 663 | Union[int, Employee, Manager] == Union[int, Employee] |
| 664 | Union[Manager, int, Employee] == Union[int, Employee] |
| 665 | Union[Employee, Manager] == Employee |
| 666 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 667 | - Similar for object:: |
| 668 | |
| 669 | Union[int, object] == object |
| 670 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 671 | - You cannot subclass or instantiate a union. |
| 672 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 673 | - You can use Optional[X] as a shorthand for Union[X, None]. |
| 674 | """ |
| 675 | |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 676 | __slots__ = ('__parameters__', '__args__', '__origin__', '__tree_hash__') |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 677 | |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 678 | def __new__(cls, parameters=None, origin=None, *args, _root=False): |
| 679 | self = super().__new__(cls, parameters, origin, *args, _root=_root) |
| 680 | if origin is None: |
| 681 | self.__parameters__ = None |
| 682 | self.__args__ = None |
| 683 | self.__origin__ = None |
| 684 | self.__tree_hash__ = hash(frozenset(('Union',))) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 685 | return self |
| 686 | if not isinstance(parameters, tuple): |
| 687 | raise TypeError("Expected parameters=<tuple>") |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 688 | if origin is Union: |
| 689 | parameters = _remove_dups_flatten(parameters) |
| 690 | # It's not a union if there's only one type left. |
| 691 | if len(parameters) == 1: |
| 692 | return parameters[0] |
| 693 | self.__parameters__ = _type_vars(parameters) |
| 694 | self.__args__ = parameters |
| 695 | self.__origin__ = origin |
| 696 | # Pre-calculate the __hash__ on instantiation. |
| 697 | # This improves speed for complex substitutions. |
| 698 | subs_tree = self._subs_tree() |
| 699 | if isinstance(subs_tree, tuple): |
| 700 | self.__tree_hash__ = hash(frozenset(subs_tree)) |
| 701 | else: |
| 702 | self.__tree_hash__ = hash(subs_tree) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 703 | return self |
| 704 | |
| 705 | def _eval_type(self, globalns, localns): |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 706 | if self.__args__ is None: |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 707 | return self |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 708 | ev_args = tuple(_eval_type(t, globalns, localns) for t in self.__args__) |
| 709 | ev_origin = _eval_type(self.__origin__, globalns, localns) |
| 710 | if ev_args == self.__args__ and ev_origin == self.__origin__: |
| 711 | # Everything is already evaluated. |
| 712 | return self |
| 713 | return self.__class__(ev_args, ev_origin, _root=True) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 714 | |
| 715 | def _get_type_vars(self, tvars): |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 716 | if self.__origin__ and self.__parameters__: |
| 717 | _get_type_vars(self.__parameters__, tvars) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 718 | |
| 719 | def __repr__(self): |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 720 | if self.__origin__ is None: |
| 721 | return super().__repr__() |
| 722 | tree = self._subs_tree() |
| 723 | if not isinstance(tree, tuple): |
| 724 | return repr(tree) |
| 725 | return tree[0]._tree_repr(tree) |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 726 | |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 727 | def _tree_repr(self, tree): |
| 728 | arg_list = [] |
| 729 | for arg in tree[1:]: |
| 730 | if not isinstance(arg, tuple): |
| 731 | arg_list.append(_type_repr(arg)) |
| 732 | else: |
| 733 | arg_list.append(arg[0]._tree_repr(arg)) |
| 734 | return super().__repr__() + '[%s]' % ', '.join(arg_list) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 735 | |
| 736 | @_tp_cache |
| 737 | def __getitem__(self, parameters): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 738 | if parameters == (): |
| 739 | raise TypeError("Cannot take a Union of no types.") |
| 740 | if not isinstance(parameters, tuple): |
| 741 | parameters = (parameters,) |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 742 | if self.__origin__ is None: |
| 743 | msg = "Union[arg, ...]: each arg must be a type." |
| 744 | else: |
| 745 | msg = "Parameters to generic types must be types." |
| 746 | parameters = tuple(_type_check(p, msg) for p in parameters) |
| 747 | if self is not Union: |
| 748 | _check_generic(self, parameters) |
| 749 | return self.__class__(parameters, origin=self, _root=True) |
| 750 | |
| 751 | def _subs_tree(self, tvars=None, args=None): |
| 752 | if self is Union: |
| 753 | return Union # Nothing to substitute |
| 754 | tree_args = _subs_tree(self, tvars, args) |
| 755 | tree_args = _remove_dups_flatten(tree_args) |
| 756 | if len(tree_args) == 1: |
| 757 | return tree_args[0] # Union of a single type is that type |
| 758 | return (Union,) + tree_args |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 759 | |
| 760 | def __eq__(self, other): |
| 761 | if not isinstance(other, _Union): |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 762 | return self._subs_tree() == other |
| 763 | return self.__tree_hash__ == other.__tree_hash__ |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 764 | |
| 765 | def __hash__(self): |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 766 | return self.__tree_hash__ |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 767 | |
| 768 | def __instancecheck__(self, obj): |
| 769 | raise TypeError("Unions cannot be used with isinstance().") |
| 770 | |
| 771 | def __subclasscheck__(self, cls): |
| 772 | raise TypeError("Unions cannot be used with issubclass().") |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 773 | |
| 774 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 775 | Union = _Union(_root=True) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 776 | |
| 777 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 778 | class _Optional(_FinalTypingBase, _root=True): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 779 | """Optional type. |
| 780 | |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 781 | Optional[X] is equivalent to Union[X, None]. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 782 | """ |
| 783 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 784 | __slots__ = () |
| 785 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 786 | @_tp_cache |
| 787 | def __getitem__(self, arg): |
| 788 | arg = _type_check(arg, "Optional[t] requires a single type.") |
| 789 | return Union[arg, type(None)] |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 790 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 791 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 792 | Optional = _Optional(_root=True) |
| 793 | |
| 794 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 795 | def _gorg(a): |
| 796 | """Return the farthest origin of a generic class.""" |
| 797 | assert isinstance(a, GenericMeta) |
| 798 | while a.__origin__ is not None: |
| 799 | a = a.__origin__ |
| 800 | return a |
| 801 | |
| 802 | |
| 803 | def _geqv(a, b): |
| 804 | """Return whether two generic classes are equivalent. |
| 805 | |
| 806 | The intention is to consider generic class X and any of its |
| 807 | parameterized forms (X[T], X[int], etc.) as equivalent. |
| 808 | |
| 809 | However, X is not equivalent to a subclass of X. |
| 810 | |
| 811 | The relation is reflexive, symmetric and transitive. |
| 812 | """ |
| 813 | assert isinstance(a, GenericMeta) and isinstance(b, GenericMeta) |
| 814 | # Reduce each to its origin. |
| 815 | return _gorg(a) is _gorg(b) |
| 816 | |
| 817 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 818 | def _next_in_mro(cls): |
| 819 | """Helper for Generic.__new__. |
| 820 | |
| 821 | Returns the class after the last occurrence of Generic or |
| 822 | Generic[...] in cls.__mro__. |
| 823 | """ |
| 824 | next_in_mro = object |
| 825 | # Look for the last occurrence of Generic or Generic[...]. |
| 826 | for i, c in enumerate(cls.__mro__[:-1]): |
| 827 | if isinstance(c, GenericMeta) and _gorg(c) is Generic: |
| 828 | next_in_mro = cls.__mro__[i+1] |
| 829 | return next_in_mro |
| 830 | |
| 831 | |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 832 | def _valid_for_check(cls): |
| 833 | if cls is Generic: |
| 834 | raise TypeError("Class %r cannot be used with class " |
| 835 | "or instance checks" % cls) |
| 836 | if (cls.__origin__ is not None and |
| 837 | sys._getframe(3).f_globals['__name__'] not in ['abc', 'functools']): |
| 838 | raise TypeError("Parameterized generics cannot be used with class " |
| 839 | "or instance checks") |
| 840 | |
| 841 | |
| 842 | def _make_subclasshook(cls): |
| 843 | """Construct a __subclasshook__ callable that incorporates |
| 844 | the associated __extra__ class in subclass checks performed |
| 845 | against cls. |
| 846 | """ |
| 847 | if isinstance(cls.__extra__, abc.ABCMeta): |
| 848 | # The logic mirrors that of ABCMeta.__subclasscheck__. |
| 849 | # Registered classes need not be checked here because |
| 850 | # cls and its extra share the same _abc_registry. |
| 851 | def __extrahook__(subclass): |
| 852 | _valid_for_check(cls) |
| 853 | res = cls.__extra__.__subclasshook__(subclass) |
| 854 | if res is not NotImplemented: |
| 855 | return res |
| 856 | if cls.__extra__ in subclass.__mro__: |
| 857 | return True |
| 858 | for scls in cls.__extra__.__subclasses__(): |
| 859 | if isinstance(scls, GenericMeta): |
| 860 | continue |
| 861 | if issubclass(subclass, scls): |
| 862 | return True |
| 863 | return NotImplemented |
| 864 | else: |
| 865 | # For non-ABC extras we'll just call issubclass(). |
| 866 | def __extrahook__(subclass): |
| 867 | _valid_for_check(cls) |
| 868 | if cls.__extra__ and issubclass(subclass, cls.__extra__): |
| 869 | return True |
| 870 | return NotImplemented |
| 871 | return __extrahook__ |
| 872 | |
| 873 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 874 | class GenericMeta(TypingMeta, abc.ABCMeta): |
| 875 | """Metaclass for generic types.""" |
| 876 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 877 | def __new__(cls, name, bases, namespace, |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 878 | tvars=None, args=None, origin=None, extra=None, orig_bases=None): |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 879 | if tvars is not None: |
| 880 | # Called from __getitem__() below. |
| 881 | assert origin is not None |
| 882 | assert all(isinstance(t, TypeVar) for t in tvars), tvars |
| 883 | else: |
| 884 | # Called from class statement. |
| 885 | assert tvars is None, tvars |
| 886 | assert args is None, args |
| 887 | assert origin is None, origin |
| 888 | |
| 889 | # Get the full set of tvars from the bases. |
| 890 | tvars = _type_vars(bases) |
| 891 | # Look for Generic[T1, ..., Tn]. |
| 892 | # If found, tvars must be a subset of it. |
| 893 | # If not found, tvars is it. |
| 894 | # Also check for and reject plain Generic, |
| 895 | # and reject multiple Generic[...]. |
| 896 | gvars = None |
| 897 | for base in bases: |
| 898 | if base is Generic: |
| 899 | raise TypeError("Cannot inherit from plain Generic") |
| 900 | if (isinstance(base, GenericMeta) and |
| 901 | base.__origin__ is Generic): |
| 902 | if gvars is not None: |
| 903 | raise TypeError( |
| 904 | "Cannot inherit from Generic[...] multiple types.") |
| 905 | gvars = base.__parameters__ |
| 906 | if gvars is None: |
| 907 | gvars = tvars |
| 908 | else: |
| 909 | tvarset = set(tvars) |
| 910 | gvarset = set(gvars) |
| 911 | if not tvarset <= gvarset: |
| 912 | raise TypeError( |
| 913 | "Some type variables (%s) " |
| 914 | "are not listed in Generic[%s]" % |
| 915 | (", ".join(str(t) for t in tvars if t not in gvarset), |
| 916 | ", ".join(str(g) for g in gvars))) |
| 917 | tvars = gvars |
| 918 | |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 919 | initial_bases = bases |
| 920 | if extra is not None and type(extra) is abc.ABCMeta and extra not in bases: |
| 921 | bases = (extra,) + bases |
| 922 | bases = tuple(_gorg(b) if isinstance(b, GenericMeta) else b for b in bases) |
| 923 | |
| 924 | # remove bare Generic from bases if there are other generic bases |
| 925 | if any(isinstance(b, GenericMeta) and b is not Generic for b in bases): |
| 926 | bases = tuple(b for b in bases if b is not Generic) |
| 927 | self = super().__new__(cls, name, bases, namespace, _root=True) |
| 928 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 929 | self.__parameters__ = tvars |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 930 | # Be prepared that GenericMeta will be subclassed by TupleMeta |
| 931 | # and CallableMeta, those two allow ..., (), or [] in __args___. |
| 932 | self.__args__ = tuple(... if a is _TypingEllipsis else |
| 933 | () if a is _TypingEmpty else |
| 934 | a for a in args) if args else None |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 935 | self.__origin__ = origin |
Guido van Rossum | 1cea70f | 2016-05-18 08:35:00 -0700 | [diff] [blame] | 936 | self.__extra__ = extra |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 937 | # Speed hack (https://github.com/python/typing/issues/196). |
| 938 | self.__next_in_mro__ = _next_in_mro(self) |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 939 | # Preserve base classes on subclassing (__bases__ are type erased now). |
| 940 | if orig_bases is None: |
| 941 | self.__orig_bases__ = initial_bases |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 942 | |
| 943 | # This allows unparameterized generic collections to be used |
| 944 | # with issubclass() and isinstance() in the same way as their |
| 945 | # collections.abc counterparts (e.g., isinstance([], Iterable)). |
Guido van Rossum | e259267 | 2016-10-08 20:27:22 -0700 | [diff] [blame] | 946 | if ('__subclasshook__' not in namespace and extra # allow overriding |
| 947 | or hasattr(self.__subclasshook__, '__name__') and |
| 948 | self.__subclasshook__.__name__ == '__extrahook__'): |
| 949 | self.__subclasshook__ = _make_subclasshook(self) |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 950 | if isinstance(extra, abc.ABCMeta): |
| 951 | self._abc_registry = extra._abc_registry |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 952 | |
| 953 | if origin and hasattr(origin, '__qualname__'): # Fix for Python 3.2. |
| 954 | self.__qualname__ = origin.__qualname__ |
| 955 | self.__tree_hash__ = hash(self._subs_tree()) if origin else hash((self.__name__,)) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 956 | return self |
| 957 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 958 | def _get_type_vars(self, tvars): |
| 959 | if self.__origin__ and self.__parameters__: |
| 960 | _get_type_vars(self.__parameters__, tvars) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 961 | |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 962 | def _eval_type(self, globalns, localns): |
| 963 | ev_origin = (self.__origin__._eval_type(globalns, localns) |
| 964 | if self.__origin__ else None) |
| 965 | ev_args = tuple(_eval_type(a, globalns, localns) for a |
| 966 | in self.__args__) if self.__args__ else None |
| 967 | if ev_origin == self.__origin__ and ev_args == self.__args__: |
| 968 | return self |
| 969 | return self.__class__(self.__name__, |
| 970 | self.__bases__, |
| 971 | dict(self.__dict__), |
| 972 | tvars=_type_vars(ev_args) if ev_args else None, |
| 973 | args=ev_args, |
| 974 | origin=ev_origin, |
| 975 | extra=self.__extra__, |
| 976 | orig_bases=self.__orig_bases__) |
| 977 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 978 | def __repr__(self): |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 979 | if self.__origin__ is None: |
| 980 | return super().__repr__() |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 981 | return self._tree_repr(self._subs_tree()) |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 982 | |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 983 | def _tree_repr(self, tree): |
| 984 | arg_list = [] |
| 985 | for arg in tree[1:]: |
| 986 | if arg == (): |
| 987 | arg_list.append('()') |
| 988 | elif not isinstance(arg, tuple): |
| 989 | arg_list.append(_type_repr(arg)) |
| 990 | else: |
| 991 | arg_list.append(arg[0]._tree_repr(arg)) |
| 992 | return super().__repr__() + '[%s]' % ', '.join(arg_list) |
| 993 | |
| 994 | def _subs_tree(self, tvars=None, args=None): |
| 995 | if self.__origin__ is None: |
| 996 | return self |
| 997 | tree_args = _subs_tree(self, tvars, args) |
| 998 | return (_gorg(self),) + tuple(tree_args) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 999 | |
| 1000 | def __eq__(self, other): |
| 1001 | if not isinstance(other, GenericMeta): |
| 1002 | return NotImplemented |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1003 | if self.__origin__ is None or other.__origin__ is None: |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1004 | return self is other |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1005 | return self.__tree_hash__ == other.__tree_hash__ |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1006 | |
| 1007 | def __hash__(self): |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1008 | return self.__tree_hash__ |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1009 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1010 | @_tp_cache |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1011 | def __getitem__(self, params): |
| 1012 | if not isinstance(params, tuple): |
| 1013 | params = (params,) |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1014 | if not params and not _gorg(self) is Tuple: |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1015 | raise TypeError( |
| 1016 | "Parameter list to %s[...] cannot be empty" % _qualname(self)) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1017 | msg = "Parameters to generic types must be types." |
| 1018 | params = tuple(_type_check(p, msg) for p in params) |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1019 | if self is Generic: |
| 1020 | # Generic can only be subscripted with unique type variables. |
| 1021 | if not all(isinstance(p, TypeVar) for p in params): |
| 1022 | raise TypeError( |
| 1023 | "Parameters to Generic[...] must all be type variables") |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1024 | if len(set(params)) != len(params): |
Guido van Rossum | 1b66910 | 2015-09-04 12:15:54 -0700 | [diff] [blame] | 1025 | raise TypeError( |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1026 | "Parameters to Generic[...] must all be unique") |
| 1027 | tvars = params |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 1028 | args = params |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1029 | elif self in (Tuple, Callable): |
| 1030 | tvars = _type_vars(params) |
| 1031 | args = params |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1032 | elif self is _Protocol: |
| 1033 | # _Protocol is internal, don't check anything. |
| 1034 | tvars = params |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 1035 | args = params |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1036 | elif self.__origin__ in (Generic, _Protocol): |
| 1037 | # Can't subscript Generic[...] or _Protocol[...]. |
| 1038 | raise TypeError("Cannot subscript already-subscripted %s" % |
| 1039 | repr(self)) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1040 | else: |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1041 | # Subscripting a regular Generic subclass. |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1042 | _check_generic(self, params) |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1043 | tvars = _type_vars(params) |
| 1044 | args = params |
| 1045 | return self.__class__(self.__name__, |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 1046 | self.__bases__, |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1047 | dict(self.__dict__), |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1048 | tvars=tvars, |
| 1049 | args=args, |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1050 | origin=self, |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 1051 | extra=self.__extra__, |
| 1052 | orig_bases=self.__orig_bases__) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1053 | |
Guido van Rossum | 1b66910 | 2015-09-04 12:15:54 -0700 | [diff] [blame] | 1054 | def __instancecheck__(self, instance): |
| 1055 | # Since we extend ABC.__subclasscheck__ and |
| 1056 | # ABC.__instancecheck__ inlines the cache checking done by the |
| 1057 | # latter, we must extend __instancecheck__ too. For simplicity |
| 1058 | # we just skip the cache check -- instance checks for generic |
| 1059 | # classes are supposed to be rare anyways. |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 1060 | return issubclass(instance.__class__, self) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1061 | |
Guido van Rossum | b7dedc8 | 2016-10-29 12:44:29 -0700 | [diff] [blame] | 1062 | def __copy__(self): |
| 1063 | return self.__class__(self.__name__, self.__bases__, dict(self.__dict__), |
| 1064 | self.__parameters__, self.__args__, self.__origin__, |
| 1065 | self.__extra__, self.__orig_bases__) |
| 1066 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1067 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1068 | # Prevent checks for Generic to crash when defining Generic. |
| 1069 | Generic = None |
| 1070 | |
| 1071 | |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1072 | def _generic_new(base_cls, cls, *args, **kwds): |
| 1073 | # Assure type is erased on instantiation, |
| 1074 | # but attempt to store it in __orig_class__ |
| 1075 | if cls.__origin__ is None: |
| 1076 | return base_cls.__new__(cls) |
| 1077 | else: |
| 1078 | origin = _gorg(cls) |
| 1079 | obj = base_cls.__new__(origin) |
| 1080 | try: |
| 1081 | obj.__orig_class__ = cls |
| 1082 | except AttributeError: |
| 1083 | pass |
| 1084 | obj.__init__(*args, **kwds) |
| 1085 | return obj |
| 1086 | |
| 1087 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1088 | class Generic(metaclass=GenericMeta): |
| 1089 | """Abstract base class for generic types. |
| 1090 | |
| 1091 | A generic type is typically declared by inheriting from an |
| 1092 | instantiation of this class with one or more type variables. |
| 1093 | For example, a generic mapping type might be defined as:: |
| 1094 | |
| 1095 | class Mapping(Generic[KT, VT]): |
| 1096 | def __getitem__(self, key: KT) -> VT: |
| 1097 | ... |
| 1098 | # Etc. |
| 1099 | |
| 1100 | This class can then be used as follows:: |
| 1101 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1102 | 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] | 1103 | try: |
| 1104 | return mapping[key] |
| 1105 | except KeyError: |
| 1106 | return default |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1107 | """ |
| 1108 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1109 | __slots__ = () |
| 1110 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1111 | def __new__(cls, *args, **kwds): |
Guido van Rossum | 62fe1bb | 2016-10-29 16:05:26 -0700 | [diff] [blame^] | 1112 | if _geqv(cls, Generic): |
| 1113 | raise TypeError("Type Generic cannot be instantiated; " |
| 1114 | "it can be used only as a base class") |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1115 | return _generic_new(cls.__next_in_mro__, cls, *args, **kwds) |
| 1116 | |
| 1117 | |
| 1118 | class _TypingEmpty: |
| 1119 | """Placeholder for () or []. Used by TupleMeta and CallableMeta |
| 1120 | to allow empy list/tuple in specific places, without allowing them |
| 1121 | to sneak in where prohibited. |
| 1122 | """ |
| 1123 | |
| 1124 | |
| 1125 | class _TypingEllipsis: |
| 1126 | """Ditto for ...""" |
| 1127 | |
| 1128 | |
| 1129 | class TupleMeta(GenericMeta): |
| 1130 | """Metaclass for Tuple""" |
| 1131 | |
| 1132 | @_tp_cache |
| 1133 | def __getitem__(self, parameters): |
| 1134 | if self.__origin__ is not None or not _geqv(self, Tuple): |
| 1135 | # Normal generic rules apply if this is not the first subscription |
| 1136 | # or a subscription of a subclass. |
| 1137 | return super().__getitem__(parameters) |
| 1138 | if parameters == (): |
| 1139 | return super().__getitem__((_TypingEmpty,)) |
| 1140 | if not isinstance(parameters, tuple): |
| 1141 | parameters = (parameters,) |
| 1142 | if len(parameters) == 2 and parameters[1] is ...: |
| 1143 | msg = "Tuple[t, ...]: t must be a type." |
| 1144 | p = _type_check(parameters[0], msg) |
| 1145 | return super().__getitem__((p, _TypingEllipsis)) |
| 1146 | msg = "Tuple[t0, t1, ...]: each t must be a type." |
| 1147 | parameters = tuple(_type_check(p, msg) for p in parameters) |
| 1148 | return super().__getitem__(parameters) |
| 1149 | |
| 1150 | def __instancecheck__(self, obj): |
| 1151 | if self.__args__ == None: |
| 1152 | return isinstance(obj, tuple) |
| 1153 | raise TypeError("Parameterized Tuple cannot be used " |
| 1154 | "with isinstance().") |
| 1155 | |
| 1156 | def __subclasscheck__(self, cls): |
| 1157 | if self.__args__ == None: |
| 1158 | return issubclass(cls, tuple) |
| 1159 | raise TypeError("Parameterized Tuple cannot be used " |
| 1160 | "with issubclass().") |
| 1161 | |
| 1162 | |
| 1163 | class Tuple(tuple, extra=tuple, metaclass=TupleMeta): |
| 1164 | """Tuple type; Tuple[X, Y] is the cross-product type of X and Y. |
| 1165 | |
| 1166 | Example: Tuple[T1, T2] is a tuple of two elements corresponding |
| 1167 | to type variables T1 and T2. Tuple[int, float, str] is a tuple |
| 1168 | of an int, a float and a string. |
| 1169 | |
| 1170 | To specify a variable-length tuple of homogeneous type, use Tuple[T, ...]. |
| 1171 | """ |
| 1172 | |
| 1173 | __slots__ = () |
| 1174 | |
| 1175 | def __new__(cls, *args, **kwds): |
| 1176 | if _geqv(cls, Tuple): |
| 1177 | raise TypeError("Type Tuple cannot be instantiated; " |
| 1178 | "use tuple() instead") |
| 1179 | return _generic_new(tuple, cls, *args, **kwds) |
| 1180 | |
| 1181 | |
| 1182 | class CallableMeta(GenericMeta): |
| 1183 | """ Metaclass for Callable.""" |
| 1184 | |
| 1185 | def __repr__(self): |
| 1186 | if self.__origin__ is None: |
| 1187 | return super().__repr__() |
| 1188 | return self._tree_repr(self._subs_tree()) |
| 1189 | |
| 1190 | def _tree_repr(self, tree): |
| 1191 | if _gorg(self) is not Callable: |
| 1192 | return super()._tree_repr(tree) |
| 1193 | # For actual Callable (not its subclass) we override |
| 1194 | # super()._tree_repr() for nice formatting. |
| 1195 | arg_list = [] |
| 1196 | for arg in tree[1:]: |
| 1197 | if arg == (): |
| 1198 | arg_list.append('[]') |
| 1199 | elif not isinstance(arg, tuple): |
| 1200 | arg_list.append(_type_repr(arg)) |
| 1201 | else: |
| 1202 | arg_list.append(arg[0]._tree_repr(arg)) |
| 1203 | if len(arg_list) == 2: |
| 1204 | return repr(tree[0]) + '[%s]' % ', '.join(arg_list) |
| 1205 | return (repr(tree[0]) + |
| 1206 | '[[%s], %s]' % (', '.join(arg_list[:-1]), arg_list[-1])) |
| 1207 | |
| 1208 | def __getitem__(self, parameters): |
| 1209 | """ A thin wrapper around __getitem_inner__ to provide the latter |
| 1210 | with hashable arguments to improve speed. |
| 1211 | """ |
| 1212 | |
| 1213 | if self.__origin__ is not None or not _geqv(self, Callable): |
| 1214 | return super().__getitem__(parameters) |
| 1215 | if not isinstance(parameters, tuple) or len(parameters) != 2: |
| 1216 | raise TypeError("Callable must be used as " |
| 1217 | "Callable[[arg, ...], result].") |
| 1218 | args, result = parameters |
| 1219 | if args is ...: |
| 1220 | parameters = (..., result) |
| 1221 | elif args == []: |
| 1222 | parameters = ((), result) |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1223 | else: |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1224 | if not isinstance(args, list): |
| 1225 | raise TypeError("Callable[args, result]: args must be a list." |
| 1226 | " Got %.100r." % (args,)) |
| 1227 | parameters = tuple(args) + (result,) |
| 1228 | return self.__getitem_inner__(parameters) |
| 1229 | |
| 1230 | @_tp_cache |
| 1231 | def __getitem_inner__(self, parameters): |
| 1232 | *args, result = parameters |
| 1233 | msg = "Callable[args, result]: result must be a type." |
| 1234 | result = _type_check(result, msg) |
| 1235 | if args == [...,]: |
| 1236 | return super().__getitem__((_TypingEllipsis, result)) |
| 1237 | if args == [(),]: |
| 1238 | return super().__getitem__((_TypingEmpty, result)) |
| 1239 | msg = "Callable[[arg, ...], result]: each arg must be a type." |
| 1240 | args = tuple(_type_check(arg, msg) for arg in args) |
| 1241 | parameters = args + (result,) |
| 1242 | return super().__getitem__(parameters) |
| 1243 | |
| 1244 | |
| 1245 | class Callable(extra=collections_abc.Callable, metaclass = CallableMeta): |
| 1246 | """Callable type; Callable[[int], str] is a function of (int) -> str. |
| 1247 | |
| 1248 | The subscription syntax must always be used with exactly two |
| 1249 | values: the argument list and the return type. The argument list |
| 1250 | must be a list of types; the return type must be a single type. |
| 1251 | |
| 1252 | There is no syntax to indicate optional or keyword arguments, |
| 1253 | such function types are rarely used as callback types. |
| 1254 | """ |
| 1255 | |
| 1256 | __slots__ = () |
| 1257 | |
| 1258 | def __new__(cls, *args, **kwds): |
| 1259 | if _geqv(cls, Callable): |
| 1260 | raise TypeError("Type Callable cannot be instantiated; " |
| 1261 | "use a non-abstract subclass instead") |
| 1262 | return _generic_new(cls.__next_in_mro__, cls, *args, **kwds) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1263 | |
| 1264 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1265 | class _ClassVar(_FinalTypingBase, _root=True): |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1266 | """Special type construct to mark class variables. |
| 1267 | |
| 1268 | An annotation wrapped in ClassVar indicates that a given |
| 1269 | attribute is intended to be used as a class variable and |
| 1270 | should not be set on instances of that class. Usage:: |
| 1271 | |
| 1272 | class Starship: |
| 1273 | stats: ClassVar[Dict[str, int]] = {} # class variable |
| 1274 | damage: int = 10 # instance variable |
| 1275 | |
| 1276 | ClassVar accepts only types and cannot be further subscribed. |
| 1277 | |
| 1278 | Note that ClassVar is not a class itself, and should not |
| 1279 | be used with isinstance() or issubclass(). |
| 1280 | """ |
| 1281 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1282 | __slots__ = ('__type__',) |
| 1283 | |
| 1284 | def __init__(self, tp=None, **kwds): |
| 1285 | self.__type__ = tp |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1286 | |
| 1287 | def __getitem__(self, item): |
| 1288 | cls = type(self) |
| 1289 | if self.__type__ is None: |
| 1290 | return cls(_type_check(item, |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1291 | '{} accepts only single type.'.format(cls.__name__[1:])), |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1292 | _root=True) |
| 1293 | raise TypeError('{} cannot be further subscripted' |
| 1294 | .format(cls.__name__[1:])) |
| 1295 | |
| 1296 | def _eval_type(self, globalns, localns): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1297 | new_tp = _eval_type(self.__type__, globalns, localns) |
| 1298 | if new_tp == self.__type__: |
| 1299 | return self |
| 1300 | return type(self)(new_tp, _root=True) |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1301 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1302 | def __repr__(self): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1303 | r = super().__repr__() |
| 1304 | if self.__type__ is not None: |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1305 | r += '[{}]'.format(_type_repr(self.__type__)) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1306 | return r |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1307 | |
| 1308 | def __hash__(self): |
| 1309 | return hash((type(self).__name__, self.__type__)) |
| 1310 | |
| 1311 | def __eq__(self, other): |
| 1312 | if not isinstance(other, _ClassVar): |
| 1313 | return NotImplemented |
| 1314 | if self.__type__ is not None: |
| 1315 | return self.__type__ == other.__type__ |
| 1316 | return self is other |
| 1317 | |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1318 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1319 | ClassVar = _ClassVar(_root=True) |
| 1320 | |
| 1321 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1322 | def cast(typ, val): |
| 1323 | """Cast a value to a type. |
| 1324 | |
| 1325 | This returns the value unchanged. To the type checker this |
| 1326 | signals that the return value has the designated type, but at |
| 1327 | runtime we intentionally don't check anything (we want this |
| 1328 | to be as fast as possible). |
| 1329 | """ |
| 1330 | return val |
| 1331 | |
| 1332 | |
| 1333 | def _get_defaults(func): |
| 1334 | """Internal helper to extract the default arguments, by name.""" |
| 1335 | code = func.__code__ |
| 1336 | pos_count = code.co_argcount |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1337 | arg_names = code.co_varnames |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1338 | arg_names = arg_names[:pos_count] |
| 1339 | defaults = func.__defaults__ or () |
| 1340 | kwdefaults = func.__kwdefaults__ |
| 1341 | res = dict(kwdefaults) if kwdefaults else {} |
| 1342 | pos_offset = pos_count - len(defaults) |
| 1343 | for name, value in zip(arg_names[pos_offset:], defaults): |
| 1344 | assert name not in res |
| 1345 | res[name] = value |
| 1346 | return res |
| 1347 | |
| 1348 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1349 | if sys.version_info[:2] >= (3, 3): |
| 1350 | def get_type_hints(obj, globalns=None, localns=None): |
| 1351 | """Return type hints for an object. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1352 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1353 | This is often the same as obj.__annotations__, but it handles |
| 1354 | forward references encoded as string literals, and if necessary |
| 1355 | 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] | 1356 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1357 | The argument may be a module, class, method, or function. The annotations |
| 1358 | are returned as a dictionary, or in the case of a class, a ChainMap of |
| 1359 | dictionaries. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1360 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1361 | TypeError is raised if the argument is not of a type that can contain |
| 1362 | annotations, and an empty dictionary is returned if no annotations are |
| 1363 | present. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1364 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1365 | BEWARE -- the behavior of globalns and localns is counterintuitive |
| 1366 | (unless you are familiar with how eval() and exec() work). The |
| 1367 | search order is locals first, then globals. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1368 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1369 | - If no dict arguments are passed, an attempt is made to use the |
| 1370 | globals from obj, and these are also used as the locals. If the |
| 1371 | object does not appear to have globals, an exception is raised. |
| 1372 | |
| 1373 | - If one dict argument is passed, it is used for both globals and |
| 1374 | locals. |
| 1375 | |
| 1376 | - If two dict arguments are passed, they specify globals and |
| 1377 | locals, respectively. |
| 1378 | """ |
| 1379 | |
| 1380 | if getattr(obj, '__no_type_check__', None): |
| 1381 | return {} |
| 1382 | if globalns is None: |
| 1383 | globalns = getattr(obj, '__globals__', {}) |
| 1384 | if localns is None: |
| 1385 | localns = globalns |
| 1386 | elif localns is None: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1387 | localns = globalns |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1388 | |
| 1389 | if (isinstance(obj, types.FunctionType) or |
| 1390 | isinstance(obj, types.BuiltinFunctionType) or |
| 1391 | isinstance(obj, types.MethodType)): |
| 1392 | defaults = _get_defaults(obj) |
| 1393 | hints = obj.__annotations__ |
| 1394 | for name, value in hints.items(): |
| 1395 | if value is None: |
| 1396 | value = type(None) |
| 1397 | if isinstance(value, str): |
| 1398 | value = _ForwardRef(value) |
| 1399 | value = _eval_type(value, globalns, localns) |
| 1400 | if name in defaults and defaults[name] is None: |
| 1401 | value = Optional[value] |
| 1402 | hints[name] = value |
| 1403 | return hints |
| 1404 | |
| 1405 | if isinstance(obj, types.ModuleType): |
| 1406 | try: |
| 1407 | hints = obj.__annotations__ |
| 1408 | except AttributeError: |
| 1409 | return {} |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1410 | for name, value in hints.items(): |
| 1411 | if value is None: |
| 1412 | value = type(None) |
| 1413 | if isinstance(value, str): |
| 1414 | value = _ForwardRef(value) |
| 1415 | value = _eval_type(value, globalns, localns) |
| 1416 | hints[name] = value |
| 1417 | return hints |
| 1418 | |
| 1419 | if isinstance(object, type): |
| 1420 | cmap = None |
| 1421 | for base in reversed(obj.__mro__): |
| 1422 | new_map = collections.ChainMap if cmap is None else cmap.new_child |
| 1423 | try: |
| 1424 | hints = base.__dict__['__annotations__'] |
| 1425 | except KeyError: |
| 1426 | cmap = new_map() |
| 1427 | else: |
| 1428 | for name, value in hints.items(): |
| 1429 | if value is None: |
| 1430 | value = type(None) |
| 1431 | if isinstance(value, str): |
| 1432 | value = _ForwardRef(value) |
| 1433 | value = _eval_type(value, globalns, localns) |
| 1434 | hints[name] = value |
| 1435 | cmap = new_map(hints) |
| 1436 | return cmap |
| 1437 | |
| 1438 | raise TypeError('{!r} is not a module, class, method, ' |
| 1439 | 'or function.'.format(obj)) |
| 1440 | |
| 1441 | else: |
| 1442 | def get_type_hints(obj, globalns=None, localns=None): |
| 1443 | """Return type hints for a function or method object. |
| 1444 | |
| 1445 | This is often the same as obj.__annotations__, but it handles |
| 1446 | forward references encoded as string literals, and if necessary |
| 1447 | adds Optional[t] if a default value equal to None is set. |
| 1448 | |
| 1449 | BEWARE -- the behavior of globalns and localns is counterintuitive |
| 1450 | (unless you are familiar with how eval() and exec() work). The |
| 1451 | search order is locals first, then globals. |
| 1452 | |
| 1453 | - If no dict arguments are passed, an attempt is made to use the |
| 1454 | globals from obj, and these are also used as the locals. If the |
| 1455 | object does not appear to have globals, an exception is raised. |
| 1456 | |
| 1457 | - If one dict argument is passed, it is used for both globals and |
| 1458 | locals. |
| 1459 | |
| 1460 | - If two dict arguments are passed, they specify globals and |
| 1461 | locals, respectively. |
| 1462 | """ |
| 1463 | if getattr(obj, '__no_type_check__', None): |
| 1464 | return {} |
| 1465 | if globalns is None: |
| 1466 | globalns = getattr(obj, '__globals__', {}) |
| 1467 | if localns is None: |
| 1468 | localns = globalns |
| 1469 | elif localns is None: |
| 1470 | localns = globalns |
| 1471 | defaults = _get_defaults(obj) |
| 1472 | hints = dict(obj.__annotations__) |
| 1473 | for name, value in hints.items(): |
| 1474 | if isinstance(value, str): |
| 1475 | value = _ForwardRef(value) |
| 1476 | value = _eval_type(value, globalns, localns) |
| 1477 | if name in defaults and defaults[name] is None: |
| 1478 | value = Optional[value] |
| 1479 | hints[name] = value |
| 1480 | return hints |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1481 | |
| 1482 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1483 | def no_type_check(arg): |
| 1484 | """Decorator to indicate that annotations are not type hints. |
| 1485 | |
| 1486 | 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] | 1487 | applies recursively to all methods and classes defined in that class |
| 1488 | (but not to methods defined in its superclasses or subclasses). |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1489 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1490 | This mutates the function(s) or class(es) in place. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1491 | """ |
| 1492 | if isinstance(arg, type): |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1493 | arg_attrs = arg.__dict__.copy() |
| 1494 | for attr, val in arg.__dict__.items(): |
| 1495 | if val in arg.__bases__: |
| 1496 | arg_attrs.pop(attr) |
| 1497 | for obj in arg_attrs.values(): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1498 | if isinstance(obj, types.FunctionType): |
| 1499 | obj.__no_type_check__ = True |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1500 | if isinstance(obj, type): |
| 1501 | no_type_check(obj) |
| 1502 | try: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1503 | arg.__no_type_check__ = True |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1504 | except TypeError: # built-in classes |
| 1505 | pass |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1506 | return arg |
| 1507 | |
| 1508 | |
| 1509 | def no_type_check_decorator(decorator): |
| 1510 | """Decorator to give another decorator the @no_type_check effect. |
| 1511 | |
| 1512 | This wraps the decorator with something that wraps the decorated |
| 1513 | function in @no_type_check. |
| 1514 | """ |
| 1515 | |
| 1516 | @functools.wraps(decorator) |
| 1517 | def wrapped_decorator(*args, **kwds): |
| 1518 | func = decorator(*args, **kwds) |
| 1519 | func = no_type_check(func) |
| 1520 | return func |
| 1521 | |
| 1522 | return wrapped_decorator |
| 1523 | |
| 1524 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1525 | def _overload_dummy(*args, **kwds): |
| 1526 | """Helper for @overload to raise when called.""" |
| 1527 | raise NotImplementedError( |
| 1528 | "You should not call an overloaded function. " |
| 1529 | "A series of @overload-decorated functions " |
| 1530 | "outside a stub module should always be followed " |
| 1531 | "by an implementation that is not @overload-ed.") |
| 1532 | |
| 1533 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1534 | def overload(func): |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1535 | """Decorator for overloaded functions/methods. |
| 1536 | |
| 1537 | In a stub file, place two or more stub definitions for the same |
| 1538 | function in a row, each decorated with @overload. For example: |
| 1539 | |
| 1540 | @overload |
| 1541 | def utf8(value: None) -> None: ... |
| 1542 | @overload |
| 1543 | def utf8(value: bytes) -> bytes: ... |
| 1544 | @overload |
| 1545 | def utf8(value: str) -> bytes: ... |
| 1546 | |
| 1547 | In a non-stub file (i.e. a regular .py file), do the same but |
| 1548 | follow it with an implementation. The implementation should *not* |
| 1549 | be decorated with @overload. For example: |
| 1550 | |
| 1551 | @overload |
| 1552 | def utf8(value: None) -> None: ... |
| 1553 | @overload |
| 1554 | def utf8(value: bytes) -> bytes: ... |
| 1555 | @overload |
| 1556 | def utf8(value: str) -> bytes: ... |
| 1557 | def utf8(value): |
| 1558 | # implementation goes here |
| 1559 | """ |
| 1560 | return _overload_dummy |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1561 | |
| 1562 | |
| 1563 | class _ProtocolMeta(GenericMeta): |
| 1564 | """Internal metaclass for _Protocol. |
| 1565 | |
| 1566 | This exists so _Protocol classes can be generic without deriving |
| 1567 | from Generic. |
| 1568 | """ |
| 1569 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1570 | def __instancecheck__(self, obj): |
| 1571 | raise TypeError("Protocols cannot be used with isinstance().") |
| 1572 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1573 | def __subclasscheck__(self, cls): |
| 1574 | if not self._is_protocol: |
| 1575 | # No structural checks since this isn't a protocol. |
| 1576 | return NotImplemented |
| 1577 | |
| 1578 | if self is _Protocol: |
| 1579 | # Every class is a subclass of the empty protocol. |
| 1580 | return True |
| 1581 | |
| 1582 | # Find all attributes defined in the protocol. |
| 1583 | attrs = self._get_protocol_attrs() |
| 1584 | |
| 1585 | for attr in attrs: |
| 1586 | if not any(attr in d.__dict__ for d in cls.__mro__): |
| 1587 | return False |
| 1588 | return True |
| 1589 | |
| 1590 | def _get_protocol_attrs(self): |
| 1591 | # Get all Protocol base classes. |
| 1592 | protocol_bases = [] |
| 1593 | for c in self.__mro__: |
| 1594 | if getattr(c, '_is_protocol', False) and c.__name__ != '_Protocol': |
| 1595 | protocol_bases.append(c) |
| 1596 | |
| 1597 | # Get attributes included in protocol. |
| 1598 | attrs = set() |
| 1599 | for base in protocol_bases: |
| 1600 | for attr in base.__dict__.keys(): |
| 1601 | # Include attributes not defined in any non-protocol bases. |
| 1602 | for c in self.__mro__: |
| 1603 | if (c is not base and attr in c.__dict__ and |
| 1604 | not getattr(c, '_is_protocol', False)): |
| 1605 | break |
| 1606 | else: |
| 1607 | if (not attr.startswith('_abc_') and |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1608 | attr != '__abstractmethods__' and |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1609 | attr != '__annotations__' and |
| 1610 | attr != '__weakref__' and |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1611 | attr != '_is_protocol' and |
| 1612 | attr != '__dict__' and |
| 1613 | attr != '__args__' and |
| 1614 | attr != '__slots__' and |
| 1615 | attr != '_get_protocol_attrs' and |
| 1616 | attr != '__next_in_mro__' and |
| 1617 | attr != '__parameters__' and |
| 1618 | attr != '__origin__' and |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 1619 | attr != '__orig_bases__' and |
Guido van Rossum | 1cea70f | 2016-05-18 08:35:00 -0700 | [diff] [blame] | 1620 | attr != '__extra__' and |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1621 | attr != '__tree_hash__' and |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1622 | attr != '__module__'): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1623 | attrs.add(attr) |
| 1624 | |
| 1625 | return attrs |
| 1626 | |
| 1627 | |
| 1628 | class _Protocol(metaclass=_ProtocolMeta): |
| 1629 | """Internal base class for protocol classes. |
| 1630 | |
| 1631 | This implements a simple-minded structural isinstance check |
| 1632 | (similar but more general than the one-offs in collections.abc |
| 1633 | such as Hashable). |
| 1634 | """ |
| 1635 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1636 | __slots__ = () |
| 1637 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1638 | _is_protocol = True |
| 1639 | |
| 1640 | |
| 1641 | # Various ABCs mimicking those in collections.abc. |
| 1642 | # A few are simply re-exported for completeness. |
| 1643 | |
| 1644 | Hashable = collections_abc.Hashable # Not generic. |
| 1645 | |
| 1646 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1647 | if hasattr(collections_abc, 'Awaitable'): |
| 1648 | class Awaitable(Generic[T_co], extra=collections_abc.Awaitable): |
| 1649 | __slots__ = () |
Guido van Rossum | 62fe1bb | 2016-10-29 16:05:26 -0700 | [diff] [blame^] | 1650 | |
| 1651 | __all__.append('Awaitable') |
| 1652 | |
| 1653 | |
| 1654 | if hasattr(collections_abc, 'Coroutine'): |
| 1655 | class Coroutine(Awaitable[V_co], Generic[T_co, T_contra, V_co], |
| 1656 | extra=collections_abc.Coroutine): |
| 1657 | __slots__ = () |
| 1658 | |
| 1659 | __all__.append('Coroutine') |
Guido van Rossum | f17c200 | 2015-12-03 17:31:24 -0800 | [diff] [blame] | 1660 | |
| 1661 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1662 | if hasattr(collections_abc, 'AsyncIterable'): |
Guido van Rossum | f17c200 | 2015-12-03 17:31:24 -0800 | [diff] [blame] | 1663 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1664 | class AsyncIterable(Generic[T_co], extra=collections_abc.AsyncIterable): |
| 1665 | __slots__ = () |
Guido van Rossum | f17c200 | 2015-12-03 17:31:24 -0800 | [diff] [blame] | 1666 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1667 | class AsyncIterator(AsyncIterable[T_co], |
| 1668 | extra=collections_abc.AsyncIterator): |
| 1669 | __slots__ = () |
| 1670 | |
Guido van Rossum | 62fe1bb | 2016-10-29 16:05:26 -0700 | [diff] [blame^] | 1671 | __all__.append('AsyncIterable') |
| 1672 | __all__.append('AsyncIterator') |
Guido van Rossum | f17c200 | 2015-12-03 17:31:24 -0800 | [diff] [blame] | 1673 | |
| 1674 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1675 | class Iterable(Generic[T_co], extra=collections_abc.Iterable): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1676 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1677 | |
| 1678 | |
| 1679 | class Iterator(Iterable[T_co], extra=collections_abc.Iterator): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1680 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1681 | |
| 1682 | |
| 1683 | class SupportsInt(_Protocol): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1684 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1685 | |
| 1686 | @abstractmethod |
| 1687 | def __int__(self) -> int: |
| 1688 | pass |
| 1689 | |
| 1690 | |
| 1691 | class SupportsFloat(_Protocol): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1692 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1693 | |
| 1694 | @abstractmethod |
| 1695 | def __float__(self) -> float: |
| 1696 | pass |
| 1697 | |
| 1698 | |
| 1699 | class SupportsComplex(_Protocol): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1700 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1701 | |
| 1702 | @abstractmethod |
| 1703 | def __complex__(self) -> complex: |
| 1704 | pass |
| 1705 | |
| 1706 | |
| 1707 | class SupportsBytes(_Protocol): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1708 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1709 | |
| 1710 | @abstractmethod |
| 1711 | def __bytes__(self) -> bytes: |
| 1712 | pass |
| 1713 | |
| 1714 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1715 | class SupportsAbs(_Protocol[T_co]): |
| 1716 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1717 | |
| 1718 | @abstractmethod |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1719 | def __abs__(self) -> T_co: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1720 | pass |
| 1721 | |
| 1722 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1723 | class SupportsRound(_Protocol[T_co]): |
| 1724 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1725 | |
| 1726 | @abstractmethod |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1727 | def __round__(self, ndigits: int = 0) -> T_co: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1728 | pass |
| 1729 | |
| 1730 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1731 | if hasattr(collections_abc, 'Reversible'): |
| 1732 | class Reversible(Iterable[T_co], extra=collections_abc.Reversible): |
| 1733 | __slots__ = () |
| 1734 | else: |
| 1735 | class Reversible(_Protocol[T_co]): |
| 1736 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1737 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1738 | @abstractmethod |
| 1739 | def __reversed__(self) -> 'Iterator[T_co]': |
| 1740 | pass |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1741 | |
| 1742 | |
| 1743 | Sized = collections_abc.Sized # Not generic. |
| 1744 | |
| 1745 | |
| 1746 | class Container(Generic[T_co], extra=collections_abc.Container): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1747 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1748 | |
| 1749 | |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1750 | if hasattr(collections_abc, 'Collection'): |
| 1751 | class Collection(Sized, Iterable[T_co], Container[T_co], |
| 1752 | extra=collections_abc.Collection): |
| 1753 | __slots__ = () |
| 1754 | |
| 1755 | __all__.append('Collection') |
| 1756 | |
| 1757 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1758 | # Callable was defined earlier. |
| 1759 | |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1760 | if hasattr(collections_abc, 'Collection'): |
| 1761 | class AbstractSet(Collection[T_co], |
| 1762 | extra=collections_abc.Set): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1763 | __slots__ = () |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1764 | else: |
| 1765 | class AbstractSet(Sized, Iterable[T_co], Container[T_co], |
| 1766 | extra=collections_abc.Set): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1767 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1768 | |
| 1769 | |
| 1770 | class MutableSet(AbstractSet[T], extra=collections_abc.MutableSet): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1771 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1772 | |
| 1773 | |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1774 | # NOTE: It is only covariant in the value type. |
| 1775 | if hasattr(collections_abc, 'Collection'): |
| 1776 | class Mapping(Collection[KT], Generic[KT, VT_co], |
| 1777 | extra=collections_abc.Mapping): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1778 | __slots__ = () |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1779 | else: |
| 1780 | class Mapping(Sized, Iterable[KT], Container[KT], Generic[KT, VT_co], |
| 1781 | extra=collections_abc.Mapping): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1782 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1783 | |
| 1784 | |
| 1785 | class MutableMapping(Mapping[KT, VT], extra=collections_abc.MutableMapping): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1786 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1787 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1788 | if hasattr(collections_abc, 'Reversible'): |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1789 | if hasattr(collections_abc, 'Collection'): |
| 1790 | class Sequence(Reversible[T_co], Collection[T_co], |
| 1791 | extra=collections_abc.Sequence): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1792 | __slots__ = () |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1793 | else: |
| 1794 | class Sequence(Sized, Reversible[T_co], Container[T_co], |
| 1795 | extra=collections_abc.Sequence): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1796 | __slots__ = () |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1797 | else: |
| 1798 | class Sequence(Sized, Iterable[T_co], Container[T_co], |
| 1799 | extra=collections_abc.Sequence): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1800 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1801 | |
| 1802 | |
| 1803 | class MutableSequence(Sequence[T], extra=collections_abc.MutableSequence): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1804 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1805 | |
| 1806 | |
| 1807 | class ByteString(Sequence[int], extra=collections_abc.ByteString): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1808 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1809 | |
| 1810 | |
Guido van Rossum | 1cea70f | 2016-05-18 08:35:00 -0700 | [diff] [blame] | 1811 | class List(list, MutableSequence[T], extra=list): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1812 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1813 | __slots__ = () |
| 1814 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1815 | def __new__(cls, *args, **kwds): |
| 1816 | if _geqv(cls, List): |
| 1817 | raise TypeError("Type List cannot be instantiated; " |
| 1818 | "use list() instead") |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1819 | return _generic_new(list, cls, *args, **kwds) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1820 | |
| 1821 | |
Guido van Rossum | 1cea70f | 2016-05-18 08:35:00 -0700 | [diff] [blame] | 1822 | class Set(set, MutableSet[T], extra=set): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1823 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1824 | __slots__ = () |
| 1825 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1826 | def __new__(cls, *args, **kwds): |
| 1827 | if _geqv(cls, Set): |
| 1828 | raise TypeError("Type Set cannot be instantiated; " |
| 1829 | "use set() instead") |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1830 | return _generic_new(set, cls, *args, **kwds) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1831 | |
| 1832 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1833 | class FrozenSet(frozenset, AbstractSet[T_co], extra=frozenset): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1834 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1835 | |
| 1836 | def __new__(cls, *args, **kwds): |
| 1837 | if _geqv(cls, FrozenSet): |
| 1838 | raise TypeError("Type FrozenSet cannot be instantiated; " |
| 1839 | "use frozenset() instead") |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1840 | return _generic_new(frozenset, cls, *args, **kwds) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1841 | |
| 1842 | |
| 1843 | class MappingView(Sized, Iterable[T_co], extra=collections_abc.MappingView): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1844 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1845 | |
| 1846 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1847 | class KeysView(MappingView[KT], AbstractSet[KT], |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1848 | extra=collections_abc.KeysView): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1849 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1850 | |
| 1851 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1852 | class ItemsView(MappingView[Tuple[KT, VT_co]], |
Guido van Rossum | 0e0563c | 2016-04-05 14:54:25 -0700 | [diff] [blame] | 1853 | AbstractSet[Tuple[KT, VT_co]], |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1854 | Generic[KT, VT_co], |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1855 | extra=collections_abc.ItemsView): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1856 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1857 | |
| 1858 | |
| 1859 | class ValuesView(MappingView[VT_co], extra=collections_abc.ValuesView): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1860 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1861 | |
| 1862 | |
Brett Cannon | f3ad042 | 2016-04-15 10:51:30 -0700 | [diff] [blame] | 1863 | if hasattr(contextlib, 'AbstractContextManager'): |
| 1864 | class ContextManager(Generic[T_co], extra=contextlib.AbstractContextManager): |
| 1865 | __slots__ = () |
| 1866 | __all__.append('ContextManager') |
| 1867 | |
| 1868 | |
Guido van Rossum | 1cea70f | 2016-05-18 08:35:00 -0700 | [diff] [blame] | 1869 | class Dict(dict, MutableMapping[KT, VT], extra=dict): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1870 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1871 | __slots__ = () |
| 1872 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1873 | def __new__(cls, *args, **kwds): |
| 1874 | if _geqv(cls, Dict): |
| 1875 | raise TypeError("Type Dict cannot be instantiated; " |
| 1876 | "use dict() instead") |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1877 | return _generic_new(dict, cls, *args, **kwds) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1878 | |
Guido van Rossum | 1cea70f | 2016-05-18 08:35:00 -0700 | [diff] [blame] | 1879 | class DefaultDict(collections.defaultdict, MutableMapping[KT, VT], |
| 1880 | extra=collections.defaultdict): |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1881 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1882 | __slots__ = () |
| 1883 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1884 | def __new__(cls, *args, **kwds): |
| 1885 | if _geqv(cls, DefaultDict): |
| 1886 | raise TypeError("Type DefaultDict cannot be instantiated; " |
| 1887 | "use collections.defaultdict() instead") |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1888 | return _generic_new(collections.defaultdict, cls, *args, **kwds) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1889 | |
| 1890 | # Determine what base class to use for Generator. |
| 1891 | if hasattr(collections_abc, 'Generator'): |
| 1892 | # Sufficiently recent versions of 3.5 have a Generator ABC. |
| 1893 | _G_base = collections_abc.Generator |
| 1894 | else: |
| 1895 | # Fall back on the exact type. |
| 1896 | _G_base = types.GeneratorType |
| 1897 | |
| 1898 | |
| 1899 | class Generator(Iterator[T_co], Generic[T_co, T_contra, V_co], |
| 1900 | extra=_G_base): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1901 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1902 | |
| 1903 | def __new__(cls, *args, **kwds): |
| 1904 | if _geqv(cls, Generator): |
| 1905 | raise TypeError("Type Generator cannot be instantiated; " |
| 1906 | "create a subclass instead") |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1907 | return _generic_new(_G_base, cls, *args, **kwds) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1908 | |
| 1909 | |
Guido van Rossum | eb9aca3 | 2016-05-24 16:38:22 -0700 | [diff] [blame] | 1910 | # Internal type variable used for Type[]. |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1911 | CT_co = TypeVar('CT_co', covariant=True, bound=type) |
Guido van Rossum | eb9aca3 | 2016-05-24 16:38:22 -0700 | [diff] [blame] | 1912 | |
| 1913 | |
Guido van Rossum | b22c708 | 2016-05-26 09:56:19 -0700 | [diff] [blame] | 1914 | # This is not a real generic class. Don't use outside annotations. |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1915 | class Type(Generic[CT_co], extra=type): |
Guido van Rossum | b22c708 | 2016-05-26 09:56:19 -0700 | [diff] [blame] | 1916 | """A special construct usable to annotate class objects. |
Guido van Rossum | eb9aca3 | 2016-05-24 16:38:22 -0700 | [diff] [blame] | 1917 | |
| 1918 | For example, suppose we have the following classes:: |
| 1919 | |
| 1920 | class User: ... # Abstract base for User classes |
| 1921 | class BasicUser(User): ... |
| 1922 | class ProUser(User): ... |
| 1923 | class TeamUser(User): ... |
| 1924 | |
| 1925 | And a function that takes a class argument that's a subclass of |
| 1926 | User and returns an instance of the corresponding class:: |
| 1927 | |
| 1928 | U = TypeVar('U', bound=User) |
| 1929 | def new_user(user_class: Type[U]) -> U: |
| 1930 | user = user_class() |
| 1931 | # (Here we could write the user object to a database) |
| 1932 | return user |
| 1933 | |
| 1934 | joe = new_user(BasicUser) |
| 1935 | |
| 1936 | At this point the type checker knows that joe has type BasicUser. |
| 1937 | """ |
| 1938 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1939 | __slots__ = () |
| 1940 | |
Guido van Rossum | eb9aca3 | 2016-05-24 16:38:22 -0700 | [diff] [blame] | 1941 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1942 | def _make_nmtuple(name, types): |
| 1943 | nm_tpl = collections.namedtuple(name, [n for n, t in types]) |
| 1944 | nm_tpl._field_types = dict(types) |
Guido van Rossum | 557d1eb | 2015-11-19 08:16:31 -0800 | [diff] [blame] | 1945 | try: |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1946 | nm_tpl.__module__ = sys._getframe(2).f_globals.get('__name__', '__main__') |
Guido van Rossum | 557d1eb | 2015-11-19 08:16:31 -0800 | [diff] [blame] | 1947 | except (AttributeError, ValueError): |
| 1948 | pass |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1949 | return nm_tpl |
| 1950 | |
| 1951 | |
| 1952 | if sys.version_info[:2] >= (3, 6): |
| 1953 | class NamedTupleMeta(type): |
| 1954 | |
| 1955 | def __new__(cls, typename, bases, ns, *, _root=False): |
| 1956 | if _root: |
| 1957 | return super().__new__(cls, typename, bases, ns) |
| 1958 | types = ns.get('__annotations__', {}) |
| 1959 | return _make_nmtuple(typename, types.items()) |
| 1960 | |
| 1961 | class NamedTuple(metaclass=NamedTupleMeta, _root=True): |
| 1962 | """Typed version of namedtuple. |
| 1963 | |
| 1964 | Usage:: |
| 1965 | |
| 1966 | class Employee(NamedTuple): |
| 1967 | name: str |
| 1968 | id: int |
| 1969 | |
| 1970 | This is equivalent to:: |
| 1971 | |
| 1972 | Employee = collections.namedtuple('Employee', ['name', 'id']) |
| 1973 | |
| 1974 | The resulting class has one extra attribute: _field_types, |
| 1975 | giving a dict mapping field names to types. (The field names |
| 1976 | are in the _fields attribute, which is part of the namedtuple |
| 1977 | API.) Backward-compatible usage:: |
| 1978 | |
| 1979 | Employee = NamedTuple('Employee', [('name', str), ('id', int)]) |
| 1980 | """ |
| 1981 | |
| 1982 | def __new__(self, typename, fields): |
| 1983 | return _make_nmtuple(typename, fields) |
| 1984 | else: |
| 1985 | def NamedTuple(typename, fields): |
| 1986 | """Typed version of namedtuple. |
| 1987 | |
| 1988 | Usage:: |
| 1989 | |
| 1990 | Employee = typing.NamedTuple('Employee', [('name', str), 'id', int)]) |
| 1991 | |
| 1992 | This is equivalent to:: |
| 1993 | |
| 1994 | Employee = collections.namedtuple('Employee', ['name', 'id']) |
| 1995 | |
| 1996 | The resulting class has one extra attribute: _field_types, |
| 1997 | giving a dict mapping field names to types. (The field names |
| 1998 | are in the _fields attribute, which is part of the namedtuple |
| 1999 | API.) |
| 2000 | """ |
| 2001 | return _make_nmtuple(typename, fields) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2002 | |
| 2003 | |
Guido van Rossum | 91185fe | 2016-06-08 11:19:11 -0700 | [diff] [blame] | 2004 | def NewType(name, tp): |
| 2005 | """NewType creates simple unique types with almost zero |
| 2006 | runtime overhead. NewType(name, tp) is considered a subtype of tp |
| 2007 | by static type checkers. At runtime, NewType(name, tp) returns |
| 2008 | a dummy function that simply returns its argument. Usage:: |
| 2009 | |
| 2010 | UserId = NewType('UserId', int) |
| 2011 | |
| 2012 | def name_by_id(user_id: UserId) -> str: |
| 2013 | ... |
| 2014 | |
| 2015 | UserId('user') # Fails type check |
| 2016 | |
| 2017 | name_by_id(42) # Fails type check |
| 2018 | name_by_id(UserId(42)) # OK |
| 2019 | |
| 2020 | num = UserId(5) + 1 # type: int |
| 2021 | """ |
| 2022 | |
| 2023 | def new_type(x): |
| 2024 | return x |
| 2025 | |
| 2026 | new_type.__name__ = name |
| 2027 | new_type.__supertype__ = tp |
| 2028 | return new_type |
| 2029 | |
| 2030 | |
Guido van Rossum | 0e0563c | 2016-04-05 14:54:25 -0700 | [diff] [blame] | 2031 | # Python-version-specific alias (Python 2: unicode; Python 3: str) |
| 2032 | Text = str |
| 2033 | |
| 2034 | |
Guido van Rossum | 91185fe | 2016-06-08 11:19:11 -0700 | [diff] [blame] | 2035 | # Constant that's True when type checking, but False here. |
| 2036 | TYPE_CHECKING = False |
| 2037 | |
| 2038 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2039 | class IO(Generic[AnyStr]): |
| 2040 | """Generic base class for TextIO and BinaryIO. |
| 2041 | |
| 2042 | This is an abstract, generic version of the return of open(). |
| 2043 | |
| 2044 | NOTE: This does not distinguish between the different possible |
| 2045 | classes (text vs. binary, read vs. write vs. read/write, |
| 2046 | append-only, unbuffered). The TextIO and BinaryIO subclasses |
| 2047 | below capture the distinctions between text vs. binary, which is |
| 2048 | pervasive in the interface; however we currently do not offer a |
| 2049 | way to track the other distinctions in the type system. |
| 2050 | """ |
| 2051 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 2052 | __slots__ = () |
| 2053 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2054 | @abstractproperty |
| 2055 | def mode(self) -> str: |
| 2056 | pass |
| 2057 | |
| 2058 | @abstractproperty |
| 2059 | def name(self) -> str: |
| 2060 | pass |
| 2061 | |
| 2062 | @abstractmethod |
| 2063 | def close(self) -> None: |
| 2064 | pass |
| 2065 | |
| 2066 | @abstractmethod |
| 2067 | def closed(self) -> bool: |
| 2068 | pass |
| 2069 | |
| 2070 | @abstractmethod |
| 2071 | def fileno(self) -> int: |
| 2072 | pass |
| 2073 | |
| 2074 | @abstractmethod |
| 2075 | def flush(self) -> None: |
| 2076 | pass |
| 2077 | |
| 2078 | @abstractmethod |
| 2079 | def isatty(self) -> bool: |
| 2080 | pass |
| 2081 | |
| 2082 | @abstractmethod |
| 2083 | def read(self, n: int = -1) -> AnyStr: |
| 2084 | pass |
| 2085 | |
| 2086 | @abstractmethod |
| 2087 | def readable(self) -> bool: |
| 2088 | pass |
| 2089 | |
| 2090 | @abstractmethod |
| 2091 | def readline(self, limit: int = -1) -> AnyStr: |
| 2092 | pass |
| 2093 | |
| 2094 | @abstractmethod |
| 2095 | def readlines(self, hint: int = -1) -> List[AnyStr]: |
| 2096 | pass |
| 2097 | |
| 2098 | @abstractmethod |
| 2099 | def seek(self, offset: int, whence: int = 0) -> int: |
| 2100 | pass |
| 2101 | |
| 2102 | @abstractmethod |
| 2103 | def seekable(self) -> bool: |
| 2104 | pass |
| 2105 | |
| 2106 | @abstractmethod |
| 2107 | def tell(self) -> int: |
| 2108 | pass |
| 2109 | |
| 2110 | @abstractmethod |
| 2111 | def truncate(self, size: int = None) -> int: |
| 2112 | pass |
| 2113 | |
| 2114 | @abstractmethod |
| 2115 | def writable(self) -> bool: |
| 2116 | pass |
| 2117 | |
| 2118 | @abstractmethod |
| 2119 | def write(self, s: AnyStr) -> int: |
| 2120 | pass |
| 2121 | |
| 2122 | @abstractmethod |
| 2123 | def writelines(self, lines: List[AnyStr]) -> None: |
| 2124 | pass |
| 2125 | |
| 2126 | @abstractmethod |
| 2127 | def __enter__(self) -> 'IO[AnyStr]': |
| 2128 | pass |
| 2129 | |
| 2130 | @abstractmethod |
| 2131 | def __exit__(self, type, value, traceback) -> None: |
| 2132 | pass |
| 2133 | |
| 2134 | |
| 2135 | class BinaryIO(IO[bytes]): |
| 2136 | """Typed version of the return of open() in binary mode.""" |
| 2137 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 2138 | __slots__ = () |
| 2139 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2140 | @abstractmethod |
| 2141 | def write(self, s: Union[bytes, bytearray]) -> int: |
| 2142 | pass |
| 2143 | |
| 2144 | @abstractmethod |
| 2145 | def __enter__(self) -> 'BinaryIO': |
| 2146 | pass |
| 2147 | |
| 2148 | |
| 2149 | class TextIO(IO[str]): |
| 2150 | """Typed version of the return of open() in text mode.""" |
| 2151 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 2152 | __slots__ = () |
| 2153 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2154 | @abstractproperty |
| 2155 | def buffer(self) -> BinaryIO: |
| 2156 | pass |
| 2157 | |
| 2158 | @abstractproperty |
| 2159 | def encoding(self) -> str: |
| 2160 | pass |
| 2161 | |
| 2162 | @abstractproperty |
| 2163 | def errors(self) -> str: |
| 2164 | pass |
| 2165 | |
| 2166 | @abstractproperty |
| 2167 | def line_buffering(self) -> bool: |
| 2168 | pass |
| 2169 | |
| 2170 | @abstractproperty |
| 2171 | def newlines(self) -> Any: |
| 2172 | pass |
| 2173 | |
| 2174 | @abstractmethod |
| 2175 | def __enter__(self) -> 'TextIO': |
| 2176 | pass |
| 2177 | |
| 2178 | |
| 2179 | class io: |
| 2180 | """Wrapper namespace for IO generic classes.""" |
| 2181 | |
| 2182 | __all__ = ['IO', 'TextIO', 'BinaryIO'] |
| 2183 | IO = IO |
| 2184 | TextIO = TextIO |
| 2185 | BinaryIO = BinaryIO |
| 2186 | |
| 2187 | io.__name__ = __name__ + '.io' |
| 2188 | sys.modules[io.__name__] = io |
| 2189 | |
| 2190 | |
| 2191 | Pattern = _TypeAlias('Pattern', AnyStr, type(stdlib_re.compile('')), |
| 2192 | lambda p: p.pattern) |
| 2193 | Match = _TypeAlias('Match', AnyStr, type(stdlib_re.match('', '')), |
| 2194 | lambda m: m.re.pattern) |
| 2195 | |
| 2196 | |
| 2197 | class re: |
| 2198 | """Wrapper namespace for re type aliases.""" |
| 2199 | |
| 2200 | __all__ = ['Pattern', 'Match'] |
| 2201 | Pattern = Pattern |
| 2202 | Match = Match |
| 2203 | |
| 2204 | re.__name__ = __name__ + '.re' |
| 2205 | sys.modules[re.__name__] = re |