blob: 5573a1fbf93ccc122d8e73223dac99afbc86fe91 [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
1304 attr != '__dict__' and
1305 attr != '__args__' and
1306 attr != '__slots__' and
1307 attr != '_get_protocol_attrs' and
1308 attr != '__next_in_mro__' and
1309 attr != '__parameters__' and
1310 attr != '__origin__' and
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001311 attr != '__extra__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001312 attr != '__module__'):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001313 attrs.add(attr)
1314
1315 return attrs
1316
1317
1318class _Protocol(metaclass=_ProtocolMeta):
1319 """Internal base class for protocol classes.
1320
1321 This implements a simple-minded structural isinstance check
1322 (similar but more general than the one-offs in collections.abc
1323 such as Hashable).
1324 """
1325
Guido van Rossumd70fe632015-08-05 12:11:06 +02001326 __slots__ = ()
1327
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001328 _is_protocol = True
1329
1330
1331# Various ABCs mimicking those in collections.abc.
1332# A few are simply re-exported for completeness.
1333
1334Hashable = collections_abc.Hashable # Not generic.
1335
1336
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001337if hasattr(collections_abc, 'Awaitable'):
1338 class Awaitable(Generic[T_co], extra=collections_abc.Awaitable):
1339 __slots__ = ()
1340else:
1341 Awaitable = None
Guido van Rossumf17c2002015-12-03 17:31:24 -08001342
1343
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001344if hasattr(collections_abc, 'AsyncIterable'):
Guido van Rossumf17c2002015-12-03 17:31:24 -08001345
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001346 class AsyncIterable(Generic[T_co], extra=collections_abc.AsyncIterable):
1347 __slots__ = ()
Guido van Rossumf17c2002015-12-03 17:31:24 -08001348
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001349 class AsyncIterator(AsyncIterable[T_co],
1350 extra=collections_abc.AsyncIterator):
1351 __slots__ = ()
1352
1353else:
1354 AsyncIterable = None
1355 AsyncIterator = None
Guido van Rossumf17c2002015-12-03 17:31:24 -08001356
1357
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001358class Iterable(Generic[T_co], extra=collections_abc.Iterable):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001359 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001360
1361
1362class Iterator(Iterable[T_co], extra=collections_abc.Iterator):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001363 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001364
1365
1366class SupportsInt(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001367 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001368
1369 @abstractmethod
1370 def __int__(self) -> int:
1371 pass
1372
1373
1374class SupportsFloat(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001375 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001376
1377 @abstractmethod
1378 def __float__(self) -> float:
1379 pass
1380
1381
1382class SupportsComplex(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001383 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001384
1385 @abstractmethod
1386 def __complex__(self) -> complex:
1387 pass
1388
1389
1390class SupportsBytes(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001391 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001392
1393 @abstractmethod
1394 def __bytes__(self) -> bytes:
1395 pass
1396
1397
Guido van Rossumd70fe632015-08-05 12:11:06 +02001398class SupportsAbs(_Protocol[T_co]):
1399 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001400
1401 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001402 def __abs__(self) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001403 pass
1404
1405
Guido van Rossumd70fe632015-08-05 12:11:06 +02001406class SupportsRound(_Protocol[T_co]):
1407 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001408
1409 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001410 def __round__(self, ndigits: int = 0) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001411 pass
1412
1413
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001414if hasattr(collections_abc, 'Reversible'):
1415 class Reversible(Iterable[T_co], extra=collections_abc.Reversible):
1416 __slots__ = ()
1417else:
1418 class Reversible(_Protocol[T_co]):
1419 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001420
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001421 @abstractmethod
1422 def __reversed__(self) -> 'Iterator[T_co]':
1423 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001424
1425
1426Sized = collections_abc.Sized # Not generic.
1427
1428
1429class Container(Generic[T_co], extra=collections_abc.Container):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001430 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001431
1432
Guido van Rossumefa798d2016-08-23 11:01:50 -07001433if hasattr(collections_abc, 'Collection'):
1434 class Collection(Sized, Iterable[T_co], Container[T_co],
1435 extra=collections_abc.Collection):
1436 __slots__ = ()
1437
1438 __all__.append('Collection')
1439
1440
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001441# Callable was defined earlier.
1442
Guido van Rossumefa798d2016-08-23 11:01:50 -07001443if hasattr(collections_abc, 'Collection'):
1444 class AbstractSet(Collection[T_co],
1445 extra=collections_abc.Set):
1446 pass
1447else:
1448 class AbstractSet(Sized, Iterable[T_co], Container[T_co],
1449 extra=collections_abc.Set):
1450 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001451
1452
1453class MutableSet(AbstractSet[T], extra=collections_abc.MutableSet):
1454 pass
1455
1456
Guido van Rossumefa798d2016-08-23 11:01:50 -07001457# NOTE: It is only covariant in the value type.
1458if hasattr(collections_abc, 'Collection'):
1459 class Mapping(Collection[KT], Generic[KT, VT_co],
1460 extra=collections_abc.Mapping):
1461 pass
1462else:
1463 class Mapping(Sized, Iterable[KT], Container[KT], Generic[KT, VT_co],
1464 extra=collections_abc.Mapping):
1465 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001466
1467
1468class MutableMapping(Mapping[KT, VT], extra=collections_abc.MutableMapping):
1469 pass
1470
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001471if hasattr(collections_abc, 'Reversible'):
Guido van Rossumefa798d2016-08-23 11:01:50 -07001472 if hasattr(collections_abc, 'Collection'):
1473 class Sequence(Reversible[T_co], Collection[T_co],
1474 extra=collections_abc.Sequence):
1475 pass
1476 else:
1477 class Sequence(Sized, Reversible[T_co], Container[T_co],
1478 extra=collections_abc.Sequence):
1479 pass
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001480else:
1481 class Sequence(Sized, Iterable[T_co], Container[T_co],
1482 extra=collections_abc.Sequence):
1483 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001484
1485
1486class MutableSequence(Sequence[T], extra=collections_abc.MutableSequence):
1487 pass
1488
1489
1490class ByteString(Sequence[int], extra=collections_abc.ByteString):
1491 pass
1492
1493
1494ByteString.register(type(memoryview(b'')))
1495
1496
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001497class List(list, MutableSequence[T], extra=list):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001498
1499 def __new__(cls, *args, **kwds):
1500 if _geqv(cls, List):
1501 raise TypeError("Type List cannot be instantiated; "
1502 "use list() instead")
1503 return list.__new__(cls, *args, **kwds)
1504
1505
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001506class Set(set, MutableSet[T], extra=set):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001507
1508 def __new__(cls, *args, **kwds):
1509 if _geqv(cls, Set):
1510 raise TypeError("Type Set cannot be instantiated; "
1511 "use set() instead")
1512 return set.__new__(cls, *args, **kwds)
1513
1514
Guido van Rossumd70fe632015-08-05 12:11:06 +02001515class _FrozenSetMeta(GenericMeta):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001516 """This metaclass ensures set is not a subclass of FrozenSet.
1517
1518 Without this metaclass, set would be considered a subclass of
1519 FrozenSet, because FrozenSet.__extra__ is collections.abc.Set, and
1520 set is a subclass of that.
1521 """
1522
1523 def __subclasscheck__(self, cls):
1524 if issubclass(cls, Set):
1525 return False
1526 return super().__subclasscheck__(cls)
1527
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001528
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001529class FrozenSet(frozenset, AbstractSet[T_co], metaclass=_FrozenSetMeta,
1530 extra=frozenset):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001531 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001532
1533 def __new__(cls, *args, **kwds):
1534 if _geqv(cls, FrozenSet):
1535 raise TypeError("Type FrozenSet cannot be instantiated; "
1536 "use frozenset() instead")
1537 return frozenset.__new__(cls, *args, **kwds)
1538
1539
1540class MappingView(Sized, Iterable[T_co], extra=collections_abc.MappingView):
1541 pass
1542
1543
Guido van Rossumd70fe632015-08-05 12:11:06 +02001544class KeysView(MappingView[KT], AbstractSet[KT],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001545 extra=collections_abc.KeysView):
1546 pass
1547
1548
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001549class ItemsView(MappingView[Tuple[KT, VT_co]],
Guido van Rossum0e0563c2016-04-05 14:54:25 -07001550 AbstractSet[Tuple[KT, VT_co]],
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001551 Generic[KT, VT_co],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001552 extra=collections_abc.ItemsView):
1553 pass
1554
1555
1556class ValuesView(MappingView[VT_co], extra=collections_abc.ValuesView):
1557 pass
1558
1559
Brett Cannonf3ad0422016-04-15 10:51:30 -07001560if hasattr(contextlib, 'AbstractContextManager'):
1561 class ContextManager(Generic[T_co], extra=contextlib.AbstractContextManager):
1562 __slots__ = ()
1563 __all__.append('ContextManager')
1564
1565
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001566class Dict(dict, MutableMapping[KT, VT], extra=dict):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001567
1568 def __new__(cls, *args, **kwds):
1569 if _geqv(cls, Dict):
1570 raise TypeError("Type Dict cannot be instantiated; "
1571 "use dict() instead")
1572 return dict.__new__(cls, *args, **kwds)
1573
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001574class DefaultDict(collections.defaultdict, MutableMapping[KT, VT],
1575 extra=collections.defaultdict):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001576
1577 def __new__(cls, *args, **kwds):
1578 if _geqv(cls, DefaultDict):
1579 raise TypeError("Type DefaultDict cannot be instantiated; "
1580 "use collections.defaultdict() instead")
1581 return collections.defaultdict.__new__(cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001582
1583# Determine what base class to use for Generator.
1584if hasattr(collections_abc, 'Generator'):
1585 # Sufficiently recent versions of 3.5 have a Generator ABC.
1586 _G_base = collections_abc.Generator
1587else:
1588 # Fall back on the exact type.
1589 _G_base = types.GeneratorType
1590
1591
1592class Generator(Iterator[T_co], Generic[T_co, T_contra, V_co],
1593 extra=_G_base):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001594 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001595
1596 def __new__(cls, *args, **kwds):
1597 if _geqv(cls, Generator):
1598 raise TypeError("Type Generator cannot be instantiated; "
1599 "create a subclass instead")
1600 return super().__new__(cls, *args, **kwds)
1601
1602
Guido van Rossumeb9aca32016-05-24 16:38:22 -07001603# Internal type variable used for Type[].
Guido van Rossumefa798d2016-08-23 11:01:50 -07001604CT_co = TypeVar('CT_co', covariant=True, bound=type)
Guido van Rossumeb9aca32016-05-24 16:38:22 -07001605
1606
Guido van Rossumb22c7082016-05-26 09:56:19 -07001607# This is not a real generic class. Don't use outside annotations.
Guido van Rossumefa798d2016-08-23 11:01:50 -07001608class Type(type, Generic[CT_co], extra=type):
Guido van Rossumb22c7082016-05-26 09:56:19 -07001609 """A special construct usable to annotate class objects.
Guido van Rossumeb9aca32016-05-24 16:38:22 -07001610
1611 For example, suppose we have the following classes::
1612
1613 class User: ... # Abstract base for User classes
1614 class BasicUser(User): ...
1615 class ProUser(User): ...
1616 class TeamUser(User): ...
1617
1618 And a function that takes a class argument that's a subclass of
1619 User and returns an instance of the corresponding class::
1620
1621 U = TypeVar('U', bound=User)
1622 def new_user(user_class: Type[U]) -> U:
1623 user = user_class()
1624 # (Here we could write the user object to a database)
1625 return user
1626
1627 joe = new_user(BasicUser)
1628
1629 At this point the type checker knows that joe has type BasicUser.
1630 """
1631
1632
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001633def NamedTuple(typename, fields):
1634 """Typed version of namedtuple.
1635
1636 Usage::
1637
1638 Employee = typing.NamedTuple('Employee', [('name', str), 'id', int)])
1639
1640 This is equivalent to::
1641
1642 Employee = collections.namedtuple('Employee', ['name', 'id'])
1643
1644 The resulting class has one extra attribute: _field_types,
1645 giving a dict mapping field names to types. (The field names
1646 are in the _fields attribute, which is part of the namedtuple
1647 API.)
1648 """
1649 fields = [(n, t) for n, t in fields]
1650 cls = collections.namedtuple(typename, [n for n, t in fields])
1651 cls._field_types = dict(fields)
Guido van Rossum557d1eb2015-11-19 08:16:31 -08001652 # Set the module to the caller's module (otherwise it'd be 'typing').
1653 try:
1654 cls.__module__ = sys._getframe(1).f_globals.get('__name__', '__main__')
1655 except (AttributeError, ValueError):
1656 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001657 return cls
1658
1659
Guido van Rossum91185fe2016-06-08 11:19:11 -07001660def NewType(name, tp):
1661 """NewType creates simple unique types with almost zero
1662 runtime overhead. NewType(name, tp) is considered a subtype of tp
1663 by static type checkers. At runtime, NewType(name, tp) returns
1664 a dummy function that simply returns its argument. Usage::
1665
1666 UserId = NewType('UserId', int)
1667
1668 def name_by_id(user_id: UserId) -> str:
1669 ...
1670
1671 UserId('user') # Fails type check
1672
1673 name_by_id(42) # Fails type check
1674 name_by_id(UserId(42)) # OK
1675
1676 num = UserId(5) + 1 # type: int
1677 """
1678
1679 def new_type(x):
1680 return x
1681
1682 new_type.__name__ = name
1683 new_type.__supertype__ = tp
1684 return new_type
1685
1686
Guido van Rossum0e0563c2016-04-05 14:54:25 -07001687# Python-version-specific alias (Python 2: unicode; Python 3: str)
1688Text = str
1689
1690
Guido van Rossum91185fe2016-06-08 11:19:11 -07001691# Constant that's True when type checking, but False here.
1692TYPE_CHECKING = False
1693
1694
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001695class IO(Generic[AnyStr]):
1696 """Generic base class for TextIO and BinaryIO.
1697
1698 This is an abstract, generic version of the return of open().
1699
1700 NOTE: This does not distinguish between the different possible
1701 classes (text vs. binary, read vs. write vs. read/write,
1702 append-only, unbuffered). The TextIO and BinaryIO subclasses
1703 below capture the distinctions between text vs. binary, which is
1704 pervasive in the interface; however we currently do not offer a
1705 way to track the other distinctions in the type system.
1706 """
1707
Guido van Rossumd70fe632015-08-05 12:11:06 +02001708 __slots__ = ()
1709
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001710 @abstractproperty
1711 def mode(self) -> str:
1712 pass
1713
1714 @abstractproperty
1715 def name(self) -> str:
1716 pass
1717
1718 @abstractmethod
1719 def close(self) -> None:
1720 pass
1721
1722 @abstractmethod
1723 def closed(self) -> bool:
1724 pass
1725
1726 @abstractmethod
1727 def fileno(self) -> int:
1728 pass
1729
1730 @abstractmethod
1731 def flush(self) -> None:
1732 pass
1733
1734 @abstractmethod
1735 def isatty(self) -> bool:
1736 pass
1737
1738 @abstractmethod
1739 def read(self, n: int = -1) -> AnyStr:
1740 pass
1741
1742 @abstractmethod
1743 def readable(self) -> bool:
1744 pass
1745
1746 @abstractmethod
1747 def readline(self, limit: int = -1) -> AnyStr:
1748 pass
1749
1750 @abstractmethod
1751 def readlines(self, hint: int = -1) -> List[AnyStr]:
1752 pass
1753
1754 @abstractmethod
1755 def seek(self, offset: int, whence: int = 0) -> int:
1756 pass
1757
1758 @abstractmethod
1759 def seekable(self) -> bool:
1760 pass
1761
1762 @abstractmethod
1763 def tell(self) -> int:
1764 pass
1765
1766 @abstractmethod
1767 def truncate(self, size: int = None) -> int:
1768 pass
1769
1770 @abstractmethod
1771 def writable(self) -> bool:
1772 pass
1773
1774 @abstractmethod
1775 def write(self, s: AnyStr) -> int:
1776 pass
1777
1778 @abstractmethod
1779 def writelines(self, lines: List[AnyStr]) -> None:
1780 pass
1781
1782 @abstractmethod
1783 def __enter__(self) -> 'IO[AnyStr]':
1784 pass
1785
1786 @abstractmethod
1787 def __exit__(self, type, value, traceback) -> None:
1788 pass
1789
1790
1791class BinaryIO(IO[bytes]):
1792 """Typed version of the return of open() in binary mode."""
1793
Guido van Rossumd70fe632015-08-05 12:11:06 +02001794 __slots__ = ()
1795
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001796 @abstractmethod
1797 def write(self, s: Union[bytes, bytearray]) -> int:
1798 pass
1799
1800 @abstractmethod
1801 def __enter__(self) -> 'BinaryIO':
1802 pass
1803
1804
1805class TextIO(IO[str]):
1806 """Typed version of the return of open() in text mode."""
1807
Guido van Rossumd70fe632015-08-05 12:11:06 +02001808 __slots__ = ()
1809
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001810 @abstractproperty
1811 def buffer(self) -> BinaryIO:
1812 pass
1813
1814 @abstractproperty
1815 def encoding(self) -> str:
1816 pass
1817
1818 @abstractproperty
1819 def errors(self) -> str:
1820 pass
1821
1822 @abstractproperty
1823 def line_buffering(self) -> bool:
1824 pass
1825
1826 @abstractproperty
1827 def newlines(self) -> Any:
1828 pass
1829
1830 @abstractmethod
1831 def __enter__(self) -> 'TextIO':
1832 pass
1833
1834
1835class io:
1836 """Wrapper namespace for IO generic classes."""
1837
1838 __all__ = ['IO', 'TextIO', 'BinaryIO']
1839 IO = IO
1840 TextIO = TextIO
1841 BinaryIO = BinaryIO
1842
1843io.__name__ = __name__ + '.io'
1844sys.modules[io.__name__] = io
1845
1846
1847Pattern = _TypeAlias('Pattern', AnyStr, type(stdlib_re.compile('')),
1848 lambda p: p.pattern)
1849Match = _TypeAlias('Match', AnyStr, type(stdlib_re.match('', '')),
1850 lambda m: m.re.pattern)
1851
1852
1853class re:
1854 """Wrapper namespace for re type aliases."""
1855
1856 __all__ = ['Pattern', 'Match']
1857 Pattern = Pattern
1858 Match = Match
1859
1860re.__name__ = __name__ + '.re'
1861sys.modules[re.__name__] = re