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