blob: 1a4982ead9a3e49a8e3c8748b92dcf85a12fcd7f [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
490 if any(issubclass(t1, t2)
491 for t2 in all_params - {t1} if not isinstance(t2, TypeVar)):
492 all_params.remove(t1)
493 # It's not a union if there's only one type left.
494 if len(all_params) == 1:
495 return all_params.pop()
496 # Create a new class with these params.
497 self = super().__new__(cls, name, bases, {}, _root=True)
498 self.__union_params__ = tuple(t for t in params if t in all_params)
499 self.__union_set_params__ = frozenset(self.__union_params__)
500 return self
501
502 def _eval_type(self, globalns, localns):
503 p = tuple(_eval_type(t, globalns, localns)
504 for t in self.__union_params__)
505 if p == self.__union_params__:
506 return self
507 else:
508 return self.__class__(self.__name__, self.__bases__, {},
509 p, _root=True)
510
511 def _has_type_var(self):
512 if self.__union_params__:
513 for t in self.__union_params__:
514 if _has_type_var(t):
515 return True
516 return False
517
518 def __repr__(self):
519 r = super().__repr__()
520 if self.__union_params__:
521 r += '[%s]' % (', '.join(_type_repr(t)
522 for t in self.__union_params__))
523 return r
524
525 def __getitem__(self, parameters):
526 if self.__union_params__ is not None:
527 raise TypeError(
528 "Cannot subscript an existing Union. Use Union[u, t] instead.")
529 if parameters == ():
530 raise TypeError("Cannot take a Union of no types.")
531 if not isinstance(parameters, tuple):
532 parameters = (parameters,)
533 return self.__class__(self.__name__, self.__bases__,
534 dict(self.__dict__), parameters, _root=True)
535
536 def __eq__(self, other):
537 if not isinstance(other, UnionMeta):
538 return NotImplemented
539 return self.__union_set_params__ == other.__union_set_params__
540
541 def __hash__(self):
542 return hash(self.__union_set_params__)
543
Guido van Rossumd70fe632015-08-05 12:11:06 +0200544 def __instancecheck__(self, obj):
545 raise TypeError("Unions cannot be used with isinstance().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700546
547 def __subclasscheck__(self, cls):
548 if cls is Any:
549 return True
550 if self.__union_params__ is None:
551 return isinstance(cls, UnionMeta)
552 elif isinstance(cls, UnionMeta):
553 if cls.__union_params__ is None:
554 return False
555 return all(issubclass(c, self) for c in (cls.__union_params__))
556 elif isinstance(cls, TypeVar):
557 if cls in self.__union_params__:
558 return True
559 if cls.__constraints__:
560 return issubclass(Union[cls.__constraints__], self)
561 return False
562 else:
563 return any(issubclass(cls, t) for t in self.__union_params__)
564
565
566class Union(Final, metaclass=UnionMeta, _root=True):
567 """Union type; Union[X, Y] means either X or Y.
568
569 To define a union, use e.g. Union[int, str]. Details:
570
571 - The arguments must be types and there must be at least one.
572
573 - None as an argument is a special case and is replaced by
574 type(None).
575
576 - Unions of unions are flattened, e.g.::
577
578 Union[Union[int, str], float] == Union[int, str, float]
579
580 - Unions of a single argument vanish, e.g.::
581
582 Union[int] == int # The constructor actually returns int
583
584 - Redundant arguments are skipped, e.g.::
585
586 Union[int, str, int] == Union[int, str]
587
588 - When comparing unions, the argument order is ignored, e.g.::
589
590 Union[int, str] == Union[str, int]
591
592 - When two arguments have a subclass relationship, the least
593 derived argument is kept, e.g.::
594
595 class Employee: pass
596 class Manager(Employee): pass
597 Union[int, Employee, Manager] == Union[int, Employee]
598 Union[Manager, int, Employee] == Union[int, Employee]
599 Union[Employee, Manager] == Employee
600
601 - Corollary: if Any is present it is the sole survivor, e.g.::
602
603 Union[int, Any] == Any
604
605 - Similar for object::
606
607 Union[int, object] == object
608
609 - To cut a tie: Union[object, Any] == Union[Any, object] == Any.
610
611 - You cannot subclass or instantiate a union.
612
613 - You cannot write Union[X][Y] (what would it mean?).
614
615 - You can use Optional[X] as a shorthand for Union[X, None].
616 """
617
618 # Unsubscripted Union type has params set to None.
619 __union_params__ = None
620 __union_set_params__ = None
621
622
623class OptionalMeta(TypingMeta):
624 """Metaclass for Optional."""
625
626 def __new__(cls, name, bases, namespace, _root=False):
627 return super().__new__(cls, name, bases, namespace, _root=_root)
628
629 def __getitem__(self, arg):
630 arg = _type_check(arg, "Optional[t] requires a single type.")
631 return Union[arg, type(None)]
632
633
634class Optional(Final, metaclass=OptionalMeta, _root=True):
635 """Optional type.
636
637 Optional[X] is equivalent to Union[X, type(None)].
638 """
639
Guido van Rossumd70fe632015-08-05 12:11:06 +0200640 __slots__ = ()
641
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700642
643class TupleMeta(TypingMeta):
644 """Metaclass for Tuple."""
645
646 def __new__(cls, name, bases, namespace, parameters=None,
647 use_ellipsis=False, _root=False):
648 self = super().__new__(cls, name, bases, namespace, _root=_root)
649 self.__tuple_params__ = parameters
650 self.__tuple_use_ellipsis__ = use_ellipsis
651 return self
652
653 def _has_type_var(self):
654 if self.__tuple_params__:
655 for t in self.__tuple_params__:
656 if _has_type_var(t):
657 return True
658 return False
659
660 def _eval_type(self, globalns, localns):
661 tp = self.__tuple_params__
662 if tp is None:
663 return self
664 p = tuple(_eval_type(t, globalns, localns) for t in tp)
665 if p == self.__tuple_params__:
666 return self
667 else:
668 return self.__class__(self.__name__, self.__bases__, {},
669 p, _root=True)
670
671 def __repr__(self):
672 r = super().__repr__()
673 if self.__tuple_params__ is not None:
674 params = [_type_repr(p) for p in self.__tuple_params__]
675 if self.__tuple_use_ellipsis__:
676 params.append('...')
677 r += '[%s]' % (
678 ', '.join(params))
679 return r
680
681 def __getitem__(self, parameters):
682 if self.__tuple_params__ is not None:
683 raise TypeError("Cannot re-parameterize %r" % (self,))
684 if not isinstance(parameters, tuple):
685 parameters = (parameters,)
686 if len(parameters) == 2 and parameters[1] == Ellipsis:
687 parameters = parameters[:1]
688 use_ellipsis = True
689 msg = "Tuple[t, ...]: t must be a type."
690 else:
691 use_ellipsis = False
692 msg = "Tuple[t0, t1, ...]: each t must be a type."
693 parameters = tuple(_type_check(p, msg) for p in parameters)
694 return self.__class__(self.__name__, self.__bases__,
695 dict(self.__dict__), parameters,
696 use_ellipsis=use_ellipsis, _root=True)
697
698 def __eq__(self, other):
699 if not isinstance(other, TupleMeta):
700 return NotImplemented
701 return self.__tuple_params__ == other.__tuple_params__
702
703 def __hash__(self):
704 return hash(self.__tuple_params__)
705
Guido van Rossumd70fe632015-08-05 12:11:06 +0200706 def __instancecheck__(self, obj):
707 raise TypeError("Tuples cannot be used with isinstance().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700708
709 def __subclasscheck__(self, cls):
710 if cls is Any:
711 return True
712 if not isinstance(cls, type):
713 return super().__subclasscheck__(cls) # To TypeError.
714 if issubclass(cls, tuple):
715 return True # Special case.
716 if not isinstance(cls, TupleMeta):
717 return super().__subclasscheck__(cls) # False.
718 if self.__tuple_params__ is None:
719 return True
720 if cls.__tuple_params__ is None:
721 return False # ???
722 if cls.__tuple_use_ellipsis__ != self.__tuple_use_ellipsis__:
723 return False
724 # Covariance.
725 return (len(self.__tuple_params__) == len(cls.__tuple_params__) and
726 all(issubclass(x, p)
727 for x, p in zip(cls.__tuple_params__,
728 self.__tuple_params__)))
729
730
731class Tuple(Final, metaclass=TupleMeta, _root=True):
732 """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
733
734 Example: Tuple[T1, T2] is a tuple of two elements corresponding
735 to type variables T1 and T2. Tuple[int, float, str] is a tuple
736 of an int, a float and a string.
737
738 To specify a variable-length tuple of homogeneous type, use Sequence[T].
739 """
740
Guido van Rossumd70fe632015-08-05 12:11:06 +0200741 __slots__ = ()
742
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700743
744class CallableMeta(TypingMeta):
745 """Metaclass for Callable."""
746
747 def __new__(cls, name, bases, namespace, _root=False,
748 args=None, result=None):
749 if args is None and result is None:
750 pass # Must be 'class Callable'.
751 else:
752 if args is not Ellipsis:
753 if not isinstance(args, list):
754 raise TypeError("Callable[args, result]: "
755 "args must be a list."
756 " Got %.100r." % (args,))
757 msg = "Callable[[arg, ...], result]: each arg must be a type."
758 args = tuple(_type_check(arg, msg) for arg in args)
759 msg = "Callable[args, result]: result must be a type."
760 result = _type_check(result, msg)
761 self = super().__new__(cls, name, bases, namespace, _root=_root)
762 self.__args__ = args
763 self.__result__ = result
764 return self
765
766 def _has_type_var(self):
767 if self.__args__:
768 for t in self.__args__:
769 if _has_type_var(t):
770 return True
771 return _has_type_var(self.__result__)
772
773 def _eval_type(self, globalns, localns):
774 if self.__args__ is None and self.__result__ is None:
775 return self
Guido van Rossumd70fe632015-08-05 12:11:06 +0200776 if self.__args__ is Ellipsis:
777 args = self.__args__
778 else:
779 args = [_eval_type(t, globalns, localns) for t in self.__args__]
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700780 result = _eval_type(self.__result__, globalns, localns)
781 if args == self.__args__ and result == self.__result__:
782 return self
783 else:
784 return self.__class__(self.__name__, self.__bases__, {},
785 args=args, result=result, _root=True)
786
787 def __repr__(self):
788 r = super().__repr__()
789 if self.__args__ is not None or self.__result__ is not None:
790 if self.__args__ is Ellipsis:
791 args_r = '...'
792 else:
793 args_r = '[%s]' % ', '.join(_type_repr(t)
794 for t in self.__args__)
795 r += '[%s, %s]' % (args_r, _type_repr(self.__result__))
796 return r
797
798 def __getitem__(self, parameters):
799 if self.__args__ is not None or self.__result__ is not None:
800 raise TypeError("This Callable type is already parameterized.")
801 if not isinstance(parameters, tuple) or len(parameters) != 2:
802 raise TypeError(
803 "Callable must be used as Callable[[arg, ...], result].")
804 args, result = parameters
805 return self.__class__(self.__name__, self.__bases__,
806 dict(self.__dict__), _root=True,
807 args=args, result=result)
808
809 def __eq__(self, other):
810 if not isinstance(other, CallableMeta):
811 return NotImplemented
812 return (self.__args__ == other.__args__ and
813 self.__result__ == other.__result__)
814
815 def __hash__(self):
816 return hash(self.__args__) ^ hash(self.__result__)
817
Guido van Rossumd70fe632015-08-05 12:11:06 +0200818 def __instancecheck__(self, obj):
819 # For unparametrized Callable we allow this, because
820 # typing.Callable should be equivalent to
821 # collections.abc.Callable.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700822 if self.__args__ is None and self.__result__ is None:
Guido van Rossumd70fe632015-08-05 12:11:06 +0200823 return isinstance(obj, collections_abc.Callable)
824 else:
825 raise TypeError("Callable[] cannot be used with isinstance().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700826
827 def __subclasscheck__(self, cls):
828 if cls is Any:
829 return True
830 if not isinstance(cls, CallableMeta):
831 return super().__subclasscheck__(cls)
832 if self.__args__ is None and self.__result__ is None:
833 return True
834 # We're not doing covariance or contravariance -- this is *invariance*.
835 return self == cls
836
837
838class Callable(Final, metaclass=CallableMeta, _root=True):
839 """Callable type; Callable[[int], str] is a function of (int) -> str.
840
841 The subscription syntax must always be used with exactly two
842 values: the argument list and the return type. The argument list
843 must be a list of types; the return type must be a single type.
844
845 There is no syntax to indicate optional or keyword arguments,
846 such function types are rarely used as callback types.
847 """
848
Guido van Rossumd70fe632015-08-05 12:11:06 +0200849 __slots__ = ()
850
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700851
852def _gorg(a):
853 """Return the farthest origin of a generic class."""
854 assert isinstance(a, GenericMeta)
855 while a.__origin__ is not None:
856 a = a.__origin__
857 return a
858
859
860def _geqv(a, b):
861 """Return whether two generic classes are equivalent.
862
863 The intention is to consider generic class X and any of its
864 parameterized forms (X[T], X[int], etc.) as equivalent.
865
866 However, X is not equivalent to a subclass of X.
867
868 The relation is reflexive, symmetric and transitive.
869 """
870 assert isinstance(a, GenericMeta) and isinstance(b, GenericMeta)
871 # Reduce each to its origin.
872 return _gorg(a) is _gorg(b)
873
874
875class GenericMeta(TypingMeta, abc.ABCMeta):
876 """Metaclass for generic types."""
877
878 # TODO: Constrain more how Generic is used; only a few
879 # standard patterns should be allowed.
880
881 # TODO: Use a more precise rule than matching __name__ to decide
882 # whether two classes are the same. Also, save the formal
883 # parameters. (These things are related! A solution lies in
884 # using origin.)
885
886 __extra__ = None
887
888 def __new__(cls, name, bases, namespace,
889 parameters=None, origin=None, extra=None):
890 if parameters is None:
891 # Extract parameters from direct base classes. Only
892 # direct bases are considered and only those that are
893 # themselves generic, and parameterized with type
894 # variables. Don't use bases like Any, Union, Tuple,
895 # Callable or type variables.
896 params = None
897 for base in bases:
898 if isinstance(base, TypingMeta):
899 if not isinstance(base, GenericMeta):
900 raise TypeError(
901 "You cannot inherit from magic class %s" %
902 repr(base))
903 if base.__parameters__ is None:
904 continue # The base is unparameterized.
905 for bp in base.__parameters__:
906 if _has_type_var(bp) and not isinstance(bp, TypeVar):
907 raise TypeError(
908 "Cannot inherit from a generic class "
909 "parameterized with "
910 "non-type-variable %s" % bp)
911 if params is None:
912 params = []
913 if bp not in params:
914 params.append(bp)
915 if params is not None:
916 parameters = tuple(params)
917 self = super().__new__(cls, name, bases, namespace, _root=True)
918 self.__parameters__ = parameters
919 if extra is not None:
920 self.__extra__ = extra
921 # Else __extra__ is inherited, eventually from the
922 # (meta-)class default above.
923 self.__origin__ = origin
924 return self
925
926 def _has_type_var(self):
927 if self.__parameters__:
928 for t in self.__parameters__:
929 if _has_type_var(t):
930 return True
931 return False
932
933 def __repr__(self):
934 r = super().__repr__()
935 if self.__parameters__ is not None:
936 r += '[%s]' % (
937 ', '.join(_type_repr(p) for p in self.__parameters__))
938 return r
939
940 def __eq__(self, other):
941 if not isinstance(other, GenericMeta):
942 return NotImplemented
943 return (_geqv(self, other) and
944 self.__parameters__ == other.__parameters__)
945
946 def __hash__(self):
947 return hash((self.__name__, self.__parameters__))
948
949 def __getitem__(self, params):
950 if not isinstance(params, tuple):
951 params = (params,)
952 if not params:
953 raise TypeError("Cannot have empty parameter list")
954 msg = "Parameters to generic types must be types."
955 params = tuple(_type_check(p, msg) for p in params)
956 if self.__parameters__ is None:
957 for p in params:
958 if not isinstance(p, TypeVar):
959 raise TypeError("Initial parameters must be "
960 "type variables; got %s" % p)
Guido van Rossumd70fe632015-08-05 12:11:06 +0200961 if len(set(params)) != len(params):
Guido van Rossum1b669102015-09-04 12:15:54 -0700962 raise TypeError(
963 "All type variables in Generic[...] must be distinct.")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700964 else:
965 if len(params) != len(self.__parameters__):
966 raise TypeError("Cannot change parameter count from %d to %d" %
967 (len(self.__parameters__), len(params)))
968 for new, old in zip(params, self.__parameters__):
969 if isinstance(old, TypeVar):
970 if not old.__constraints__:
971 # Substituting for an unconstrained TypeVar is OK.
972 continue
973 if issubclass(new, Union[old.__constraints__]):
974 # Specializing a constrained type variable is OK.
975 continue
976 if not issubclass(new, old):
977 raise TypeError(
978 "Cannot substitute %s for %s in %s" %
979 (_type_repr(new), _type_repr(old), self))
980
981 return self.__class__(self.__name__, self.__bases__,
982 dict(self.__dict__),
983 parameters=params,
984 origin=self,
985 extra=self.__extra__)
986
Guido van Rossum1b669102015-09-04 12:15:54 -0700987 def __instancecheck__(self, instance):
988 # Since we extend ABC.__subclasscheck__ and
989 # ABC.__instancecheck__ inlines the cache checking done by the
990 # latter, we must extend __instancecheck__ too. For simplicity
991 # we just skip the cache check -- instance checks for generic
992 # classes are supposed to be rare anyways.
993 return self.__subclasscheck__(instance.__class__)
994
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700995 def __subclasscheck__(self, cls):
996 if cls is Any:
997 return True
998 if isinstance(cls, GenericMeta):
999 # For a class C(Generic[T]) where T is co-variant,
1000 # C[X] is a subclass of C[Y] iff X is a subclass of Y.
1001 origin = self.__origin__
1002 if origin is not None and origin is cls.__origin__:
1003 assert len(self.__parameters__) == len(origin.__parameters__)
1004 assert len(cls.__parameters__) == len(origin.__parameters__)
1005 for p_self, p_cls, p_origin in zip(self.__parameters__,
1006 cls.__parameters__,
1007 origin.__parameters__):
1008 if isinstance(p_origin, TypeVar):
1009 if p_origin.__covariant__:
1010 # Covariant -- p_cls must be a subclass of p_self.
1011 if not issubclass(p_cls, p_self):
1012 break
1013 elif p_origin.__contravariant__:
1014 # Contravariant. I think it's the opposite. :-)
1015 if not issubclass(p_self, p_cls):
1016 break
1017 else:
1018 # Invariant -- p_cls and p_self must equal.
1019 if p_self != p_cls:
1020 break
1021 else:
1022 # If the origin's parameter is not a typevar,
1023 # insist on invariance.
1024 if p_self != p_cls:
1025 break
1026 else:
1027 return True
1028 # If we break out of the loop, the superclass gets a chance.
1029 if super().__subclasscheck__(cls):
1030 return True
1031 if self.__extra__ is None or isinstance(cls, GenericMeta):
1032 return False
1033 return issubclass(cls, self.__extra__)
1034
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001035
1036class Generic(metaclass=GenericMeta):
1037 """Abstract base class for generic types.
1038
1039 A generic type is typically declared by inheriting from an
1040 instantiation of this class with one or more type variables.
1041 For example, a generic mapping type might be defined as::
1042
1043 class Mapping(Generic[KT, VT]):
1044 def __getitem__(self, key: KT) -> VT:
1045 ...
1046 # Etc.
1047
1048 This class can then be used as follows::
1049
1050 def lookup_name(mapping: Mapping, key: KT, default: VT) -> VT:
1051 try:
1052 return mapping[key]
1053 except KeyError:
1054 return default
1055
1056 For clarity the type variables may be redefined, e.g.::
1057
1058 X = TypeVar('X')
1059 Y = TypeVar('Y')
1060 def lookup_name(mapping: Mapping[X, Y], key: X, default: Y) -> Y:
1061 # Same body as above.
1062 """
1063
Guido van Rossumd70fe632015-08-05 12:11:06 +02001064 __slots__ = ()
1065
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001066 def __new__(cls, *args, **kwds):
1067 next_in_mro = object
1068 # Look for the last occurrence of Generic or Generic[...].
1069 for i, c in enumerate(cls.__mro__[:-1]):
1070 if isinstance(c, GenericMeta) and _gorg(c) is Generic:
1071 next_in_mro = cls.__mro__[i+1]
1072 return next_in_mro.__new__(_gorg(cls))
1073
1074
1075def cast(typ, val):
1076 """Cast a value to a type.
1077
1078 This returns the value unchanged. To the type checker this
1079 signals that the return value has the designated type, but at
1080 runtime we intentionally don't check anything (we want this
1081 to be as fast as possible).
1082 """
1083 return val
1084
1085
1086def _get_defaults(func):
1087 """Internal helper to extract the default arguments, by name."""
1088 code = func.__code__
1089 pos_count = code.co_argcount
1090 kw_count = code.co_kwonlyargcount
1091 arg_names = code.co_varnames
1092 kwarg_names = arg_names[pos_count:pos_count + kw_count]
1093 arg_names = arg_names[:pos_count]
1094 defaults = func.__defaults__ or ()
1095 kwdefaults = func.__kwdefaults__
1096 res = dict(kwdefaults) if kwdefaults else {}
1097 pos_offset = pos_count - len(defaults)
1098 for name, value in zip(arg_names[pos_offset:], defaults):
1099 assert name not in res
1100 res[name] = value
1101 return res
1102
1103
1104def get_type_hints(obj, globalns=None, localns=None):
1105 """Return type hints for a function or method object.
1106
1107 This is often the same as obj.__annotations__, but it handles
1108 forward references encoded as string literals, and if necessary
1109 adds Optional[t] if a default value equal to None is set.
1110
1111 BEWARE -- the behavior of globalns and localns is counterintuitive
1112 (unless you are familiar with how eval() and exec() work). The
1113 search order is locals first, then globals.
1114
1115 - If no dict arguments are passed, an attempt is made to use the
1116 globals from obj, and these are also used as the locals. If the
1117 object does not appear to have globals, an exception is raised.
1118
1119 - If one dict argument is passed, it is used for both globals and
1120 locals.
1121
1122 - If two dict arguments are passed, they specify globals and
1123 locals, respectively.
1124 """
1125 if getattr(obj, '__no_type_check__', None):
1126 return {}
1127 if globalns is None:
1128 globalns = getattr(obj, '__globals__', {})
1129 if localns is None:
1130 localns = globalns
1131 elif localns is None:
1132 localns = globalns
1133 defaults = _get_defaults(obj)
1134 hints = dict(obj.__annotations__)
1135 for name, value in hints.items():
1136 if isinstance(value, str):
1137 value = _ForwardRef(value)
1138 value = _eval_type(value, globalns, localns)
1139 if name in defaults and defaults[name] is None:
1140 value = Optional[value]
1141 hints[name] = value
1142 return hints
1143
1144
1145# TODO: Also support this as a class decorator.
1146def no_type_check(arg):
1147 """Decorator to indicate that annotations are not type hints.
1148
1149 The argument must be a class or function; if it is a class, it
1150 applies recursively to all methods defined in that class (but not
1151 to methods defined in its superclasses or subclasses).
1152
1153 This mutates the function(s) in place.
1154 """
1155 if isinstance(arg, type):
1156 for obj in arg.__dict__.values():
1157 if isinstance(obj, types.FunctionType):
1158 obj.__no_type_check__ = True
1159 else:
1160 arg.__no_type_check__ = True
1161 return arg
1162
1163
1164def no_type_check_decorator(decorator):
1165 """Decorator to give another decorator the @no_type_check effect.
1166
1167 This wraps the decorator with something that wraps the decorated
1168 function in @no_type_check.
1169 """
1170
1171 @functools.wraps(decorator)
1172 def wrapped_decorator(*args, **kwds):
1173 func = decorator(*args, **kwds)
1174 func = no_type_check(func)
1175 return func
1176
1177 return wrapped_decorator
1178
1179
1180def overload(func):
1181 raise RuntimeError("Overloading is only supported in library stubs")
1182
1183
1184class _ProtocolMeta(GenericMeta):
1185 """Internal metaclass for _Protocol.
1186
1187 This exists so _Protocol classes can be generic without deriving
1188 from Generic.
1189 """
1190
Guido van Rossumd70fe632015-08-05 12:11:06 +02001191 def __instancecheck__(self, obj):
1192 raise TypeError("Protocols cannot be used with isinstance().")
1193
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001194 def __subclasscheck__(self, cls):
1195 if not self._is_protocol:
1196 # No structural checks since this isn't a protocol.
1197 return NotImplemented
1198
1199 if self is _Protocol:
1200 # Every class is a subclass of the empty protocol.
1201 return True
1202
1203 # Find all attributes defined in the protocol.
1204 attrs = self._get_protocol_attrs()
1205
1206 for attr in attrs:
1207 if not any(attr in d.__dict__ for d in cls.__mro__):
1208 return False
1209 return True
1210
1211 def _get_protocol_attrs(self):
1212 # Get all Protocol base classes.
1213 protocol_bases = []
1214 for c in self.__mro__:
1215 if getattr(c, '_is_protocol', False) and c.__name__ != '_Protocol':
1216 protocol_bases.append(c)
1217
1218 # Get attributes included in protocol.
1219 attrs = set()
1220 for base in protocol_bases:
1221 for attr in base.__dict__.keys():
1222 # Include attributes not defined in any non-protocol bases.
1223 for c in self.__mro__:
1224 if (c is not base and attr in c.__dict__ and
1225 not getattr(c, '_is_protocol', False)):
1226 break
1227 else:
1228 if (not attr.startswith('_abc_') and
1229 attr != '__abstractmethods__' and
1230 attr != '_is_protocol' and
1231 attr != '__dict__' and
Guido van Rossumd70fe632015-08-05 12:11:06 +02001232 attr != '__slots__' and
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001233 attr != '_get_protocol_attrs' and
1234 attr != '__parameters__' and
1235 attr != '__origin__' and
1236 attr != '__module__'):
1237 attrs.add(attr)
1238
1239 return attrs
1240
1241
1242class _Protocol(metaclass=_ProtocolMeta):
1243 """Internal base class for protocol classes.
1244
1245 This implements a simple-minded structural isinstance check
1246 (similar but more general than the one-offs in collections.abc
1247 such as Hashable).
1248 """
1249
Guido van Rossumd70fe632015-08-05 12:11:06 +02001250 __slots__ = ()
1251
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001252 _is_protocol = True
1253
1254
1255# Various ABCs mimicking those in collections.abc.
1256# A few are simply re-exported for completeness.
1257
1258Hashable = collections_abc.Hashable # Not generic.
1259
1260
1261class Iterable(Generic[T_co], extra=collections_abc.Iterable):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001262 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001263
1264
1265class Iterator(Iterable[T_co], extra=collections_abc.Iterator):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001266 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001267
1268
1269class SupportsInt(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001270 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001271
1272 @abstractmethod
1273 def __int__(self) -> int:
1274 pass
1275
1276
1277class SupportsFloat(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001278 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001279
1280 @abstractmethod
1281 def __float__(self) -> float:
1282 pass
1283
1284
1285class SupportsComplex(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001286 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001287
1288 @abstractmethod
1289 def __complex__(self) -> complex:
1290 pass
1291
1292
1293class SupportsBytes(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001294 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001295
1296 @abstractmethod
1297 def __bytes__(self) -> bytes:
1298 pass
1299
1300
Guido van Rossumd70fe632015-08-05 12:11:06 +02001301class SupportsAbs(_Protocol[T_co]):
1302 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001303
1304 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001305 def __abs__(self) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001306 pass
1307
1308
Guido van Rossumd70fe632015-08-05 12:11:06 +02001309class SupportsRound(_Protocol[T_co]):
1310 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001311
1312 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001313 def __round__(self, ndigits: int = 0) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001314 pass
1315
1316
Guido van Rossumd70fe632015-08-05 12:11:06 +02001317class Reversible(_Protocol[T_co]):
1318 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001319
1320 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001321 def __reversed__(self) -> 'Iterator[T_co]':
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001322 pass
1323
1324
1325Sized = collections_abc.Sized # Not generic.
1326
1327
1328class Container(Generic[T_co], extra=collections_abc.Container):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001329 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001330
1331
1332# Callable was defined earlier.
1333
1334
1335class AbstractSet(Sized, Iterable[T_co], Container[T_co],
1336 extra=collections_abc.Set):
1337 pass
1338
1339
1340class MutableSet(AbstractSet[T], extra=collections_abc.MutableSet):
1341 pass
1342
1343
Guido van Rossumd70fe632015-08-05 12:11:06 +02001344# NOTE: Only the value type is covariant.
1345class Mapping(Sized, Iterable[KT], Container[KT], Generic[VT_co],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001346 extra=collections_abc.Mapping):
1347 pass
1348
1349
1350class MutableMapping(Mapping[KT, VT], extra=collections_abc.MutableMapping):
1351 pass
1352
1353
1354class Sequence(Sized, Iterable[T_co], Container[T_co],
1355 extra=collections_abc.Sequence):
1356 pass
1357
1358
1359class MutableSequence(Sequence[T], extra=collections_abc.MutableSequence):
1360 pass
1361
1362
1363class ByteString(Sequence[int], extra=collections_abc.ByteString):
1364 pass
1365
1366
1367ByteString.register(type(memoryview(b'')))
1368
1369
Guido van Rossumd70fe632015-08-05 12:11:06 +02001370class List(list, MutableSequence[T]):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001371
1372 def __new__(cls, *args, **kwds):
1373 if _geqv(cls, List):
1374 raise TypeError("Type List cannot be instantiated; "
1375 "use list() instead")
1376 return list.__new__(cls, *args, **kwds)
1377
1378
Guido van Rossumd70fe632015-08-05 12:11:06 +02001379class Set(set, MutableSet[T]):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001380
1381 def __new__(cls, *args, **kwds):
1382 if _geqv(cls, Set):
1383 raise TypeError("Type Set cannot be instantiated; "
1384 "use set() instead")
1385 return set.__new__(cls, *args, **kwds)
1386
1387
Guido van Rossumd70fe632015-08-05 12:11:06 +02001388class _FrozenSetMeta(GenericMeta):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001389 """This metaclass ensures set is not a subclass of FrozenSet.
1390
1391 Without this metaclass, set would be considered a subclass of
1392 FrozenSet, because FrozenSet.__extra__ is collections.abc.Set, and
1393 set is a subclass of that.
1394 """
1395
1396 def __subclasscheck__(self, cls):
1397 if issubclass(cls, Set):
1398 return False
1399 return super().__subclasscheck__(cls)
1400
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001401
1402class FrozenSet(frozenset, AbstractSet[T_co], metaclass=_FrozenSetMeta):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001403 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001404
1405 def __new__(cls, *args, **kwds):
1406 if _geqv(cls, FrozenSet):
1407 raise TypeError("Type FrozenSet cannot be instantiated; "
1408 "use frozenset() instead")
1409 return frozenset.__new__(cls, *args, **kwds)
1410
1411
1412class MappingView(Sized, Iterable[T_co], extra=collections_abc.MappingView):
1413 pass
1414
1415
Guido van Rossumd70fe632015-08-05 12:11:06 +02001416class KeysView(MappingView[KT], AbstractSet[KT],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001417 extra=collections_abc.KeysView):
1418 pass
1419
1420
Guido van Rossumd70fe632015-08-05 12:11:06 +02001421# TODO: Enable Set[Tuple[KT, VT_co]] instead of Generic[KT, VT_co].
1422class ItemsView(MappingView, Generic[KT, VT_co],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001423 extra=collections_abc.ItemsView):
1424 pass
1425
1426
1427class ValuesView(MappingView[VT_co], extra=collections_abc.ValuesView):
1428 pass
1429
1430
Guido van Rossumd70fe632015-08-05 12:11:06 +02001431class Dict(dict, MutableMapping[KT, VT]):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001432
1433 def __new__(cls, *args, **kwds):
1434 if _geqv(cls, Dict):
1435 raise TypeError("Type Dict cannot be instantiated; "
1436 "use dict() instead")
1437 return dict.__new__(cls, *args, **kwds)
1438
1439
1440# Determine what base class to use for Generator.
1441if hasattr(collections_abc, 'Generator'):
1442 # Sufficiently recent versions of 3.5 have a Generator ABC.
1443 _G_base = collections_abc.Generator
1444else:
1445 # Fall back on the exact type.
1446 _G_base = types.GeneratorType
1447
1448
1449class Generator(Iterator[T_co], Generic[T_co, T_contra, V_co],
1450 extra=_G_base):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001451 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001452
1453 def __new__(cls, *args, **kwds):
1454 if _geqv(cls, Generator):
1455 raise TypeError("Type Generator cannot be instantiated; "
1456 "create a subclass instead")
1457 return super().__new__(cls, *args, **kwds)
1458
1459
1460def NamedTuple(typename, fields):
1461 """Typed version of namedtuple.
1462
1463 Usage::
1464
1465 Employee = typing.NamedTuple('Employee', [('name', str), 'id', int)])
1466
1467 This is equivalent to::
1468
1469 Employee = collections.namedtuple('Employee', ['name', 'id'])
1470
1471 The resulting class has one extra attribute: _field_types,
1472 giving a dict mapping field names to types. (The field names
1473 are in the _fields attribute, which is part of the namedtuple
1474 API.)
1475 """
1476 fields = [(n, t) for n, t in fields]
1477 cls = collections.namedtuple(typename, [n for n, t in fields])
1478 cls._field_types = dict(fields)
1479 return cls
1480
1481
1482class IO(Generic[AnyStr]):
1483 """Generic base class for TextIO and BinaryIO.
1484
1485 This is an abstract, generic version of the return of open().
1486
1487 NOTE: This does not distinguish between the different possible
1488 classes (text vs. binary, read vs. write vs. read/write,
1489 append-only, unbuffered). The TextIO and BinaryIO subclasses
1490 below capture the distinctions between text vs. binary, which is
1491 pervasive in the interface; however we currently do not offer a
1492 way to track the other distinctions in the type system.
1493 """
1494
Guido van Rossumd70fe632015-08-05 12:11:06 +02001495 __slots__ = ()
1496
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001497 @abstractproperty
1498 def mode(self) -> str:
1499 pass
1500
1501 @abstractproperty
1502 def name(self) -> str:
1503 pass
1504
1505 @abstractmethod
1506 def close(self) -> None:
1507 pass
1508
1509 @abstractmethod
1510 def closed(self) -> bool:
1511 pass
1512
1513 @abstractmethod
1514 def fileno(self) -> int:
1515 pass
1516
1517 @abstractmethod
1518 def flush(self) -> None:
1519 pass
1520
1521 @abstractmethod
1522 def isatty(self) -> bool:
1523 pass
1524
1525 @abstractmethod
1526 def read(self, n: int = -1) -> AnyStr:
1527 pass
1528
1529 @abstractmethod
1530 def readable(self) -> bool:
1531 pass
1532
1533 @abstractmethod
1534 def readline(self, limit: int = -1) -> AnyStr:
1535 pass
1536
1537 @abstractmethod
1538 def readlines(self, hint: int = -1) -> List[AnyStr]:
1539 pass
1540
1541 @abstractmethod
1542 def seek(self, offset: int, whence: int = 0) -> int:
1543 pass
1544
1545 @abstractmethod
1546 def seekable(self) -> bool:
1547 pass
1548
1549 @abstractmethod
1550 def tell(self) -> int:
1551 pass
1552
1553 @abstractmethod
1554 def truncate(self, size: int = None) -> int:
1555 pass
1556
1557 @abstractmethod
1558 def writable(self) -> bool:
1559 pass
1560
1561 @abstractmethod
1562 def write(self, s: AnyStr) -> int:
1563 pass
1564
1565 @abstractmethod
1566 def writelines(self, lines: List[AnyStr]) -> None:
1567 pass
1568
1569 @abstractmethod
1570 def __enter__(self) -> 'IO[AnyStr]':
1571 pass
1572
1573 @abstractmethod
1574 def __exit__(self, type, value, traceback) -> None:
1575 pass
1576
1577
1578class BinaryIO(IO[bytes]):
1579 """Typed version of the return of open() in binary mode."""
1580
Guido van Rossumd70fe632015-08-05 12:11:06 +02001581 __slots__ = ()
1582
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001583 @abstractmethod
1584 def write(self, s: Union[bytes, bytearray]) -> int:
1585 pass
1586
1587 @abstractmethod
1588 def __enter__(self) -> 'BinaryIO':
1589 pass
1590
1591
1592class TextIO(IO[str]):
1593 """Typed version of the return of open() in text mode."""
1594
Guido van Rossumd70fe632015-08-05 12:11:06 +02001595 __slots__ = ()
1596
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001597 @abstractproperty
1598 def buffer(self) -> BinaryIO:
1599 pass
1600
1601 @abstractproperty
1602 def encoding(self) -> str:
1603 pass
1604
1605 @abstractproperty
1606 def errors(self) -> str:
1607 pass
1608
1609 @abstractproperty
1610 def line_buffering(self) -> bool:
1611 pass
1612
1613 @abstractproperty
1614 def newlines(self) -> Any:
1615 pass
1616
1617 @abstractmethod
1618 def __enter__(self) -> 'TextIO':
1619 pass
1620
1621
1622class io:
1623 """Wrapper namespace for IO generic classes."""
1624
1625 __all__ = ['IO', 'TextIO', 'BinaryIO']
1626 IO = IO
1627 TextIO = TextIO
1628 BinaryIO = BinaryIO
1629
1630io.__name__ = __name__ + '.io'
1631sys.modules[io.__name__] = io
1632
1633
1634Pattern = _TypeAlias('Pattern', AnyStr, type(stdlib_re.compile('')),
1635 lambda p: p.pattern)
1636Match = _TypeAlias('Match', AnyStr, type(stdlib_re.match('', '')),
1637 lambda m: m.re.pattern)
1638
1639
1640class re:
1641 """Wrapper namespace for re type aliases."""
1642
1643 __all__ = ['Pattern', 'Match']
1644 Pattern = Pattern
1645 Match = Match
1646
1647re.__name__ = __name__ + '.re'
1648sys.modules[re.__name__] = re