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