blob: 66bee917d812725fc205e300ffd593782546e523 [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.
442KT_co = TypeVar('KT_co', covariant=True) # Key type covariant containers.
443VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
444T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
445
446# A useful type variable with constraints. This represents string types.
447# TODO: What about bytearray, memoryview?
448AnyStr = TypeVar('AnyStr', bytes, str)
449
450
451class UnionMeta(TypingMeta):
452 """Metaclass for Union."""
453
454 def __new__(cls, name, bases, namespace, parameters=None, _root=False):
455 if parameters is None:
456 return super().__new__(cls, name, bases, namespace, _root=_root)
457 if not isinstance(parameters, tuple):
458 raise TypeError("Expected parameters=<tuple>")
459 # Flatten out Union[Union[...], ...] and type-check non-Union args.
460 params = []
461 msg = "Union[arg, ...]: each arg must be a type."
462 for p in parameters:
463 if isinstance(p, UnionMeta):
464 params.extend(p.__union_params__)
465 else:
466 params.append(_type_check(p, msg))
467 # Weed out strict duplicates, preserving the first of each occurrence.
468 all_params = set(params)
469 if len(all_params) < len(params):
470 new_params = []
471 for t in params:
472 if t in all_params:
473 new_params.append(t)
474 all_params.remove(t)
475 params = new_params
476 assert not all_params, all_params
477 # Weed out subclasses.
478 # E.g. Union[int, Employee, Manager] == Union[int, Employee].
479 # If Any or object is present it will be the sole survivor.
480 # If both Any and object are present, Any wins.
481 # Never discard type variables, except against Any.
482 # (In particular, Union[str, AnyStr] != AnyStr.)
483 all_params = set(params)
484 for t1 in params:
485 if t1 is Any:
486 return Any
487 if isinstance(t1, TypeVar):
488 continue
489 if any(issubclass(t1, t2)
490 for t2 in all_params - {t1} if not isinstance(t2, TypeVar)):
491 all_params.remove(t1)
492 # It's not a union if there's only one type left.
493 if len(all_params) == 1:
494 return all_params.pop()
495 # Create a new class with these params.
496 self = super().__new__(cls, name, bases, {}, _root=True)
497 self.__union_params__ = tuple(t for t in params if t in all_params)
498 self.__union_set_params__ = frozenset(self.__union_params__)
499 return self
500
501 def _eval_type(self, globalns, localns):
502 p = tuple(_eval_type(t, globalns, localns)
503 for t in self.__union_params__)
504 if p == self.__union_params__:
505 return self
506 else:
507 return self.__class__(self.__name__, self.__bases__, {},
508 p, _root=True)
509
510 def _has_type_var(self):
511 if self.__union_params__:
512 for t in self.__union_params__:
513 if _has_type_var(t):
514 return True
515 return False
516
517 def __repr__(self):
518 r = super().__repr__()
519 if self.__union_params__:
520 r += '[%s]' % (', '.join(_type_repr(t)
521 for t in self.__union_params__))
522 return r
523
524 def __getitem__(self, parameters):
525 if self.__union_params__ is not None:
526 raise TypeError(
527 "Cannot subscript an existing Union. Use Union[u, t] instead.")
528 if parameters == ():
529 raise TypeError("Cannot take a Union of no types.")
530 if not isinstance(parameters, tuple):
531 parameters = (parameters,)
532 return self.__class__(self.__name__, self.__bases__,
533 dict(self.__dict__), parameters, _root=True)
534
535 def __eq__(self, other):
536 if not isinstance(other, UnionMeta):
537 return NotImplemented
538 return self.__union_set_params__ == other.__union_set_params__
539
540 def __hash__(self):
541 return hash(self.__union_set_params__)
542
Guido van Rossum43a79cc2015-06-03 19:04:42 -0700543 def __instancecheck__(self, obj):
544 raise TypeError("Unions cannot be used with isinstance().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700545
546 def __subclasscheck__(self, cls):
547 if cls is Any:
548 return True
549 if self.__union_params__ is None:
550 return isinstance(cls, UnionMeta)
551 elif isinstance(cls, UnionMeta):
552 if cls.__union_params__ is None:
553 return False
554 return all(issubclass(c, self) for c in (cls.__union_params__))
555 elif isinstance(cls, TypeVar):
556 if cls in self.__union_params__:
557 return True
558 if cls.__constraints__:
559 return issubclass(Union[cls.__constraints__], self)
560 return False
561 else:
562 return any(issubclass(cls, t) for t in self.__union_params__)
563
564
565class Union(Final, metaclass=UnionMeta, _root=True):
566 """Union type; Union[X, Y] means either X or Y.
567
568 To define a union, use e.g. Union[int, str]. Details:
569
570 - The arguments must be types and there must be at least one.
571
572 - None as an argument is a special case and is replaced by
573 type(None).
574
575 - Unions of unions are flattened, e.g.::
576
577 Union[Union[int, str], float] == Union[int, str, float]
578
579 - Unions of a single argument vanish, e.g.::
580
581 Union[int] == int # The constructor actually returns int
582
583 - Redundant arguments are skipped, e.g.::
584
585 Union[int, str, int] == Union[int, str]
586
587 - When comparing unions, the argument order is ignored, e.g.::
588
589 Union[int, str] == Union[str, int]
590
591 - When two arguments have a subclass relationship, the least
592 derived argument is kept, e.g.::
593
594 class Employee: pass
595 class Manager(Employee): pass
596 Union[int, Employee, Manager] == Union[int, Employee]
597 Union[Manager, int, Employee] == Union[int, Employee]
598 Union[Employee, Manager] == Employee
599
600 - Corollary: if Any is present it is the sole survivor, e.g.::
601
602 Union[int, Any] == Any
603
604 - Similar for object::
605
606 Union[int, object] == object
607
608 - To cut a tie: Union[object, Any] == Union[Any, object] == Any.
609
610 - You cannot subclass or instantiate a union.
611
612 - You cannot write Union[X][Y] (what would it mean?).
613
614 - You can use Optional[X] as a shorthand for Union[X, None].
615 """
616
617 # Unsubscripted Union type has params set to None.
618 __union_params__ = None
619 __union_set_params__ = None
620
621
622class OptionalMeta(TypingMeta):
623 """Metaclass for Optional."""
624
625 def __new__(cls, name, bases, namespace, _root=False):
626 return super().__new__(cls, name, bases, namespace, _root=_root)
627
628 def __getitem__(self, arg):
629 arg = _type_check(arg, "Optional[t] requires a single type.")
630 return Union[arg, type(None)]
631
632
633class Optional(Final, metaclass=OptionalMeta, _root=True):
634 """Optional type.
635
636 Optional[X] is equivalent to Union[X, type(None)].
637 """
638
639
640class TupleMeta(TypingMeta):
641 """Metaclass for Tuple."""
642
643 def __new__(cls, name, bases, namespace, parameters=None,
644 use_ellipsis=False, _root=False):
645 self = super().__new__(cls, name, bases, namespace, _root=_root)
646 self.__tuple_params__ = parameters
647 self.__tuple_use_ellipsis__ = use_ellipsis
648 return self
649
650 def _has_type_var(self):
651 if self.__tuple_params__:
652 for t in self.__tuple_params__:
653 if _has_type_var(t):
654 return True
655 return False
656
657 def _eval_type(self, globalns, localns):
658 tp = self.__tuple_params__
659 if tp is None:
660 return self
661 p = tuple(_eval_type(t, globalns, localns) for t in tp)
662 if p == self.__tuple_params__:
663 return self
664 else:
665 return self.__class__(self.__name__, self.__bases__, {},
666 p, _root=True)
667
668 def __repr__(self):
669 r = super().__repr__()
670 if self.__tuple_params__ is not None:
671 params = [_type_repr(p) for p in self.__tuple_params__]
672 if self.__tuple_use_ellipsis__:
673 params.append('...')
674 r += '[%s]' % (
675 ', '.join(params))
676 return r
677
678 def __getitem__(self, parameters):
679 if self.__tuple_params__ is not None:
680 raise TypeError("Cannot re-parameterize %r" % (self,))
681 if not isinstance(parameters, tuple):
682 parameters = (parameters,)
683 if len(parameters) == 2 and parameters[1] == Ellipsis:
684 parameters = parameters[:1]
685 use_ellipsis = True
686 msg = "Tuple[t, ...]: t must be a type."
687 else:
688 use_ellipsis = False
689 msg = "Tuple[t0, t1, ...]: each t must be a type."
690 parameters = tuple(_type_check(p, msg) for p in parameters)
691 return self.__class__(self.__name__, self.__bases__,
692 dict(self.__dict__), parameters,
693 use_ellipsis=use_ellipsis, _root=True)
694
695 def __eq__(self, other):
696 if not isinstance(other, TupleMeta):
697 return NotImplemented
698 return self.__tuple_params__ == other.__tuple_params__
699
700 def __hash__(self):
701 return hash(self.__tuple_params__)
702
Guido van Rossum43a79cc2015-06-03 19:04:42 -0700703 def __instancecheck__(self, obj):
704 raise TypeError("Tuples cannot be used with isinstance().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700705
706 def __subclasscheck__(self, cls):
707 if cls is Any:
708 return True
709 if not isinstance(cls, type):
710 return super().__subclasscheck__(cls) # To TypeError.
711 if issubclass(cls, tuple):
712 return True # Special case.
713 if not isinstance(cls, TupleMeta):
714 return super().__subclasscheck__(cls) # False.
715 if self.__tuple_params__ is None:
716 return True
717 if cls.__tuple_params__ is None:
718 return False # ???
719 if cls.__tuple_use_ellipsis__ != self.__tuple_use_ellipsis__:
720 return False
721 # Covariance.
722 return (len(self.__tuple_params__) == len(cls.__tuple_params__) and
723 all(issubclass(x, p)
724 for x, p in zip(cls.__tuple_params__,
725 self.__tuple_params__)))
726
727
728class Tuple(Final, metaclass=TupleMeta, _root=True):
729 """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
730
731 Example: Tuple[T1, T2] is a tuple of two elements corresponding
732 to type variables T1 and T2. Tuple[int, float, str] is a tuple
733 of an int, a float and a string.
734
735 To specify a variable-length tuple of homogeneous type, use Sequence[T].
736 """
737
738
739class CallableMeta(TypingMeta):
740 """Metaclass for Callable."""
741
742 def __new__(cls, name, bases, namespace, _root=False,
743 args=None, result=None):
744 if args is None and result is None:
745 pass # Must be 'class Callable'.
746 else:
747 if args is not Ellipsis:
748 if not isinstance(args, list):
749 raise TypeError("Callable[args, result]: "
750 "args must be a list."
751 " Got %.100r." % (args,))
752 msg = "Callable[[arg, ...], result]: each arg must be a type."
753 args = tuple(_type_check(arg, msg) for arg in args)
754 msg = "Callable[args, result]: result must be a type."
755 result = _type_check(result, msg)
756 self = super().__new__(cls, name, bases, namespace, _root=_root)
757 self.__args__ = args
758 self.__result__ = result
759 return self
760
761 def _has_type_var(self):
762 if self.__args__:
763 for t in self.__args__:
764 if _has_type_var(t):
765 return True
766 return _has_type_var(self.__result__)
767
768 def _eval_type(self, globalns, localns):
769 if self.__args__ is None and self.__result__ is None:
770 return self
771 args = [_eval_type(t, globalns, localns) for t in self.__args__]
772 result = _eval_type(self.__result__, globalns, localns)
773 if args == self.__args__ and result == self.__result__:
774 return self
775 else:
776 return self.__class__(self.__name__, self.__bases__, {},
777 args=args, result=result, _root=True)
778
779 def __repr__(self):
780 r = super().__repr__()
781 if self.__args__ is not None or self.__result__ is not None:
782 if self.__args__ is Ellipsis:
783 args_r = '...'
784 else:
785 args_r = '[%s]' % ', '.join(_type_repr(t)
786 for t in self.__args__)
787 r += '[%s, %s]' % (args_r, _type_repr(self.__result__))
788 return r
789
790 def __getitem__(self, parameters):
791 if self.__args__ is not None or self.__result__ is not None:
792 raise TypeError("This Callable type is already parameterized.")
793 if not isinstance(parameters, tuple) or len(parameters) != 2:
794 raise TypeError(
795 "Callable must be used as Callable[[arg, ...], result].")
796 args, result = parameters
797 return self.__class__(self.__name__, self.__bases__,
798 dict(self.__dict__), _root=True,
799 args=args, result=result)
800
801 def __eq__(self, other):
802 if not isinstance(other, CallableMeta):
803 return NotImplemented
804 return (self.__args__ == other.__args__ and
805 self.__result__ == other.__result__)
806
807 def __hash__(self):
808 return hash(self.__args__) ^ hash(self.__result__)
809
Guido van Rossum43a79cc2015-06-03 19:04:42 -0700810 def __instancecheck__(self, obj):
811 # For unparametrized Callable we allow this, because
812 # typing.Callable should be equivalent to
813 # collections.abc.Callable.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700814 if self.__args__ is None and self.__result__ is None:
Guido van Rossum43a79cc2015-06-03 19:04:42 -0700815 return isinstance(obj, collections_abc.Callable)
816 else:
817 raise TypeError("Callable[] cannot be used with isinstance().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700818
819 def __subclasscheck__(self, cls):
820 if cls is Any:
821 return True
822 if not isinstance(cls, CallableMeta):
823 return super().__subclasscheck__(cls)
824 if self.__args__ is None and self.__result__ is None:
825 return True
826 # We're not doing covariance or contravariance -- this is *invariance*.
827 return self == cls
828
829
830class Callable(Final, metaclass=CallableMeta, _root=True):
831 """Callable type; Callable[[int], str] is a function of (int) -> str.
832
833 The subscription syntax must always be used with exactly two
834 values: the argument list and the return type. The argument list
835 must be a list of types; the return type must be a single type.
836
837 There is no syntax to indicate optional or keyword arguments,
838 such function types are rarely used as callback types.
839 """
840
841
842def _gorg(a):
843 """Return the farthest origin of a generic class."""
844 assert isinstance(a, GenericMeta)
845 while a.__origin__ is not None:
846 a = a.__origin__
847 return a
848
849
850def _geqv(a, b):
851 """Return whether two generic classes are equivalent.
852
853 The intention is to consider generic class X and any of its
854 parameterized forms (X[T], X[int], etc.) as equivalent.
855
856 However, X is not equivalent to a subclass of X.
857
858 The relation is reflexive, symmetric and transitive.
859 """
860 assert isinstance(a, GenericMeta) and isinstance(b, GenericMeta)
861 # Reduce each to its origin.
862 return _gorg(a) is _gorg(b)
863
864
865class GenericMeta(TypingMeta, abc.ABCMeta):
866 """Metaclass for generic types."""
867
868 # TODO: Constrain more how Generic is used; only a few
869 # standard patterns should be allowed.
870
871 # TODO: Use a more precise rule than matching __name__ to decide
872 # whether two classes are the same. Also, save the formal
873 # parameters. (These things are related! A solution lies in
874 # using origin.)
875
876 __extra__ = None
877
878 def __new__(cls, name, bases, namespace,
879 parameters=None, origin=None, extra=None):
880 if parameters is None:
881 # Extract parameters from direct base classes. Only
882 # direct bases are considered and only those that are
883 # themselves generic, and parameterized with type
884 # variables. Don't use bases like Any, Union, Tuple,
885 # Callable or type variables.
886 params = None
887 for base in bases:
888 if isinstance(base, TypingMeta):
889 if not isinstance(base, GenericMeta):
890 raise TypeError(
891 "You cannot inherit from magic class %s" %
892 repr(base))
893 if base.__parameters__ is None:
894 continue # The base is unparameterized.
895 for bp in base.__parameters__:
896 if _has_type_var(bp) and not isinstance(bp, TypeVar):
897 raise TypeError(
898 "Cannot inherit from a generic class "
899 "parameterized with "
900 "non-type-variable %s" % bp)
901 if params is None:
902 params = []
903 if bp not in params:
904 params.append(bp)
905 if params is not None:
906 parameters = tuple(params)
907 self = super().__new__(cls, name, bases, namespace, _root=True)
908 self.__parameters__ = parameters
909 if extra is not None:
910 self.__extra__ = extra
911 # Else __extra__ is inherited, eventually from the
912 # (meta-)class default above.
913 self.__origin__ = origin
914 return self
915
916 def _has_type_var(self):
917 if self.__parameters__:
918 for t in self.__parameters__:
919 if _has_type_var(t):
920 return True
921 return False
922
923 def __repr__(self):
924 r = super().__repr__()
925 if self.__parameters__ is not None:
926 r += '[%s]' % (
927 ', '.join(_type_repr(p) for p in self.__parameters__))
928 return r
929
930 def __eq__(self, other):
931 if not isinstance(other, GenericMeta):
932 return NotImplemented
933 return (_geqv(self, other) and
934 self.__parameters__ == other.__parameters__)
935
936 def __hash__(self):
937 return hash((self.__name__, self.__parameters__))
938
939 def __getitem__(self, params):
940 if not isinstance(params, tuple):
941 params = (params,)
942 if not params:
943 raise TypeError("Cannot have empty parameter list")
944 msg = "Parameters to generic types must be types."
945 params = tuple(_type_check(p, msg) for p in params)
946 if self.__parameters__ is None:
947 for p in params:
948 if not isinstance(p, TypeVar):
949 raise TypeError("Initial parameters must be "
950 "type variables; got %s" % p)
951 else:
952 if len(params) != len(self.__parameters__):
953 raise TypeError("Cannot change parameter count from %d to %d" %
954 (len(self.__parameters__), len(params)))
955 for new, old in zip(params, self.__parameters__):
956 if isinstance(old, TypeVar):
957 if not old.__constraints__:
958 # Substituting for an unconstrained TypeVar is OK.
959 continue
960 if issubclass(new, Union[old.__constraints__]):
961 # Specializing a constrained type variable is OK.
962 continue
963 if not issubclass(new, old):
964 raise TypeError(
965 "Cannot substitute %s for %s in %s" %
966 (_type_repr(new), _type_repr(old), self))
967
968 return self.__class__(self.__name__, self.__bases__,
969 dict(self.__dict__),
970 parameters=params,
971 origin=self,
972 extra=self.__extra__)
973
974 def __subclasscheck__(self, cls):
975 if cls is Any:
976 return True
977 if isinstance(cls, GenericMeta):
978 # For a class C(Generic[T]) where T is co-variant,
979 # C[X] is a subclass of C[Y] iff X is a subclass of Y.
980 origin = self.__origin__
981 if origin is not None and origin is cls.__origin__:
982 assert len(self.__parameters__) == len(origin.__parameters__)
983 assert len(cls.__parameters__) == len(origin.__parameters__)
984 for p_self, p_cls, p_origin in zip(self.__parameters__,
985 cls.__parameters__,
986 origin.__parameters__):
987 if isinstance(p_origin, TypeVar):
988 if p_origin.__covariant__:
989 # Covariant -- p_cls must be a subclass of p_self.
990 if not issubclass(p_cls, p_self):
991 break
992 elif p_origin.__contravariant__:
993 # Contravariant. I think it's the opposite. :-)
994 if not issubclass(p_self, p_cls):
995 break
996 else:
997 # Invariant -- p_cls and p_self must equal.
998 if p_self != p_cls:
999 break
1000 else:
1001 # If the origin's parameter is not a typevar,
1002 # insist on invariance.
1003 if p_self != p_cls:
1004 break
1005 else:
1006 return True
1007 # If we break out of the loop, the superclass gets a chance.
1008 if super().__subclasscheck__(cls):
1009 return True
1010 if self.__extra__ is None or isinstance(cls, GenericMeta):
1011 return False
1012 return issubclass(cls, self.__extra__)
1013
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001014
1015class Generic(metaclass=GenericMeta):
1016 """Abstract base class for generic types.
1017
1018 A generic type is typically declared by inheriting from an
1019 instantiation of this class with one or more type variables.
1020 For example, a generic mapping type might be defined as::
1021
1022 class Mapping(Generic[KT, VT]):
1023 def __getitem__(self, key: KT) -> VT:
1024 ...
1025 # Etc.
1026
1027 This class can then be used as follows::
1028
1029 def lookup_name(mapping: Mapping, key: KT, default: VT) -> VT:
1030 try:
1031 return mapping[key]
1032 except KeyError:
1033 return default
1034
1035 For clarity the type variables may be redefined, e.g.::
1036
1037 X = TypeVar('X')
1038 Y = TypeVar('Y')
1039 def lookup_name(mapping: Mapping[X, Y], key: X, default: Y) -> Y:
1040 # Same body as above.
1041 """
1042
1043 def __new__(cls, *args, **kwds):
1044 next_in_mro = object
1045 # Look for the last occurrence of Generic or Generic[...].
1046 for i, c in enumerate(cls.__mro__[:-1]):
1047 if isinstance(c, GenericMeta) and _gorg(c) is Generic:
1048 next_in_mro = cls.__mro__[i+1]
1049 return next_in_mro.__new__(_gorg(cls))
1050
1051
1052def cast(typ, val):
1053 """Cast a value to a type.
1054
1055 This returns the value unchanged. To the type checker this
1056 signals that the return value has the designated type, but at
1057 runtime we intentionally don't check anything (we want this
1058 to be as fast as possible).
1059 """
1060 return val
1061
1062
1063def _get_defaults(func):
1064 """Internal helper to extract the default arguments, by name."""
1065 code = func.__code__
1066 pos_count = code.co_argcount
1067 kw_count = code.co_kwonlyargcount
1068 arg_names = code.co_varnames
1069 kwarg_names = arg_names[pos_count:pos_count + kw_count]
1070 arg_names = arg_names[:pos_count]
1071 defaults = func.__defaults__ or ()
1072 kwdefaults = func.__kwdefaults__
1073 res = dict(kwdefaults) if kwdefaults else {}
1074 pos_offset = pos_count - len(defaults)
1075 for name, value in zip(arg_names[pos_offset:], defaults):
1076 assert name not in res
1077 res[name] = value
1078 return res
1079
1080
1081def get_type_hints(obj, globalns=None, localns=None):
1082 """Return type hints for a function or method object.
1083
1084 This is often the same as obj.__annotations__, but it handles
1085 forward references encoded as string literals, and if necessary
1086 adds Optional[t] if a default value equal to None is set.
1087
1088 BEWARE -- the behavior of globalns and localns is counterintuitive
1089 (unless you are familiar with how eval() and exec() work). The
1090 search order is locals first, then globals.
1091
1092 - If no dict arguments are passed, an attempt is made to use the
1093 globals from obj, and these are also used as the locals. If the
1094 object does not appear to have globals, an exception is raised.
1095
1096 - If one dict argument is passed, it is used for both globals and
1097 locals.
1098
1099 - If two dict arguments are passed, they specify globals and
1100 locals, respectively.
1101 """
1102 if getattr(obj, '__no_type_check__', None):
1103 return {}
1104 if globalns is None:
1105 globalns = getattr(obj, '__globals__', {})
1106 if localns is None:
1107 localns = globalns
1108 elif localns is None:
1109 localns = globalns
1110 defaults = _get_defaults(obj)
1111 hints = dict(obj.__annotations__)
1112 for name, value in hints.items():
1113 if isinstance(value, str):
1114 value = _ForwardRef(value)
1115 value = _eval_type(value, globalns, localns)
1116 if name in defaults and defaults[name] is None:
1117 value = Optional[value]
1118 hints[name] = value
1119 return hints
1120
1121
1122# TODO: Also support this as a class decorator.
1123def no_type_check(arg):
1124 """Decorator to indicate that annotations are not type hints.
1125
1126 The argument must be a class or function; if it is a class, it
1127 applies recursively to all methods defined in that class (but not
1128 to methods defined in its superclasses or subclasses).
1129
1130 This mutates the function(s) in place.
1131 """
1132 if isinstance(arg, type):
1133 for obj in arg.__dict__.values():
1134 if isinstance(obj, types.FunctionType):
1135 obj.__no_type_check__ = True
1136 else:
1137 arg.__no_type_check__ = True
1138 return arg
1139
1140
1141def no_type_check_decorator(decorator):
1142 """Decorator to give another decorator the @no_type_check effect.
1143
1144 This wraps the decorator with something that wraps the decorated
1145 function in @no_type_check.
1146 """
1147
1148 @functools.wraps(decorator)
1149 def wrapped_decorator(*args, **kwds):
1150 func = decorator(*args, **kwds)
1151 func = no_type_check(func)
1152 return func
1153
1154 return wrapped_decorator
1155
1156
1157def overload(func):
1158 raise RuntimeError("Overloading is only supported in library stubs")
1159
1160
1161class _ProtocolMeta(GenericMeta):
1162 """Internal metaclass for _Protocol.
1163
1164 This exists so _Protocol classes can be generic without deriving
1165 from Generic.
1166 """
1167
Guido van Rossum43a79cc2015-06-03 19:04:42 -07001168 def __instancecheck__(self, obj):
1169 raise TypeError("Protocols cannot be used with isinstance().")
1170
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001171 def __subclasscheck__(self, cls):
1172 if not self._is_protocol:
1173 # No structural checks since this isn't a protocol.
1174 return NotImplemented
1175
1176 if self is _Protocol:
1177 # Every class is a subclass of the empty protocol.
1178 return True
1179
1180 # Find all attributes defined in the protocol.
1181 attrs = self._get_protocol_attrs()
1182
1183 for attr in attrs:
1184 if not any(attr in d.__dict__ for d in cls.__mro__):
1185 return False
1186 return True
1187
1188 def _get_protocol_attrs(self):
1189 # Get all Protocol base classes.
1190 protocol_bases = []
1191 for c in self.__mro__:
1192 if getattr(c, '_is_protocol', False) and c.__name__ != '_Protocol':
1193 protocol_bases.append(c)
1194
1195 # Get attributes included in protocol.
1196 attrs = set()
1197 for base in protocol_bases:
1198 for attr in base.__dict__.keys():
1199 # Include attributes not defined in any non-protocol bases.
1200 for c in self.__mro__:
1201 if (c is not base and attr in c.__dict__ and
1202 not getattr(c, '_is_protocol', False)):
1203 break
1204 else:
1205 if (not attr.startswith('_abc_') and
1206 attr != '__abstractmethods__' and
1207 attr != '_is_protocol' and
1208 attr != '__dict__' and
1209 attr != '_get_protocol_attrs' and
1210 attr != '__parameters__' and
1211 attr != '__origin__' and
1212 attr != '__module__'):
1213 attrs.add(attr)
1214
1215 return attrs
1216
1217
1218class _Protocol(metaclass=_ProtocolMeta):
1219 """Internal base class for protocol classes.
1220
1221 This implements a simple-minded structural isinstance check
1222 (similar but more general than the one-offs in collections.abc
1223 such as Hashable).
1224 """
1225
1226 _is_protocol = True
1227
1228
1229# Various ABCs mimicking those in collections.abc.
1230# A few are simply re-exported for completeness.
1231
1232Hashable = collections_abc.Hashable # Not generic.
1233
1234
1235class Iterable(Generic[T_co], extra=collections_abc.Iterable):
1236 pass
1237
1238
1239class Iterator(Iterable[T_co], extra=collections_abc.Iterator):
1240 pass
1241
1242
1243class SupportsInt(_Protocol):
1244
1245 @abstractmethod
1246 def __int__(self) -> int:
1247 pass
1248
1249
1250class SupportsFloat(_Protocol):
1251
1252 @abstractmethod
1253 def __float__(self) -> float:
1254 pass
1255
1256
1257class SupportsComplex(_Protocol):
1258
1259 @abstractmethod
1260 def __complex__(self) -> complex:
1261 pass
1262
1263
1264class SupportsBytes(_Protocol):
1265
1266 @abstractmethod
1267 def __bytes__(self) -> bytes:
1268 pass
1269
1270
1271class SupportsAbs(_Protocol[T]):
1272
1273 @abstractmethod
1274 def __abs__(self) -> T:
1275 pass
1276
1277
1278class SupportsRound(_Protocol[T]):
1279
1280 @abstractmethod
1281 def __round__(self, ndigits: int = 0) -> T:
1282 pass
1283
1284
1285class Reversible(_Protocol[T]):
1286
1287 @abstractmethod
1288 def __reversed__(self) -> 'Iterator[T]':
1289 pass
1290
1291
1292Sized = collections_abc.Sized # Not generic.
1293
1294
1295class Container(Generic[T_co], extra=collections_abc.Container):
1296 pass
1297
1298
1299# Callable was defined earlier.
1300
1301
1302class AbstractSet(Sized, Iterable[T_co], Container[T_co],
1303 extra=collections_abc.Set):
1304 pass
1305
1306
1307class MutableSet(AbstractSet[T], extra=collections_abc.MutableSet):
1308 pass
1309
1310
1311class Mapping(Sized, Iterable[KT_co], Container[KT_co], Generic[KT_co, VT_co],
1312 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
1381class KeysView(MappingView[KT_co], AbstractSet[KT_co],
1382 extra=collections_abc.KeysView):
1383 pass
1384
1385
1386# TODO: Enable Set[Tuple[KT_co, VT_co]] instead of Generic[KT_co, VT_co].
1387class ItemsView(MappingView, Generic[KT_co, VT_co],
1388 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