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