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