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