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