blob: bc6fcdd03d7cf713276e2b666ff982a25d1d9d96 [file] [log] [blame]
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001# TODO:
2# - Generic[T, T] is invalid
3# - Look for TODO below
4
5# TODO nits:
6# Get rid of asserts that are the caller's fault.
7# Docstrings (e.g. ABCs).
8
9import abc
10from abc import abstractmethod, abstractproperty
11import collections
12import functools
13import re as stdlib_re # Avoid confusion with the re we export.
14import sys
15import types
16try:
17 import collections.abc as collections_abc
18except ImportError:
19 import collections as collections_abc # Fallback for PY3.2.
20
21
22# Please keep __all__ alphabetized within each category.
23__all__ = [
24 # Super-special typing primitives.
25 'Any',
26 'Callable',
27 'Generic',
28 'Optional',
29 'TypeVar',
30 'Union',
31 'Tuple',
32
33 # ABCs (from collections.abc).
34 'AbstractSet', # collections.abc.Set.
35 'ByteString',
36 'Container',
37 'Hashable',
38 'ItemsView',
39 'Iterable',
40 'Iterator',
41 'KeysView',
42 'Mapping',
43 'MappingView',
44 'MutableMapping',
45 'MutableSequence',
46 'MutableSet',
47 'Sequence',
48 'Sized',
49 'ValuesView',
50
51 # Structural checks, a.k.a. protocols.
52 'Reversible',
53 'SupportsAbs',
54 'SupportsFloat',
55 'SupportsInt',
56 'SupportsRound',
57
58 # Concrete collection types.
59 'Dict',
60 'List',
61 'Set',
62 'NamedTuple', # Not really a type.
63 'Generator',
64
65 # One-off things.
66 'AnyStr',
67 'cast',
68 'get_type_hints',
69 'no_type_check',
70 'no_type_check_decorator',
71 'overload',
72
73 # Submodules.
74 'io',
75 're',
76]
77
78
79def _qualname(x):
80 if sys.version_info[:2] >= (3, 3):
81 return x.__qualname__
82 else:
83 # Fall back to just name.
84 return x.__name__
85
86
87class TypingMeta(type):
88 """Metaclass for every type defined below.
89
90 This overrides __new__() to require an extra keyword parameter
91 '_root', which serves as a guard against naive subclassing of the
92 typing classes. Any legitimate class defined using a metaclass
93 derived from TypingMeta (including internal subclasses created by
94 e.g. Union[X, Y]) must pass _root=True.
95
96 This also defines a dummy constructor (all the work is done in
97 __new__) and a nicer repr().
98 """
99
100 _is_protocol = False
101
102 def __new__(cls, name, bases, namespace, *, _root=False):
103 if not _root:
104 raise TypeError("Cannot subclass %s" %
105 (', '.join(map(_type_repr, bases)) or '()'))
106 return super().__new__(cls, name, bases, namespace)
107
108 def __init__(self, *args, **kwds):
109 pass
110
111 def _eval_type(self, globalns, localns):
112 """Override this in subclasses to interpret forward references.
113
114 For example, Union['C'] is internally stored as
115 Union[_ForwardRef('C')], which should evaluate to _Union[C],
116 where C is an object found in globalns or localns (searching
117 localns first, of course).
118 """
119 return self
120
121 def _has_type_var(self):
122 return False
123
124 def __repr__(self):
125 return '%s.%s' % (self.__module__, _qualname(self))
126
127
128class Final:
129 """Mix-in class to prevent instantiation."""
130
131 def __new__(self, *args, **kwds):
132 raise TypeError("Cannot instantiate %r" % self.__class__)
133
134
135class _ForwardRef(TypingMeta):
136 """Wrapper to hold a forward reference."""
137
138 def __new__(cls, arg):
139 if not isinstance(arg, str):
140 raise TypeError('ForwardRef must be a string -- got %r' % (arg,))
141 try:
142 code = compile(arg, '<string>', 'eval')
143 except SyntaxError:
144 raise SyntaxError('ForwardRef must be an expression -- got %r' %
145 (arg,))
146 self = super().__new__(cls, arg, (), {}, _root=True)
147 self.__forward_arg__ = arg
148 self.__forward_code__ = code
149 self.__forward_evaluated__ = False
150 self.__forward_value__ = None
151 typing_globals = globals()
152 frame = sys._getframe(1)
153 while frame is not None and frame.f_globals is typing_globals:
154 frame = frame.f_back
155 assert frame is not None
156 self.__forward_frame__ = frame
157 return self
158
159 def _eval_type(self, globalns, localns):
160 if not isinstance(localns, dict):
161 raise TypeError('ForwardRef localns must be a dict -- got %r' %
162 (localns,))
163 if not isinstance(globalns, dict):
164 raise TypeError('ForwardRef globalns must be a dict -- got %r' %
165 (globalns,))
166 if not self.__forward_evaluated__:
167 if globalns is None and localns is None:
168 globalns = localns = {}
169 elif globalns is None:
170 globalns = localns
171 elif localns is None:
172 localns = globalns
173 self.__forward_value__ = _type_check(
174 eval(self.__forward_code__, globalns, localns),
175 "Forward references must evaluate to types.")
176 self.__forward_evaluated__ = True
177 return self.__forward_value__
178
Guido van Rossum43a79cc2015-06-03 19:04:42 -0700179 def __instancecheck__(self, obj):
180 raise TypeError("Forward references cannot be used with isinstance().")
181
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700182 def __subclasscheck__(self, cls):
183 if not self.__forward_evaluated__:
184 globalns = self.__forward_frame__.f_globals
185 localns = self.__forward_frame__.f_locals
186 try:
187 self._eval_type(globalns, localns)
188 except NameError:
189 return False # Too early.
190 return issubclass(cls, self.__forward_value__)
191
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700192 def __repr__(self):
193 return '_ForwardRef(%r)' % (self.__forward_arg__,)
194
195
196class _TypeAlias:
197 """Internal helper class for defining generic variants of concrete types.
198
199 Note that this is not a type; let's call it a pseudo-type. It can
200 be used in instance and subclass checks, e.g. isinstance(m, Match)
201 or issubclass(type(m), Match). However, it cannot be itself the
202 target of an issubclass() call; e.g. issubclass(Match, C) (for
203 some arbitrary class C) raises TypeError rather than returning
204 False.
205 """
206
207 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
214 isinstance(args[0], str) and
215 isinstance(args[1], tuple)):
216 # 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 Rossum43a79cc2015-06-03 19:04:42 -0700255 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
271def _has_type_var(t):
272 return t is not None and isinstance(t, TypingMeta) and t._has_type_var()
273
274
275def _eval_type(t, globalns, localns):
276 if isinstance(t, TypingMeta):
277 return t._eval_type(globalns, localns)
278 else:
279 return t
280
281
282def _type_check(arg, msg):
283 """Check that the argument is a type, and return it.
284
285 As a special case, accept None and return type(None) instead.
286 Also, _TypeAlias instances (e.g. Match, Pattern) are acceptable.
287
288 The msg argument is a human-readable error message, e.g.
289
290 "Union[arg, ...]: arg should be a type."
291
292 We append the repr() of the actual value (truncated to 100 chars).
293 """
294 if arg is None:
295 return type(None)
296 if isinstance(arg, str):
297 arg = _ForwardRef(arg)
298 if not isinstance(arg, (type, _TypeAlias)):
299 raise TypeError(msg + " Got %.100r." % (arg,))
300 return arg
301
302
303def _type_repr(obj):
304 """Return the repr() of an object, special-casing types.
305
306 If obj is a type, we return a shorter version than the default
307 type.__repr__, based on the module and qualified name, which is
308 typically enough to uniquely identify a type. For everything
309 else, we fall back on repr(obj).
310 """
311 if isinstance(obj, type) and not isinstance(obj, TypingMeta):
312 if obj.__module__ == 'builtins':
313 return _qualname(obj)
314 else:
315 return '%s.%s' % (obj.__module__, _qualname(obj))
316 else:
317 return repr(obj)
318
319
320class AnyMeta(TypingMeta):
321 """Metaclass for Any."""
322
323 def __new__(cls, name, bases, namespace, _root=False):
324 self = super().__new__(cls, name, bases, namespace, _root=_root)
325 return self
326
Guido van Rossum43a79cc2015-06-03 19:04:42 -0700327 def __instancecheck__(self, obj):
328 raise TypeError("Any cannot be used with isinstance().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700329
330 def __subclasscheck__(self, cls):
331 if not isinstance(cls, type):
332 return super().__subclasscheck__(cls) # To TypeError.
333 return True
334
335
336class Any(Final, metaclass=AnyMeta, _root=True):
337 """Special type indicating an unconstrained type.
338
339 - Any object is an instance of Any.
340 - Any class is a subclass of Any.
341 - As a special case, Any and object are subclasses of each other.
342 """
343
344
345class TypeVar(TypingMeta, metaclass=TypingMeta, _root=True):
346 """Type variable.
347
348 Usage::
349
350 T = TypeVar('T') # Can be anything
351 A = TypeVar('A', str, bytes) # Must be str or bytes
352
353 Type variables exist primarily for the benefit of static type
354 checkers. They serve as the parameters for generic types as well
355 as for generic function definitions. See class Generic for more
356 information on generic types. Generic functions work as follows:
357
358 def repeat(x: T, n: int) -> Sequence[T]:
359 '''Return a list containing n references to x.'''
360 return [x]*n
361
362 def longest(x: A, y: A) -> A:
363 '''Return the longest of two strings.'''
364 return x if len(x) >= len(y) else y
365
366 The latter example's signature is essentially the overloading
367 of (str, str) -> str and (bytes, bytes) -> bytes. Also note
368 that if the arguments are instances of some subclass of str,
369 the return type is still plain str.
370
371 At runtime, isinstance(x, T) will raise TypeError. However,
372 issubclass(C, T) is true for any class C, and issubclass(str, A)
373 and issubclass(bytes, A) are true, and issubclass(int, A) is
374 false.
375
376 Type variables may be marked covariant or contravariant by passing
377 covariant=True or contravariant=True. See PEP 484 for more
378 details. By default type variables are invariant.
379
380 Type variables can be introspected. e.g.:
381
382 T.__name__ == 'T'
383 T.__constraints__ == ()
384 T.__covariant__ == False
385 T.__contravariant__ = False
386 A.__constraints__ == (str, bytes)
387 """
388
389 def __new__(cls, name, *constraints, bound=None,
390 covariant=False, contravariant=False):
391 self = super().__new__(cls, name, (Final,), {}, _root=True)
392 if covariant and contravariant:
393 raise ValueError("Bivariant type variables are not supported.")
394 self.__covariant__ = bool(covariant)
395 self.__contravariant__ = bool(contravariant)
396 if constraints and bound is not None:
397 raise TypeError("Constraints cannot be combined with bound=...")
398 if constraints and len(constraints) == 1:
399 raise TypeError("A single constraint is not allowed")
400 msg = "TypeVar(name, constraint, ...): constraints must be types."
401 self.__constraints__ = tuple(_type_check(t, msg) for t in constraints)
402 if bound:
403 self.__bound__ = _type_check(bound, "Bound must be a type.")
404 else:
405 self.__bound__ = None
406 return self
407
408 def _has_type_var(self):
409 return True
410
411 def __repr__(self):
412 if self.__covariant__:
413 prefix = '+'
414 elif self.__contravariant__:
415 prefix = '-'
416 else:
417 prefix = '~'
418 return prefix + self.__name__
419
420 def __instancecheck__(self, instance):
421 raise TypeError("Type variables cannot be used with isinstance().")
422
423 def __subclasscheck__(self, cls):
424 # TODO: Make this raise TypeError too?
425 if cls is self:
426 return True
427 if cls is Any:
428 return True
429 if self.__bound__ is not None:
430 return issubclass(cls, self.__bound__)
431 if self.__constraints__:
432 return any(issubclass(cls, c) for c in self.__constraints__)
433 return True
434
435
436# Some unconstrained type variables. These are used by the container types.
437T = TypeVar('T') # Any type.
438KT = TypeVar('KT') # Key type.
439VT = TypeVar('VT') # Value type.
440T_co = TypeVar('T_co', covariant=True) # Any type covariant containers.
441V_co = TypeVar('V_co', covariant=True) # Any type covariant containers.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700442VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
443T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
444
445# A useful type variable with constraints. This represents string types.
446# TODO: What about bytearray, memoryview?
447AnyStr = TypeVar('AnyStr', bytes, str)
448
449
450class UnionMeta(TypingMeta):
451 """Metaclass for Union."""
452
453 def __new__(cls, name, bases, namespace, parameters=None, _root=False):
454 if parameters is None:
455 return super().__new__(cls, name, bases, namespace, _root=_root)
456 if not isinstance(parameters, tuple):
457 raise TypeError("Expected parameters=<tuple>")
458 # Flatten out Union[Union[...], ...] and type-check non-Union args.
459 params = []
460 msg = "Union[arg, ...]: each arg must be a type."
461 for p in parameters:
462 if isinstance(p, UnionMeta):
463 params.extend(p.__union_params__)
464 else:
465 params.append(_type_check(p, msg))
466 # Weed out strict duplicates, preserving the first of each occurrence.
467 all_params = set(params)
468 if len(all_params) < len(params):
469 new_params = []
470 for t in params:
471 if t in all_params:
472 new_params.append(t)
473 all_params.remove(t)
474 params = new_params
475 assert not all_params, all_params
476 # Weed out subclasses.
477 # E.g. Union[int, Employee, Manager] == Union[int, Employee].
478 # If Any or object is present it will be the sole survivor.
479 # If both Any and object are present, Any wins.
480 # Never discard type variables, except against Any.
481 # (In particular, Union[str, AnyStr] != AnyStr.)
482 all_params = set(params)
483 for t1 in params:
484 if t1 is Any:
485 return Any
486 if isinstance(t1, TypeVar):
487 continue
488 if any(issubclass(t1, t2)
489 for t2 in all_params - {t1} if not isinstance(t2, TypeVar)):
490 all_params.remove(t1)
491 # It's not a union if there's only one type left.
492 if len(all_params) == 1:
493 return all_params.pop()
494 # Create a new class with these params.
495 self = super().__new__(cls, name, bases, {}, _root=True)
496 self.__union_params__ = tuple(t for t in params if t in all_params)
497 self.__union_set_params__ = frozenset(self.__union_params__)
498 return self
499
500 def _eval_type(self, globalns, localns):
501 p = tuple(_eval_type(t, globalns, localns)
502 for t in self.__union_params__)
503 if p == self.__union_params__:
504 return self
505 else:
506 return self.__class__(self.__name__, self.__bases__, {},
507 p, _root=True)
508
509 def _has_type_var(self):
510 if self.__union_params__:
511 for t in self.__union_params__:
512 if _has_type_var(t):
513 return True
514 return False
515
516 def __repr__(self):
517 r = super().__repr__()
518 if self.__union_params__:
519 r += '[%s]' % (', '.join(_type_repr(t)
520 for t in self.__union_params__))
521 return r
522
523 def __getitem__(self, parameters):
524 if self.__union_params__ is not None:
525 raise TypeError(
526 "Cannot subscript an existing Union. Use Union[u, t] instead.")
527 if parameters == ():
528 raise TypeError("Cannot take a Union of no types.")
529 if not isinstance(parameters, tuple):
530 parameters = (parameters,)
531 return self.__class__(self.__name__, self.__bases__,
532 dict(self.__dict__), parameters, _root=True)
533
534 def __eq__(self, other):
535 if not isinstance(other, UnionMeta):
536 return NotImplemented
537 return self.__union_set_params__ == other.__union_set_params__
538
539 def __hash__(self):
540 return hash(self.__union_set_params__)
541
Guido van Rossum43a79cc2015-06-03 19:04:42 -0700542 def __instancecheck__(self, obj):
543 raise TypeError("Unions cannot be used with isinstance().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700544
545 def __subclasscheck__(self, cls):
546 if cls is Any:
547 return True
548 if self.__union_params__ is None:
549 return isinstance(cls, UnionMeta)
550 elif isinstance(cls, UnionMeta):
551 if cls.__union_params__ is None:
552 return False
553 return all(issubclass(c, self) for c in (cls.__union_params__))
554 elif isinstance(cls, TypeVar):
555 if cls in self.__union_params__:
556 return True
557 if cls.__constraints__:
558 return issubclass(Union[cls.__constraints__], self)
559 return False
560 else:
561 return any(issubclass(cls, t) for t in self.__union_params__)
562
563
564class Union(Final, metaclass=UnionMeta, _root=True):
565 """Union type; Union[X, Y] means either X or Y.
566
567 To define a union, use e.g. Union[int, str]. Details:
568
569 - The arguments must be types and there must be at least one.
570
571 - None as an argument is a special case and is replaced by
572 type(None).
573
574 - Unions of unions are flattened, e.g.::
575
576 Union[Union[int, str], float] == Union[int, str, float]
577
578 - Unions of a single argument vanish, e.g.::
579
580 Union[int] == int # The constructor actually returns int
581
582 - Redundant arguments are skipped, e.g.::
583
584 Union[int, str, int] == Union[int, str]
585
586 - When comparing unions, the argument order is ignored, e.g.::
587
588 Union[int, str] == Union[str, int]
589
590 - When two arguments have a subclass relationship, the least
591 derived argument is kept, e.g.::
592
593 class Employee: pass
594 class Manager(Employee): pass
595 Union[int, Employee, Manager] == Union[int, Employee]
596 Union[Manager, int, Employee] == Union[int, Employee]
597 Union[Employee, Manager] == Employee
598
599 - Corollary: if Any is present it is the sole survivor, e.g.::
600
601 Union[int, Any] == Any
602
603 - Similar for object::
604
605 Union[int, object] == object
606
607 - To cut a tie: Union[object, Any] == Union[Any, object] == Any.
608
609 - You cannot subclass or instantiate a union.
610
611 - You cannot write Union[X][Y] (what would it mean?).
612
613 - You can use Optional[X] as a shorthand for Union[X, None].
614 """
615
616 # Unsubscripted Union type has params set to None.
617 __union_params__ = None
618 __union_set_params__ = None
619
620
621class OptionalMeta(TypingMeta):
622 """Metaclass for Optional."""
623
624 def __new__(cls, name, bases, namespace, _root=False):
625 return super().__new__(cls, name, bases, namespace, _root=_root)
626
627 def __getitem__(self, arg):
628 arg = _type_check(arg, "Optional[t] requires a single type.")
629 return Union[arg, type(None)]
630
631
632class Optional(Final, metaclass=OptionalMeta, _root=True):
633 """Optional type.
634
635 Optional[X] is equivalent to Union[X, type(None)].
636 """
637
638
639class TupleMeta(TypingMeta):
640 """Metaclass for Tuple."""
641
642 def __new__(cls, name, bases, namespace, parameters=None,
643 use_ellipsis=False, _root=False):
644 self = super().__new__(cls, name, bases, namespace, _root=_root)
645 self.__tuple_params__ = parameters
646 self.__tuple_use_ellipsis__ = use_ellipsis
647 return self
648
649 def _has_type_var(self):
650 if self.__tuple_params__:
651 for t in self.__tuple_params__:
652 if _has_type_var(t):
653 return True
654 return False
655
656 def _eval_type(self, globalns, localns):
657 tp = self.__tuple_params__
658 if tp is None:
659 return self
660 p = tuple(_eval_type(t, globalns, localns) for t in tp)
661 if p == self.__tuple_params__:
662 return self
663 else:
664 return self.__class__(self.__name__, self.__bases__, {},
665 p, _root=True)
666
667 def __repr__(self):
668 r = super().__repr__()
669 if self.__tuple_params__ is not None:
670 params = [_type_repr(p) for p in self.__tuple_params__]
671 if self.__tuple_use_ellipsis__:
672 params.append('...')
673 r += '[%s]' % (
674 ', '.join(params))
675 return r
676
677 def __getitem__(self, parameters):
678 if self.__tuple_params__ is not None:
679 raise TypeError("Cannot re-parameterize %r" % (self,))
680 if not isinstance(parameters, tuple):
681 parameters = (parameters,)
682 if len(parameters) == 2 and parameters[1] == Ellipsis:
683 parameters = parameters[:1]
684 use_ellipsis = True
685 msg = "Tuple[t, ...]: t must be a type."
686 else:
687 use_ellipsis = False
688 msg = "Tuple[t0, t1, ...]: each t must be a type."
689 parameters = tuple(_type_check(p, msg) for p in parameters)
690 return self.__class__(self.__name__, self.__bases__,
691 dict(self.__dict__), parameters,
692 use_ellipsis=use_ellipsis, _root=True)
693
694 def __eq__(self, other):
695 if not isinstance(other, TupleMeta):
696 return NotImplemented
697 return self.__tuple_params__ == other.__tuple_params__
698
699 def __hash__(self):
700 return hash(self.__tuple_params__)
701
Guido van Rossum43a79cc2015-06-03 19:04:42 -0700702 def __instancecheck__(self, obj):
703 raise TypeError("Tuples cannot be used with isinstance().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700704
705 def __subclasscheck__(self, cls):
706 if cls is Any:
707 return True
708 if not isinstance(cls, type):
709 return super().__subclasscheck__(cls) # To TypeError.
710 if issubclass(cls, tuple):
711 return True # Special case.
712 if not isinstance(cls, TupleMeta):
713 return super().__subclasscheck__(cls) # False.
714 if self.__tuple_params__ is None:
715 return True
716 if cls.__tuple_params__ is None:
717 return False # ???
718 if cls.__tuple_use_ellipsis__ != self.__tuple_use_ellipsis__:
719 return False
720 # Covariance.
721 return (len(self.__tuple_params__) == len(cls.__tuple_params__) and
722 all(issubclass(x, p)
723 for x, p in zip(cls.__tuple_params__,
724 self.__tuple_params__)))
725
726
727class Tuple(Final, metaclass=TupleMeta, _root=True):
728 """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
729
730 Example: Tuple[T1, T2] is a tuple of two elements corresponding
731 to type variables T1 and T2. Tuple[int, float, str] is a tuple
732 of an int, a float and a string.
733
734 To specify a variable-length tuple of homogeneous type, use Sequence[T].
735 """
736
737
738class CallableMeta(TypingMeta):
739 """Metaclass for Callable."""
740
741 def __new__(cls, name, bases, namespace, _root=False,
742 args=None, result=None):
743 if args is None and result is None:
744 pass # Must be 'class Callable'.
745 else:
746 if args is not Ellipsis:
747 if not isinstance(args, list):
748 raise TypeError("Callable[args, result]: "
749 "args must be a list."
750 " Got %.100r." % (args,))
751 msg = "Callable[[arg, ...], result]: each arg must be a type."
752 args = tuple(_type_check(arg, msg) for arg in args)
753 msg = "Callable[args, result]: result must be a type."
754 result = _type_check(result, msg)
755 self = super().__new__(cls, name, bases, namespace, _root=_root)
756 self.__args__ = args
757 self.__result__ = result
758 return self
759
760 def _has_type_var(self):
761 if self.__args__:
762 for t in self.__args__:
763 if _has_type_var(t):
764 return True
765 return _has_type_var(self.__result__)
766
767 def _eval_type(self, globalns, localns):
768 if self.__args__ is None and self.__result__ is None:
769 return self
770 args = [_eval_type(t, globalns, localns) for t in self.__args__]
771 result = _eval_type(self.__result__, globalns, localns)
772 if args == self.__args__ and result == self.__result__:
773 return self
774 else:
775 return self.__class__(self.__name__, self.__bases__, {},
776 args=args, result=result, _root=True)
777
778 def __repr__(self):
779 r = super().__repr__()
780 if self.__args__ is not None or self.__result__ is not None:
781 if self.__args__ is Ellipsis:
782 args_r = '...'
783 else:
784 args_r = '[%s]' % ', '.join(_type_repr(t)
785 for t in self.__args__)
786 r += '[%s, %s]' % (args_r, _type_repr(self.__result__))
787 return r
788
789 def __getitem__(self, parameters):
790 if self.__args__ is not None or self.__result__ is not None:
791 raise TypeError("This Callable type is already parameterized.")
792 if not isinstance(parameters, tuple) or len(parameters) != 2:
793 raise TypeError(
794 "Callable must be used as Callable[[arg, ...], result].")
795 args, result = parameters
796 return self.__class__(self.__name__, self.__bases__,
797 dict(self.__dict__), _root=True,
798 args=args, result=result)
799
800 def __eq__(self, other):
801 if not isinstance(other, CallableMeta):
802 return NotImplemented
803 return (self.__args__ == other.__args__ and
804 self.__result__ == other.__result__)
805
806 def __hash__(self):
807 return hash(self.__args__) ^ hash(self.__result__)
808
Guido van Rossum43a79cc2015-06-03 19:04:42 -0700809 def __instancecheck__(self, obj):
810 # For unparametrized Callable we allow this, because
811 # typing.Callable should be equivalent to
812 # collections.abc.Callable.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700813 if self.__args__ is None and self.__result__ is None:
Guido van Rossum43a79cc2015-06-03 19:04:42 -0700814 return isinstance(obj, collections_abc.Callable)
815 else:
816 raise TypeError("Callable[] cannot be used with isinstance().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700817
818 def __subclasscheck__(self, cls):
819 if cls is Any:
820 return True
821 if not isinstance(cls, CallableMeta):
822 return super().__subclasscheck__(cls)
823 if self.__args__ is None and self.__result__ is None:
824 return True
825 # We're not doing covariance or contravariance -- this is *invariance*.
826 return self == cls
827
828
829class Callable(Final, metaclass=CallableMeta, _root=True):
830 """Callable type; Callable[[int], str] is a function of (int) -> str.
831
832 The subscription syntax must always be used with exactly two
833 values: the argument list and the return type. The argument list
834 must be a list of types; the return type must be a single type.
835
836 There is no syntax to indicate optional or keyword arguments,
837 such function types are rarely used as callback types.
838 """
839
840
841def _gorg(a):
842 """Return the farthest origin of a generic class."""
843 assert isinstance(a, GenericMeta)
844 while a.__origin__ is not None:
845 a = a.__origin__
846 return a
847
848
849def _geqv(a, b):
850 """Return whether two generic classes are equivalent.
851
852 The intention is to consider generic class X and any of its
853 parameterized forms (X[T], X[int], etc.) as equivalent.
854
855 However, X is not equivalent to a subclass of X.
856
857 The relation is reflexive, symmetric and transitive.
858 """
859 assert isinstance(a, GenericMeta) and isinstance(b, GenericMeta)
860 # Reduce each to its origin.
861 return _gorg(a) is _gorg(b)
862
863
864class GenericMeta(TypingMeta, abc.ABCMeta):
865 """Metaclass for generic types."""
866
867 # TODO: Constrain more how Generic is used; only a few
868 # standard patterns should be allowed.
869
870 # TODO: Use a more precise rule than matching __name__ to decide
871 # whether two classes are the same. Also, save the formal
872 # parameters. (These things are related! A solution lies in
873 # using origin.)
874
875 __extra__ = None
876
877 def __new__(cls, name, bases, namespace,
878 parameters=None, origin=None, extra=None):
879 if parameters is None:
880 # Extract parameters from direct base classes. Only
881 # direct bases are considered and only those that are
882 # themselves generic, and parameterized with type
883 # variables. Don't use bases like Any, Union, Tuple,
884 # Callable or type variables.
885 params = None
886 for base in bases:
887 if isinstance(base, TypingMeta):
888 if not isinstance(base, GenericMeta):
889 raise TypeError(
890 "You cannot inherit from magic class %s" %
891 repr(base))
892 if base.__parameters__ is None:
893 continue # The base is unparameterized.
894 for bp in base.__parameters__:
895 if _has_type_var(bp) and not isinstance(bp, TypeVar):
896 raise TypeError(
897 "Cannot inherit from a generic class "
898 "parameterized with "
899 "non-type-variable %s" % bp)
900 if params is None:
901 params = []
902 if bp not in params:
903 params.append(bp)
904 if params is not None:
905 parameters = tuple(params)
906 self = super().__new__(cls, name, bases, namespace, _root=True)
907 self.__parameters__ = parameters
908 if extra is not None:
909 self.__extra__ = extra
910 # Else __extra__ is inherited, eventually from the
911 # (meta-)class default above.
912 self.__origin__ = origin
913 return self
914
915 def _has_type_var(self):
916 if self.__parameters__:
917 for t in self.__parameters__:
918 if _has_type_var(t):
919 return True
920 return False
921
922 def __repr__(self):
923 r = super().__repr__()
924 if self.__parameters__ is not None:
925 r += '[%s]' % (
926 ', '.join(_type_repr(p) for p in self.__parameters__))
927 return r
928
929 def __eq__(self, other):
930 if not isinstance(other, GenericMeta):
931 return NotImplemented
932 return (_geqv(self, other) and
933 self.__parameters__ == other.__parameters__)
934
935 def __hash__(self):
936 return hash((self.__name__, self.__parameters__))
937
938 def __getitem__(self, params):
939 if not isinstance(params, tuple):
940 params = (params,)
941 if not params:
942 raise TypeError("Cannot have empty parameter list")
943 msg = "Parameters to generic types must be types."
944 params = tuple(_type_check(p, msg) for p in params)
945 if self.__parameters__ is None:
946 for p in params:
947 if not isinstance(p, TypeVar):
948 raise TypeError("Initial parameters must be "
949 "type variables; got %s" % p)
950 else:
951 if len(params) != len(self.__parameters__):
952 raise TypeError("Cannot change parameter count from %d to %d" %
953 (len(self.__parameters__), len(params)))
954 for new, old in zip(params, self.__parameters__):
955 if isinstance(old, TypeVar):
956 if not old.__constraints__:
957 # Substituting for an unconstrained TypeVar is OK.
958 continue
959 if issubclass(new, Union[old.__constraints__]):
960 # Specializing a constrained type variable is OK.
961 continue
962 if not issubclass(new, old):
963 raise TypeError(
964 "Cannot substitute %s for %s in %s" %
965 (_type_repr(new), _type_repr(old), self))
966
967 return self.__class__(self.__name__, self.__bases__,
968 dict(self.__dict__),
969 parameters=params,
970 origin=self,
971 extra=self.__extra__)
972
973 def __subclasscheck__(self, cls):
974 if cls is Any:
975 return True
976 if isinstance(cls, GenericMeta):
977 # For a class C(Generic[T]) where T is co-variant,
978 # C[X] is a subclass of C[Y] iff X is a subclass of Y.
979 origin = self.__origin__
980 if origin is not None and origin is cls.__origin__:
981 assert len(self.__parameters__) == len(origin.__parameters__)
982 assert len(cls.__parameters__) == len(origin.__parameters__)
983 for p_self, p_cls, p_origin in zip(self.__parameters__,
984 cls.__parameters__,
985 origin.__parameters__):
986 if isinstance(p_origin, TypeVar):
987 if p_origin.__covariant__:
988 # Covariant -- p_cls must be a subclass of p_self.
989 if not issubclass(p_cls, p_self):
990 break
991 elif p_origin.__contravariant__:
992 # Contravariant. I think it's the opposite. :-)
993 if not issubclass(p_self, p_cls):
994 break
995 else:
996 # Invariant -- p_cls and p_self must equal.
997 if p_self != p_cls:
998 break
999 else:
1000 # If the origin's parameter is not a typevar,
1001 # insist on invariance.
1002 if p_self != p_cls:
1003 break
1004 else:
1005 return True
1006 # If we break out of the loop, the superclass gets a chance.
1007 if super().__subclasscheck__(cls):
1008 return True
1009 if self.__extra__ is None or isinstance(cls, GenericMeta):
1010 return False
1011 return issubclass(cls, self.__extra__)
1012
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001013
1014class Generic(metaclass=GenericMeta):
1015 """Abstract base class for generic types.
1016
1017 A generic type is typically declared by inheriting from an
1018 instantiation of this class with one or more type variables.
1019 For example, a generic mapping type might be defined as::
1020
1021 class Mapping(Generic[KT, VT]):
1022 def __getitem__(self, key: KT) -> VT:
1023 ...
1024 # Etc.
1025
1026 This class can then be used as follows::
1027
1028 def lookup_name(mapping: Mapping, key: KT, default: VT) -> VT:
1029 try:
1030 return mapping[key]
1031 except KeyError:
1032 return default
1033
1034 For clarity the type variables may be redefined, e.g.::
1035
1036 X = TypeVar('X')
1037 Y = TypeVar('Y')
1038 def lookup_name(mapping: Mapping[X, Y], key: X, default: Y) -> Y:
1039 # Same body as above.
1040 """
1041
1042 def __new__(cls, *args, **kwds):
1043 next_in_mro = object
1044 # Look for the last occurrence of Generic or Generic[...].
1045 for i, c in enumerate(cls.__mro__[:-1]):
1046 if isinstance(c, GenericMeta) and _gorg(c) is Generic:
1047 next_in_mro = cls.__mro__[i+1]
1048 return next_in_mro.__new__(_gorg(cls))
1049
1050
1051def cast(typ, val):
1052 """Cast a value to a type.
1053
1054 This returns the value unchanged. To the type checker this
1055 signals that the return value has the designated type, but at
1056 runtime we intentionally don't check anything (we want this
1057 to be as fast as possible).
1058 """
1059 return val
1060
1061
1062def _get_defaults(func):
1063 """Internal helper to extract the default arguments, by name."""
1064 code = func.__code__
1065 pos_count = code.co_argcount
1066 kw_count = code.co_kwonlyargcount
1067 arg_names = code.co_varnames
1068 kwarg_names = arg_names[pos_count:pos_count + kw_count]
1069 arg_names = arg_names[:pos_count]
1070 defaults = func.__defaults__ or ()
1071 kwdefaults = func.__kwdefaults__
1072 res = dict(kwdefaults) if kwdefaults else {}
1073 pos_offset = pos_count - len(defaults)
1074 for name, value in zip(arg_names[pos_offset:], defaults):
1075 assert name not in res
1076 res[name] = value
1077 return res
1078
1079
1080def get_type_hints(obj, globalns=None, localns=None):
1081 """Return type hints for a function or method object.
1082
1083 This is often the same as obj.__annotations__, but it handles
1084 forward references encoded as string literals, and if necessary
1085 adds Optional[t] if a default value equal to None is set.
1086
1087 BEWARE -- the behavior of globalns and localns is counterintuitive
1088 (unless you are familiar with how eval() and exec() work). The
1089 search order is locals first, then globals.
1090
1091 - If no dict arguments are passed, an attempt is made to use the
1092 globals from obj, and these are also used as the locals. If the
1093 object does not appear to have globals, an exception is raised.
1094
1095 - If one dict argument is passed, it is used for both globals and
1096 locals.
1097
1098 - If two dict arguments are passed, they specify globals and
1099 locals, respectively.
1100 """
1101 if getattr(obj, '__no_type_check__', None):
1102 return {}
1103 if globalns is None:
1104 globalns = getattr(obj, '__globals__', {})
1105 if localns is None:
1106 localns = globalns
1107 elif localns is None:
1108 localns = globalns
1109 defaults = _get_defaults(obj)
1110 hints = dict(obj.__annotations__)
1111 for name, value in hints.items():
1112 if isinstance(value, str):
1113 value = _ForwardRef(value)
1114 value = _eval_type(value, globalns, localns)
1115 if name in defaults and defaults[name] is None:
1116 value = Optional[value]
1117 hints[name] = value
1118 return hints
1119
1120
1121# TODO: Also support this as a class decorator.
1122def no_type_check(arg):
1123 """Decorator to indicate that annotations are not type hints.
1124
1125 The argument must be a class or function; if it is a class, it
1126 applies recursively to all methods defined in that class (but not
1127 to methods defined in its superclasses or subclasses).
1128
1129 This mutates the function(s) in place.
1130 """
1131 if isinstance(arg, type):
1132 for obj in arg.__dict__.values():
1133 if isinstance(obj, types.FunctionType):
1134 obj.__no_type_check__ = True
1135 else:
1136 arg.__no_type_check__ = True
1137 return arg
1138
1139
1140def no_type_check_decorator(decorator):
1141 """Decorator to give another decorator the @no_type_check effect.
1142
1143 This wraps the decorator with something that wraps the decorated
1144 function in @no_type_check.
1145 """
1146
1147 @functools.wraps(decorator)
1148 def wrapped_decorator(*args, **kwds):
1149 func = decorator(*args, **kwds)
1150 func = no_type_check(func)
1151 return func
1152
1153 return wrapped_decorator
1154
1155
1156def overload(func):
1157 raise RuntimeError("Overloading is only supported in library stubs")
1158
1159
1160class _ProtocolMeta(GenericMeta):
1161 """Internal metaclass for _Protocol.
1162
1163 This exists so _Protocol classes can be generic without deriving
1164 from Generic.
1165 """
1166
Guido van Rossum43a79cc2015-06-03 19:04:42 -07001167 def __instancecheck__(self, obj):
1168 raise TypeError("Protocols cannot be used with isinstance().")
1169
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001170 def __subclasscheck__(self, cls):
1171 if not self._is_protocol:
1172 # No structural checks since this isn't a protocol.
1173 return NotImplemented
1174
1175 if self is _Protocol:
1176 # Every class is a subclass of the empty protocol.
1177 return True
1178
1179 # Find all attributes defined in the protocol.
1180 attrs = self._get_protocol_attrs()
1181
1182 for attr in attrs:
1183 if not any(attr in d.__dict__ for d in cls.__mro__):
1184 return False
1185 return True
1186
1187 def _get_protocol_attrs(self):
1188 # Get all Protocol base classes.
1189 protocol_bases = []
1190 for c in self.__mro__:
1191 if getattr(c, '_is_protocol', False) and c.__name__ != '_Protocol':
1192 protocol_bases.append(c)
1193
1194 # Get attributes included in protocol.
1195 attrs = set()
1196 for base in protocol_bases:
1197 for attr in base.__dict__.keys():
1198 # Include attributes not defined in any non-protocol bases.
1199 for c in self.__mro__:
1200 if (c is not base and attr in c.__dict__ and
1201 not getattr(c, '_is_protocol', False)):
1202 break
1203 else:
1204 if (not attr.startswith('_abc_') and
1205 attr != '__abstractmethods__' and
1206 attr != '_is_protocol' and
1207 attr != '__dict__' and
1208 attr != '_get_protocol_attrs' and
1209 attr != '__parameters__' and
1210 attr != '__origin__' and
1211 attr != '__module__'):
1212 attrs.add(attr)
1213
1214 return attrs
1215
1216
1217class _Protocol(metaclass=_ProtocolMeta):
1218 """Internal base class for protocol classes.
1219
1220 This implements a simple-minded structural isinstance check
1221 (similar but more general than the one-offs in collections.abc
1222 such as Hashable).
1223 """
1224
1225 _is_protocol = True
1226
1227
1228# Various ABCs mimicking those in collections.abc.
1229# A few are simply re-exported for completeness.
1230
1231Hashable = collections_abc.Hashable # Not generic.
1232
1233
1234class Iterable(Generic[T_co], extra=collections_abc.Iterable):
1235 pass
1236
1237
1238class Iterator(Iterable[T_co], extra=collections_abc.Iterator):
1239 pass
1240
1241
1242class SupportsInt(_Protocol):
1243
1244 @abstractmethod
1245 def __int__(self) -> int:
1246 pass
1247
1248
1249class SupportsFloat(_Protocol):
1250
1251 @abstractmethod
1252 def __float__(self) -> float:
1253 pass
1254
1255
1256class SupportsComplex(_Protocol):
1257
1258 @abstractmethod
1259 def __complex__(self) -> complex:
1260 pass
1261
1262
1263class SupportsBytes(_Protocol):
1264
1265 @abstractmethod
1266 def __bytes__(self) -> bytes:
1267 pass
1268
1269
1270class SupportsAbs(_Protocol[T]):
1271
1272 @abstractmethod
1273 def __abs__(self) -> T:
1274 pass
1275
1276
1277class SupportsRound(_Protocol[T]):
1278
1279 @abstractmethod
1280 def __round__(self, ndigits: int = 0) -> T:
1281 pass
1282
1283
1284class Reversible(_Protocol[T]):
1285
1286 @abstractmethod
1287 def __reversed__(self) -> 'Iterator[T]':
1288 pass
1289
1290
1291Sized = collections_abc.Sized # Not generic.
1292
1293
1294class Container(Generic[T_co], extra=collections_abc.Container):
1295 pass
1296
1297
1298# Callable was defined earlier.
1299
1300
1301class AbstractSet(Sized, Iterable[T_co], Container[T_co],
1302 extra=collections_abc.Set):
1303 pass
1304
1305
1306class MutableSet(AbstractSet[T], extra=collections_abc.MutableSet):
1307 pass
1308
1309
Guido van Rossum79e434d2015-06-07 13:36:19 -07001310# NOTE: Only the value type is covariant.
1311class Mapping(Sized, Iterable[KT], Container[KT], Generic[KT, VT_co],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001312 extra=collections_abc.Mapping):
1313 pass
1314
1315
1316class MutableMapping(Mapping[KT, VT], extra=collections_abc.MutableMapping):
1317 pass
1318
1319
1320class Sequence(Sized, Iterable[T_co], Container[T_co],
1321 extra=collections_abc.Sequence):
1322 pass
1323
1324
1325class MutableSequence(Sequence[T], extra=collections_abc.MutableSequence):
1326 pass
1327
1328
1329class ByteString(Sequence[int], extra=collections_abc.ByteString):
1330 pass
1331
1332
1333ByteString.register(type(memoryview(b'')))
1334
1335
Guido van Rossum43a79cc2015-06-03 19:04:42 -07001336class List(list, MutableSequence[T]):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001337
1338 def __new__(cls, *args, **kwds):
1339 if _geqv(cls, List):
1340 raise TypeError("Type List cannot be instantiated; "
1341 "use list() instead")
1342 return list.__new__(cls, *args, **kwds)
1343
1344
Guido van Rossum43a79cc2015-06-03 19:04:42 -07001345class Set(set, MutableSet[T]):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001346
1347 def __new__(cls, *args, **kwds):
1348 if _geqv(cls, Set):
1349 raise TypeError("Type Set cannot be instantiated; "
1350 "use set() instead")
1351 return set.__new__(cls, *args, **kwds)
1352
1353
Guido van Rossum43a79cc2015-06-03 19:04:42 -07001354class _FrozenSetMeta(GenericMeta):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001355 """This metaclass ensures set is not a subclass of FrozenSet.
1356
1357 Without this metaclass, set would be considered a subclass of
1358 FrozenSet, because FrozenSet.__extra__ is collections.abc.Set, and
1359 set is a subclass of that.
1360 """
1361
1362 def __subclasscheck__(self, cls):
1363 if issubclass(cls, Set):
1364 return False
1365 return super().__subclasscheck__(cls)
1366
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001367
1368class FrozenSet(frozenset, AbstractSet[T_co], metaclass=_FrozenSetMeta):
1369
1370 def __new__(cls, *args, **kwds):
1371 if _geqv(cls, FrozenSet):
1372 raise TypeError("Type FrozenSet cannot be instantiated; "
1373 "use frozenset() instead")
1374 return frozenset.__new__(cls, *args, **kwds)
1375
1376
1377class MappingView(Sized, Iterable[T_co], extra=collections_abc.MappingView):
1378 pass
1379
1380
Guido van Rossum79e434d2015-06-07 13:36:19 -07001381class KeysView(MappingView[KT], AbstractSet[KT],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001382 extra=collections_abc.KeysView):
1383 pass
1384
1385
Guido van Rossum79e434d2015-06-07 13:36:19 -07001386# TODO: Enable Set[Tuple[KT, VT_co]] instead of Generic[KT, VT_co].
1387class ItemsView(MappingView, Generic[KT, VT_co],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001388 extra=collections_abc.ItemsView):
1389 pass
1390
1391
1392class ValuesView(MappingView[VT_co], extra=collections_abc.ValuesView):
1393 pass
1394
1395
Guido van Rossum43a79cc2015-06-03 19:04:42 -07001396class Dict(dict, MutableMapping[KT, VT]):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001397
1398 def __new__(cls, *args, **kwds):
1399 if _geqv(cls, Dict):
1400 raise TypeError("Type Dict cannot be instantiated; "
1401 "use dict() instead")
1402 return dict.__new__(cls, *args, **kwds)
1403
1404
1405# Determine what base class to use for Generator.
1406if hasattr(collections_abc, 'Generator'):
1407 # Sufficiently recent versions of 3.5 have a Generator ABC.
1408 _G_base = collections_abc.Generator
1409else:
1410 # Fall back on the exact type.
1411 _G_base = types.GeneratorType
1412
1413
1414class Generator(Iterator[T_co], Generic[T_co, T_contra, V_co],
1415 extra=_G_base):
1416
1417 def __new__(cls, *args, **kwds):
1418 if _geqv(cls, Generator):
1419 raise TypeError("Type Generator cannot be instantiated; "
1420 "create a subclass instead")
1421 return super().__new__(cls, *args, **kwds)
1422
1423
1424def NamedTuple(typename, fields):
1425 """Typed version of namedtuple.
1426
1427 Usage::
1428
1429 Employee = typing.NamedTuple('Employee', [('name', str), 'id', int)])
1430
1431 This is equivalent to::
1432
1433 Employee = collections.namedtuple('Employee', ['name', 'id'])
1434
1435 The resulting class has one extra attribute: _field_types,
1436 giving a dict mapping field names to types. (The field names
1437 are in the _fields attribute, which is part of the namedtuple
1438 API.)
1439 """
1440 fields = [(n, t) for n, t in fields]
1441 cls = collections.namedtuple(typename, [n for n, t in fields])
1442 cls._field_types = dict(fields)
1443 return cls
1444
1445
1446class IO(Generic[AnyStr]):
1447 """Generic base class for TextIO and BinaryIO.
1448
1449 This is an abstract, generic version of the return of open().
1450
1451 NOTE: This does not distinguish between the different possible
1452 classes (text vs. binary, read vs. write vs. read/write,
1453 append-only, unbuffered). The TextIO and BinaryIO subclasses
1454 below capture the distinctions between text vs. binary, which is
1455 pervasive in the interface; however we currently do not offer a
1456 way to track the other distinctions in the type system.
1457 """
1458
1459 @abstractproperty
1460 def mode(self) -> str:
1461 pass
1462
1463 @abstractproperty
1464 def name(self) -> str:
1465 pass
1466
1467 @abstractmethod
1468 def close(self) -> None:
1469 pass
1470
1471 @abstractmethod
1472 def closed(self) -> bool:
1473 pass
1474
1475 @abstractmethod
1476 def fileno(self) -> int:
1477 pass
1478
1479 @abstractmethod
1480 def flush(self) -> None:
1481 pass
1482
1483 @abstractmethod
1484 def isatty(self) -> bool:
1485 pass
1486
1487 @abstractmethod
1488 def read(self, n: int = -1) -> AnyStr:
1489 pass
1490
1491 @abstractmethod
1492 def readable(self) -> bool:
1493 pass
1494
1495 @abstractmethod
1496 def readline(self, limit: int = -1) -> AnyStr:
1497 pass
1498
1499 @abstractmethod
1500 def readlines(self, hint: int = -1) -> List[AnyStr]:
1501 pass
1502
1503 @abstractmethod
1504 def seek(self, offset: int, whence: int = 0) -> int:
1505 pass
1506
1507 @abstractmethod
1508 def seekable(self) -> bool:
1509 pass
1510
1511 @abstractmethod
1512 def tell(self) -> int:
1513 pass
1514
1515 @abstractmethod
1516 def truncate(self, size: int = None) -> int:
1517 pass
1518
1519 @abstractmethod
1520 def writable(self) -> bool:
1521 pass
1522
1523 @abstractmethod
1524 def write(self, s: AnyStr) -> int:
1525 pass
1526
1527 @abstractmethod
1528 def writelines(self, lines: List[AnyStr]) -> None:
1529 pass
1530
1531 @abstractmethod
1532 def __enter__(self) -> 'IO[AnyStr]':
1533 pass
1534
1535 @abstractmethod
1536 def __exit__(self, type, value, traceback) -> None:
1537 pass
1538
1539
1540class BinaryIO(IO[bytes]):
1541 """Typed version of the return of open() in binary mode."""
1542
1543 @abstractmethod
1544 def write(self, s: Union[bytes, bytearray]) -> int:
1545 pass
1546
1547 @abstractmethod
1548 def __enter__(self) -> 'BinaryIO':
1549 pass
1550
1551
1552class TextIO(IO[str]):
1553 """Typed version of the return of open() in text mode."""
1554
1555 @abstractproperty
1556 def buffer(self) -> BinaryIO:
1557 pass
1558
1559 @abstractproperty
1560 def encoding(self) -> str:
1561 pass
1562
1563 @abstractproperty
1564 def errors(self) -> str:
1565 pass
1566
1567 @abstractproperty
1568 def line_buffering(self) -> bool:
1569 pass
1570
1571 @abstractproperty
1572 def newlines(self) -> Any:
1573 pass
1574
1575 @abstractmethod
1576 def __enter__(self) -> 'TextIO':
1577 pass
1578
1579
1580class io:
1581 """Wrapper namespace for IO generic classes."""
1582
1583 __all__ = ['IO', 'TextIO', 'BinaryIO']
1584 IO = IO
1585 TextIO = TextIO
1586 BinaryIO = BinaryIO
1587
1588io.__name__ = __name__ + '.io'
1589sys.modules[io.__name__] = io
1590
1591
1592Pattern = _TypeAlias('Pattern', AnyStr, type(stdlib_re.compile('')),
1593 lambda p: p.pattern)
1594Match = _TypeAlias('Match', AnyStr, type(stdlib_re.match('', '')),
1595 lambda m: m.re.pattern)
1596
1597
1598class re:
1599 """Wrapper namespace for re type aliases."""
1600
1601 __all__ = ['Pattern', 'Match']
1602 Pattern = Pattern
1603 Match = Match
1604
1605re.__name__ = __name__ + '.re'
1606sys.modules[re.__name__] = re