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