blob: 4cac66cd13e802801aa399a9586e9aebcb57924f [file] [log] [blame]
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001import abc
2from abc import abstractmethod, abstractproperty
3import collections
Brett Cannonf3ad0422016-04-15 10:51:30 -07004import contextlib
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07005import functools
6import re as stdlib_re # Avoid confusion with the re we export.
7import sys
8import types
9try:
10 import collections.abc as collections_abc
11except ImportError:
12 import collections as collections_abc # Fallback for PY3.2.
13
14
15# Please keep __all__ alphabetized within each category.
16__all__ = [
17 # Super-special typing primitives.
18 'Any',
19 'Callable',
20 'Generic',
21 'Optional',
Guido van Rossumeb9aca32016-05-24 16:38:22 -070022 'Tuple',
23 'Type',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070024 'TypeVar',
25 'Union',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070026
27 # ABCs (from collections.abc).
28 'AbstractSet', # collections.abc.Set.
Guido van Rossumf17c2002015-12-03 17:31:24 -080029 'Awaitable',
30 'AsyncIterator',
31 'AsyncIterable',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070032 'ByteString',
33 'Container',
34 'Hashable',
35 'ItemsView',
36 'Iterable',
37 'Iterator',
38 'KeysView',
39 'Mapping',
40 'MappingView',
41 'MutableMapping',
42 'MutableSequence',
43 'MutableSet',
44 'Sequence',
45 'Sized',
46 'ValuesView',
47
48 # Structural checks, a.k.a. protocols.
49 'Reversible',
50 'SupportsAbs',
51 'SupportsFloat',
52 'SupportsInt',
53 'SupportsRound',
54
55 # Concrete collection types.
56 'Dict',
Guido van Rossumbd5b9a02016-04-05 08:28:52 -070057 'DefaultDict',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070058 'List',
59 'Set',
60 'NamedTuple', # Not really a type.
61 'Generator',
62
63 # One-off things.
64 'AnyStr',
65 'cast',
66 'get_type_hints',
Guido van Rossum91185fe2016-06-08 11:19:11 -070067 'NewType',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070068 'no_type_check',
69 'no_type_check_decorator',
70 'overload',
Guido van Rossum0e0563c2016-04-05 14:54:25 -070071 'Text',
Guido van Rossum91185fe2016-06-08 11:19:11 -070072 'TYPE_CHECKING',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070073]
74
Guido van Rossumbd5b9a02016-04-05 08:28:52 -070075# The pseudo-submodules 're' and 'io' are part of the public
76# namespace, but excluded from __all__ because they might stomp on
77# legitimate imports of those modules.
78
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070079
80def _qualname(x):
81 if sys.version_info[:2] >= (3, 3):
82 return x.__qualname__
83 else:
84 # Fall back to just name.
85 return x.__name__
86
87
88class TypingMeta(type):
89 """Metaclass for every type defined below.
90
91 This overrides __new__() to require an extra keyword parameter
92 '_root', which serves as a guard against naive subclassing of the
93 typing classes. Any legitimate class defined using a metaclass
94 derived from TypingMeta (including internal subclasses created by
95 e.g. Union[X, Y]) must pass _root=True.
96
97 This also defines a dummy constructor (all the work is done in
98 __new__) and a nicer repr().
99 """
100
101 _is_protocol = False
102
103 def __new__(cls, name, bases, namespace, *, _root=False):
104 if not _root:
105 raise TypeError("Cannot subclass %s" %
106 (', '.join(map(_type_repr, bases)) or '()'))
107 return super().__new__(cls, name, bases, namespace)
108
109 def __init__(self, *args, **kwds):
110 pass
111
112 def _eval_type(self, globalns, localns):
113 """Override this in subclasses to interpret forward references.
114
115 For example, Union['C'] is internally stored as
116 Union[_ForwardRef('C')], which should evaluate to _Union[C],
117 where C is an object found in globalns or localns (searching
118 localns first, of course).
119 """
120 return self
121
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700122 def _get_type_vars(self, tvars):
123 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700124
125 def __repr__(self):
126 return '%s.%s' % (self.__module__, _qualname(self))
127
128
129class Final:
130 """Mix-in class to prevent instantiation."""
131
Guido van Rossumd70fe632015-08-05 12:11:06 +0200132 __slots__ = ()
133
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700134 def __new__(self, *args, **kwds):
135 raise TypeError("Cannot instantiate %r" % self.__class__)
136
137
138class _ForwardRef(TypingMeta):
139 """Wrapper to hold a forward reference."""
140
141 def __new__(cls, arg):
142 if not isinstance(arg, str):
143 raise TypeError('ForwardRef must be a string -- got %r' % (arg,))
144 try:
145 code = compile(arg, '<string>', 'eval')
146 except SyntaxError:
147 raise SyntaxError('ForwardRef must be an expression -- got %r' %
148 (arg,))
149 self = super().__new__(cls, arg, (), {}, _root=True)
150 self.__forward_arg__ = arg
151 self.__forward_code__ = code
152 self.__forward_evaluated__ = False
153 self.__forward_value__ = None
154 typing_globals = globals()
155 frame = sys._getframe(1)
156 while frame is not None and frame.f_globals is typing_globals:
157 frame = frame.f_back
158 assert frame is not None
159 self.__forward_frame__ = frame
160 return self
161
162 def _eval_type(self, globalns, localns):
163 if not isinstance(localns, dict):
164 raise TypeError('ForwardRef localns must be a dict -- got %r' %
165 (localns,))
166 if not isinstance(globalns, dict):
167 raise TypeError('ForwardRef globalns must be a dict -- got %r' %
168 (globalns,))
169 if not self.__forward_evaluated__:
170 if globalns is None and localns is None:
171 globalns = localns = {}
172 elif globalns is None:
173 globalns = localns
174 elif localns is None:
175 localns = globalns
176 self.__forward_value__ = _type_check(
177 eval(self.__forward_code__, globalns, localns),
178 "Forward references must evaluate to types.")
179 self.__forward_evaluated__ = True
180 return self.__forward_value__
181
Guido van Rossumd70fe632015-08-05 12:11:06 +0200182 def __instancecheck__(self, obj):
183 raise TypeError("Forward references cannot be used with isinstance().")
184
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700185 def __subclasscheck__(self, cls):
186 if not self.__forward_evaluated__:
187 globalns = self.__forward_frame__.f_globals
188 localns = self.__forward_frame__.f_locals
189 try:
190 self._eval_type(globalns, localns)
191 except NameError:
192 return False # Too early.
193 return issubclass(cls, self.__forward_value__)
194
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700195 def __repr__(self):
196 return '_ForwardRef(%r)' % (self.__forward_arg__,)
197
198
199class _TypeAlias:
200 """Internal helper class for defining generic variants of concrete types.
201
202 Note that this is not a type; let's call it a pseudo-type. It can
203 be used in instance and subclass checks, e.g. isinstance(m, Match)
204 or issubclass(type(m), Match). However, it cannot be itself the
205 target of an issubclass() call; e.g. issubclass(Match, C) (for
206 some arbitrary class C) raises TypeError rather than returning
207 False.
208 """
209
Guido van Rossumd70fe632015-08-05 12:11:06 +0200210 __slots__ = ('name', 'type_var', 'impl_type', 'type_checker')
211
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700212 def __new__(cls, *args, **kwds):
213 """Constructor.
214
215 This only exists to give a better error message in case
216 someone tries to subclass a type alias (not a good idea).
217 """
218 if (len(args) == 3 and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700219 isinstance(args[0], str) and
220 isinstance(args[1], tuple)):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700221 # Close enough.
222 raise TypeError("A type alias cannot be subclassed")
223 return object.__new__(cls)
224
225 def __init__(self, name, type_var, impl_type, type_checker):
226 """Initializer.
227
228 Args:
229 name: The name, e.g. 'Pattern'.
230 type_var: The type parameter, e.g. AnyStr, or the
231 specific type, e.g. str.
232 impl_type: The implementation type.
233 type_checker: Function that takes an impl_type instance.
234 and returns a value that should be a type_var instance.
235 """
236 assert isinstance(name, str), repr(name)
237 assert isinstance(type_var, type), repr(type_var)
238 assert isinstance(impl_type, type), repr(impl_type)
239 assert not isinstance(impl_type, TypingMeta), repr(impl_type)
240 self.name = name
241 self.type_var = type_var
242 self.impl_type = impl_type
243 self.type_checker = type_checker
244
245 def __repr__(self):
246 return "%s[%s]" % (self.name, _type_repr(self.type_var))
247
248 def __getitem__(self, parameter):
249 assert isinstance(parameter, type), repr(parameter)
250 if not isinstance(self.type_var, TypeVar):
251 raise TypeError("%s cannot be further parameterized." % self)
252 if self.type_var.__constraints__:
253 if not issubclass(parameter, Union[self.type_var.__constraints__]):
254 raise TypeError("%s is not a valid substitution for %s." %
255 (parameter, self.type_var))
256 return self.__class__(self.name, parameter,
257 self.impl_type, self.type_checker)
258
259 def __instancecheck__(self, obj):
Guido van Rossumd70fe632015-08-05 12:11:06 +0200260 raise TypeError("Type aliases cannot be used with isinstance().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700261
262 def __subclasscheck__(self, cls):
263 if cls is Any:
264 return True
265 if isinstance(cls, _TypeAlias):
266 # Covariance. For now, we compare by name.
267 return (cls.name == self.name and
268 issubclass(cls.type_var, self.type_var))
269 else:
270 # Note that this is too lenient, because the
271 # implementation type doesn't carry information about
272 # whether it is about bytes or str (for example).
273 return issubclass(cls, self.impl_type)
274
275
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700276def _get_type_vars(types, tvars):
277 for t in types:
278 if isinstance(t, TypingMeta):
279 t._get_type_vars(tvars)
280
281
282def _type_vars(types):
283 tvars = []
284 _get_type_vars(types, tvars)
285 return tuple(tvars)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700286
287
288def _eval_type(t, globalns, localns):
289 if isinstance(t, TypingMeta):
290 return t._eval_type(globalns, localns)
291 else:
292 return t
293
294
295def _type_check(arg, msg):
296 """Check that the argument is a type, and return it.
297
298 As a special case, accept None and return type(None) instead.
299 Also, _TypeAlias instances (e.g. Match, Pattern) are acceptable.
300
301 The msg argument is a human-readable error message, e.g.
302
303 "Union[arg, ...]: arg should be a type."
304
305 We append the repr() of the actual value (truncated to 100 chars).
306 """
307 if arg is None:
308 return type(None)
309 if isinstance(arg, str):
310 arg = _ForwardRef(arg)
Guido van Rossum91185fe2016-06-08 11:19:11 -0700311 if not isinstance(arg, (type, _TypeAlias)) and not callable(arg):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700312 raise TypeError(msg + " Got %.100r." % (arg,))
313 return arg
314
315
316def _type_repr(obj):
317 """Return the repr() of an object, special-casing types.
318
319 If obj is a type, we return a shorter version than the default
320 type.__repr__, based on the module and qualified name, which is
321 typically enough to uniquely identify a type. For everything
322 else, we fall back on repr(obj).
323 """
324 if isinstance(obj, type) and not isinstance(obj, TypingMeta):
325 if obj.__module__ == 'builtins':
326 return _qualname(obj)
327 else:
328 return '%s.%s' % (obj.__module__, _qualname(obj))
329 else:
330 return repr(obj)
331
332
333class AnyMeta(TypingMeta):
334 """Metaclass for Any."""
335
336 def __new__(cls, name, bases, namespace, _root=False):
337 self = super().__new__(cls, name, bases, namespace, _root=_root)
338 return self
339
Guido van Rossumd70fe632015-08-05 12:11:06 +0200340 def __instancecheck__(self, obj):
341 raise TypeError("Any cannot be used with isinstance().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700342
343 def __subclasscheck__(self, cls):
344 if not isinstance(cls, type):
345 return super().__subclasscheck__(cls) # To TypeError.
346 return True
347
348
349class Any(Final, metaclass=AnyMeta, _root=True):
350 """Special type indicating an unconstrained type.
351
352 - Any object is an instance of Any.
353 - Any class is a subclass of Any.
354 - As a special case, Any and object are subclasses of each other.
355 """
356
Guido van Rossumd70fe632015-08-05 12:11:06 +0200357 __slots__ = ()
358
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700359
360class TypeVar(TypingMeta, metaclass=TypingMeta, _root=True):
361 """Type variable.
362
363 Usage::
364
365 T = TypeVar('T') # Can be anything
366 A = TypeVar('A', str, bytes) # Must be str or bytes
367
368 Type variables exist primarily for the benefit of static type
369 checkers. They serve as the parameters for generic types as well
370 as for generic function definitions. See class Generic for more
371 information on generic types. Generic functions work as follows:
372
373 def repeat(x: T, n: int) -> Sequence[T]:
374 '''Return a list containing n references to x.'''
375 return [x]*n
376
377 def longest(x: A, y: A) -> A:
378 '''Return the longest of two strings.'''
379 return x if len(x) >= len(y) else y
380
381 The latter example's signature is essentially the overloading
382 of (str, str) -> str and (bytes, bytes) -> bytes. Also note
383 that if the arguments are instances of some subclass of str,
384 the return type is still plain str.
385
386 At runtime, isinstance(x, T) will raise TypeError. However,
387 issubclass(C, T) is true for any class C, and issubclass(str, A)
388 and issubclass(bytes, A) are true, and issubclass(int, A) is
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700389 false. (TODO: Why is this needed? This may change. See #136.)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700390
391 Type variables may be marked covariant or contravariant by passing
392 covariant=True or contravariant=True. See PEP 484 for more
393 details. By default type variables are invariant.
394
395 Type variables can be introspected. e.g.:
396
397 T.__name__ == 'T'
398 T.__constraints__ == ()
399 T.__covariant__ == False
400 T.__contravariant__ = False
401 A.__constraints__ == (str, bytes)
402 """
403
404 def __new__(cls, name, *constraints, bound=None,
405 covariant=False, contravariant=False):
406 self = super().__new__(cls, name, (Final,), {}, _root=True)
407 if covariant and contravariant:
408 raise ValueError("Bivariant type variables are not supported.")
409 self.__covariant__ = bool(covariant)
410 self.__contravariant__ = bool(contravariant)
411 if constraints and bound is not None:
412 raise TypeError("Constraints cannot be combined with bound=...")
413 if constraints and len(constraints) == 1:
414 raise TypeError("A single constraint is not allowed")
415 msg = "TypeVar(name, constraint, ...): constraints must be types."
416 self.__constraints__ = tuple(_type_check(t, msg) for t in constraints)
417 if bound:
418 self.__bound__ = _type_check(bound, "Bound must be a type.")
419 else:
420 self.__bound__ = None
421 return self
422
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700423 def _get_type_vars(self, tvars):
424 if self not in tvars:
425 tvars.append(self)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700426
427 def __repr__(self):
428 if self.__covariant__:
429 prefix = '+'
430 elif self.__contravariant__:
431 prefix = '-'
432 else:
433 prefix = '~'
434 return prefix + self.__name__
435
436 def __instancecheck__(self, instance):
437 raise TypeError("Type variables cannot be used with isinstance().")
438
439 def __subclasscheck__(self, cls):
440 # TODO: Make this raise TypeError too?
441 if cls is self:
442 return True
443 if cls is Any:
444 return True
445 if self.__bound__ is not None:
446 return issubclass(cls, self.__bound__)
447 if self.__constraints__:
448 return any(issubclass(cls, c) for c in self.__constraints__)
449 return True
450
451
452# Some unconstrained type variables. These are used by the container types.
Guido van Rossumeb9aca32016-05-24 16:38:22 -0700453# (These are not for export.)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700454T = TypeVar('T') # Any type.
455KT = TypeVar('KT') # Key type.
456VT = TypeVar('VT') # Value type.
457T_co = TypeVar('T_co', covariant=True) # Any type covariant containers.
458V_co = TypeVar('V_co', covariant=True) # Any type covariant containers.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700459VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
460T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
461
462# A useful type variable with constraints. This represents string types.
Guido van Rossumeb9aca32016-05-24 16:38:22 -0700463# (This one *is* for export!)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700464AnyStr = TypeVar('AnyStr', bytes, str)
465
466
467class UnionMeta(TypingMeta):
468 """Metaclass for Union."""
469
470 def __new__(cls, name, bases, namespace, parameters=None, _root=False):
471 if parameters is None:
472 return super().__new__(cls, name, bases, namespace, _root=_root)
473 if not isinstance(parameters, tuple):
474 raise TypeError("Expected parameters=<tuple>")
475 # Flatten out Union[Union[...], ...] and type-check non-Union args.
476 params = []
477 msg = "Union[arg, ...]: each arg must be a type."
478 for p in parameters:
479 if isinstance(p, UnionMeta):
480 params.extend(p.__union_params__)
481 else:
482 params.append(_type_check(p, msg))
483 # Weed out strict duplicates, preserving the first of each occurrence.
484 all_params = set(params)
485 if len(all_params) < len(params):
486 new_params = []
487 for t in params:
488 if t in all_params:
489 new_params.append(t)
490 all_params.remove(t)
491 params = new_params
492 assert not all_params, all_params
493 # Weed out subclasses.
494 # E.g. Union[int, Employee, Manager] == Union[int, Employee].
495 # If Any or object is present it will be the sole survivor.
496 # If both Any and object are present, Any wins.
497 # Never discard type variables, except against Any.
498 # (In particular, Union[str, AnyStr] != AnyStr.)
499 all_params = set(params)
500 for t1 in params:
501 if t1 is Any:
502 return Any
503 if isinstance(t1, TypeVar):
504 continue
Guido van Rossumca636ea2015-10-19 14:55:47 -0700505 if isinstance(t1, _TypeAlias):
506 # _TypeAlias is not a real class.
507 continue
Guido van Rossum91185fe2016-06-08 11:19:11 -0700508 if not isinstance(t1, type):
509 assert callable(t1) # A callable might sneak through.
510 continue
511 if any(isinstance(t2, type) and issubclass(t1, t2)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700512 for t2 in all_params - {t1} if not isinstance(t2, TypeVar)):
513 all_params.remove(t1)
514 # It's not a union if there's only one type left.
515 if len(all_params) == 1:
516 return all_params.pop()
517 # Create a new class with these params.
518 self = super().__new__(cls, name, bases, {}, _root=True)
519 self.__union_params__ = tuple(t for t in params if t in all_params)
520 self.__union_set_params__ = frozenset(self.__union_params__)
521 return self
522
523 def _eval_type(self, globalns, localns):
524 p = tuple(_eval_type(t, globalns, localns)
525 for t in self.__union_params__)
526 if p == self.__union_params__:
527 return self
528 else:
529 return self.__class__(self.__name__, self.__bases__, {},
530 p, _root=True)
531
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700532 def _get_type_vars(self, tvars):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700533 if self.__union_params__:
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700534 _get_type_vars(self.__union_params__, tvars)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700535
536 def __repr__(self):
537 r = super().__repr__()
538 if self.__union_params__:
539 r += '[%s]' % (', '.join(_type_repr(t)
540 for t in self.__union_params__))
541 return r
542
543 def __getitem__(self, parameters):
544 if self.__union_params__ is not None:
545 raise TypeError(
546 "Cannot subscript an existing Union. Use Union[u, t] instead.")
547 if parameters == ():
548 raise TypeError("Cannot take a Union of no types.")
549 if not isinstance(parameters, tuple):
550 parameters = (parameters,)
551 return self.__class__(self.__name__, self.__bases__,
552 dict(self.__dict__), parameters, _root=True)
553
554 def __eq__(self, other):
555 if not isinstance(other, UnionMeta):
556 return NotImplemented
557 return self.__union_set_params__ == other.__union_set_params__
558
559 def __hash__(self):
560 return hash(self.__union_set_params__)
561
Guido van Rossumd70fe632015-08-05 12:11:06 +0200562 def __instancecheck__(self, obj):
563 raise TypeError("Unions cannot be used with isinstance().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700564
565 def __subclasscheck__(self, cls):
566 if cls is Any:
567 return True
568 if self.__union_params__ is None:
569 return isinstance(cls, UnionMeta)
570 elif isinstance(cls, UnionMeta):
571 if cls.__union_params__ is None:
572 return False
573 return all(issubclass(c, self) for c in (cls.__union_params__))
574 elif isinstance(cls, TypeVar):
575 if cls in self.__union_params__:
576 return True
577 if cls.__constraints__:
578 return issubclass(Union[cls.__constraints__], self)
579 return False
580 else:
581 return any(issubclass(cls, t) for t in self.__union_params__)
582
583
584class Union(Final, metaclass=UnionMeta, _root=True):
585 """Union type; Union[X, Y] means either X or Y.
586
587 To define a union, use e.g. Union[int, str]. Details:
588
589 - The arguments must be types and there must be at least one.
590
591 - None as an argument is a special case and is replaced by
592 type(None).
593
594 - Unions of unions are flattened, e.g.::
595
596 Union[Union[int, str], float] == Union[int, str, float]
597
598 - Unions of a single argument vanish, e.g.::
599
600 Union[int] == int # The constructor actually returns int
601
602 - Redundant arguments are skipped, e.g.::
603
604 Union[int, str, int] == Union[int, str]
605
606 - When comparing unions, the argument order is ignored, e.g.::
607
608 Union[int, str] == Union[str, int]
609
610 - When two arguments have a subclass relationship, the least
611 derived argument is kept, e.g.::
612
613 class Employee: pass
614 class Manager(Employee): pass
615 Union[int, Employee, Manager] == Union[int, Employee]
616 Union[Manager, int, Employee] == Union[int, Employee]
617 Union[Employee, Manager] == Employee
618
619 - Corollary: if Any is present it is the sole survivor, e.g.::
620
621 Union[int, Any] == Any
622
623 - Similar for object::
624
625 Union[int, object] == object
626
627 - To cut a tie: Union[object, Any] == Union[Any, object] == Any.
628
629 - You cannot subclass or instantiate a union.
630
631 - You cannot write Union[X][Y] (what would it mean?).
632
633 - You can use Optional[X] as a shorthand for Union[X, None].
634 """
635
636 # Unsubscripted Union type has params set to None.
637 __union_params__ = None
638 __union_set_params__ = None
639
640
641class OptionalMeta(TypingMeta):
642 """Metaclass for Optional."""
643
644 def __new__(cls, name, bases, namespace, _root=False):
645 return super().__new__(cls, name, bases, namespace, _root=_root)
646
647 def __getitem__(self, arg):
648 arg = _type_check(arg, "Optional[t] requires a single type.")
649 return Union[arg, type(None)]
650
651
652class Optional(Final, metaclass=OptionalMeta, _root=True):
653 """Optional type.
654
655 Optional[X] is equivalent to Union[X, type(None)].
656 """
657
Guido van Rossumd70fe632015-08-05 12:11:06 +0200658 __slots__ = ()
659
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700660
661class TupleMeta(TypingMeta):
662 """Metaclass for Tuple."""
663
664 def __new__(cls, name, bases, namespace, parameters=None,
665 use_ellipsis=False, _root=False):
666 self = super().__new__(cls, name, bases, namespace, _root=_root)
667 self.__tuple_params__ = parameters
668 self.__tuple_use_ellipsis__ = use_ellipsis
669 return self
670
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700671 def _get_type_vars(self, tvars):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700672 if self.__tuple_params__:
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700673 _get_type_vars(self.__tuple_params__, tvars)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700674
675 def _eval_type(self, globalns, localns):
676 tp = self.__tuple_params__
677 if tp is None:
678 return self
679 p = tuple(_eval_type(t, globalns, localns) for t in tp)
680 if p == self.__tuple_params__:
681 return self
682 else:
683 return self.__class__(self.__name__, self.__bases__, {},
684 p, _root=True)
685
686 def __repr__(self):
687 r = super().__repr__()
688 if self.__tuple_params__ is not None:
689 params = [_type_repr(p) for p in self.__tuple_params__]
690 if self.__tuple_use_ellipsis__:
691 params.append('...')
Guido van Rossum91185fe2016-06-08 11:19:11 -0700692 if not params:
693 params.append('()')
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700694 r += '[%s]' % (
695 ', '.join(params))
696 return r
697
698 def __getitem__(self, parameters):
699 if self.__tuple_params__ is not None:
700 raise TypeError("Cannot re-parameterize %r" % (self,))
701 if not isinstance(parameters, tuple):
702 parameters = (parameters,)
703 if len(parameters) == 2 and parameters[1] == Ellipsis:
704 parameters = parameters[:1]
705 use_ellipsis = True
706 msg = "Tuple[t, ...]: t must be a type."
707 else:
708 use_ellipsis = False
709 msg = "Tuple[t0, t1, ...]: each t must be a type."
710 parameters = tuple(_type_check(p, msg) for p in parameters)
711 return self.__class__(self.__name__, self.__bases__,
712 dict(self.__dict__), parameters,
713 use_ellipsis=use_ellipsis, _root=True)
714
715 def __eq__(self, other):
716 if not isinstance(other, TupleMeta):
717 return NotImplemented
Guido van Rossum5abcbb32016-04-18 07:37:41 -0700718 return (self.__tuple_params__ == other.__tuple_params__ and
719 self.__tuple_use_ellipsis__ == other.__tuple_use_ellipsis__)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700720
721 def __hash__(self):
722 return hash(self.__tuple_params__)
723
Guido van Rossumd70fe632015-08-05 12:11:06 +0200724 def __instancecheck__(self, obj):
725 raise TypeError("Tuples cannot be used with isinstance().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700726
727 def __subclasscheck__(self, cls):
728 if cls is Any:
729 return True
730 if not isinstance(cls, type):
731 return super().__subclasscheck__(cls) # To TypeError.
732 if issubclass(cls, tuple):
733 return True # Special case.
734 if not isinstance(cls, TupleMeta):
735 return super().__subclasscheck__(cls) # False.
736 if self.__tuple_params__ is None:
737 return True
738 if cls.__tuple_params__ is None:
739 return False # ???
740 if cls.__tuple_use_ellipsis__ != self.__tuple_use_ellipsis__:
741 return False
742 # Covariance.
743 return (len(self.__tuple_params__) == len(cls.__tuple_params__) and
744 all(issubclass(x, p)
745 for x, p in zip(cls.__tuple_params__,
746 self.__tuple_params__)))
747
748
749class Tuple(Final, metaclass=TupleMeta, _root=True):
750 """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
751
752 Example: Tuple[T1, T2] is a tuple of two elements corresponding
753 to type variables T1 and T2. Tuple[int, float, str] is a tuple
754 of an int, a float and a string.
755
756 To specify a variable-length tuple of homogeneous type, use Sequence[T].
757 """
758
Guido van Rossumd70fe632015-08-05 12:11:06 +0200759 __slots__ = ()
760
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700761
762class CallableMeta(TypingMeta):
763 """Metaclass for Callable."""
764
765 def __new__(cls, name, bases, namespace, _root=False,
766 args=None, result=None):
767 if args is None and result is None:
768 pass # Must be 'class Callable'.
769 else:
770 if args is not Ellipsis:
771 if not isinstance(args, list):
772 raise TypeError("Callable[args, result]: "
773 "args must be a list."
774 " Got %.100r." % (args,))
775 msg = "Callable[[arg, ...], result]: each arg must be a type."
776 args = tuple(_type_check(arg, msg) for arg in args)
777 msg = "Callable[args, result]: result must be a type."
778 result = _type_check(result, msg)
779 self = super().__new__(cls, name, bases, namespace, _root=_root)
780 self.__args__ = args
781 self.__result__ = result
782 return self
783
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700784 def _get_type_vars(self, tvars):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700785 if self.__args__:
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700786 _get_type_vars(self.__args__, tvars)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700787
788 def _eval_type(self, globalns, localns):
789 if self.__args__ is None and self.__result__ is None:
790 return self
Guido van Rossumd70fe632015-08-05 12:11:06 +0200791 if self.__args__ is Ellipsis:
792 args = self.__args__
793 else:
794 args = [_eval_type(t, globalns, localns) for t in self.__args__]
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700795 result = _eval_type(self.__result__, globalns, localns)
796 if args == self.__args__ and result == self.__result__:
797 return self
798 else:
799 return self.__class__(self.__name__, self.__bases__, {},
800 args=args, result=result, _root=True)
801
802 def __repr__(self):
803 r = super().__repr__()
804 if self.__args__ is not None or self.__result__ is not None:
805 if self.__args__ is Ellipsis:
806 args_r = '...'
807 else:
808 args_r = '[%s]' % ', '.join(_type_repr(t)
809 for t in self.__args__)
810 r += '[%s, %s]' % (args_r, _type_repr(self.__result__))
811 return r
812
813 def __getitem__(self, parameters):
814 if self.__args__ is not None or self.__result__ is not None:
815 raise TypeError("This Callable type is already parameterized.")
816 if not isinstance(parameters, tuple) or len(parameters) != 2:
817 raise TypeError(
818 "Callable must be used as Callable[[arg, ...], result].")
819 args, result = parameters
820 return self.__class__(self.__name__, self.__bases__,
821 dict(self.__dict__), _root=True,
822 args=args, result=result)
823
824 def __eq__(self, other):
825 if not isinstance(other, CallableMeta):
826 return NotImplemented
827 return (self.__args__ == other.__args__ and
828 self.__result__ == other.__result__)
829
830 def __hash__(self):
831 return hash(self.__args__) ^ hash(self.__result__)
832
Guido van Rossumd70fe632015-08-05 12:11:06 +0200833 def __instancecheck__(self, obj):
834 # For unparametrized Callable we allow this, because
835 # typing.Callable should be equivalent to
836 # collections.abc.Callable.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700837 if self.__args__ is None and self.__result__ is None:
Guido van Rossumd70fe632015-08-05 12:11:06 +0200838 return isinstance(obj, collections_abc.Callable)
839 else:
840 raise TypeError("Callable[] cannot be used with isinstance().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700841
842 def __subclasscheck__(self, cls):
843 if cls is Any:
844 return True
845 if not isinstance(cls, CallableMeta):
846 return super().__subclasscheck__(cls)
847 if self.__args__ is None and self.__result__ is None:
848 return True
849 # We're not doing covariance or contravariance -- this is *invariance*.
850 return self == cls
851
852
853class Callable(Final, metaclass=CallableMeta, _root=True):
854 """Callable type; Callable[[int], str] is a function of (int) -> str.
855
856 The subscription syntax must always be used with exactly two
857 values: the argument list and the return type. The argument list
858 must be a list of types; the return type must be a single type.
859
860 There is no syntax to indicate optional or keyword arguments,
861 such function types are rarely used as callback types.
862 """
863
Guido van Rossumd70fe632015-08-05 12:11:06 +0200864 __slots__ = ()
865
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700866
867def _gorg(a):
868 """Return the farthest origin of a generic class."""
869 assert isinstance(a, GenericMeta)
870 while a.__origin__ is not None:
871 a = a.__origin__
872 return a
873
874
875def _geqv(a, b):
876 """Return whether two generic classes are equivalent.
877
878 The intention is to consider generic class X and any of its
879 parameterized forms (X[T], X[int], etc.) as equivalent.
880
881 However, X is not equivalent to a subclass of X.
882
883 The relation is reflexive, symmetric and transitive.
884 """
885 assert isinstance(a, GenericMeta) and isinstance(b, GenericMeta)
886 # Reduce each to its origin.
887 return _gorg(a) is _gorg(b)
888
889
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700890def _next_in_mro(cls):
891 """Helper for Generic.__new__.
892
893 Returns the class after the last occurrence of Generic or
894 Generic[...] in cls.__mro__.
895 """
896 next_in_mro = object
897 # Look for the last occurrence of Generic or Generic[...].
898 for i, c in enumerate(cls.__mro__[:-1]):
899 if isinstance(c, GenericMeta) and _gorg(c) is Generic:
900 next_in_mro = cls.__mro__[i+1]
901 return next_in_mro
902
903
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700904class GenericMeta(TypingMeta, abc.ABCMeta):
905 """Metaclass for generic types."""
906
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700907 def __new__(cls, name, bases, namespace,
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700908 tvars=None, args=None, origin=None, extra=None):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700909 self = super().__new__(cls, name, bases, namespace, _root=True)
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700910
911 if tvars is not None:
912 # Called from __getitem__() below.
913 assert origin is not None
914 assert all(isinstance(t, TypeVar) for t in tvars), tvars
915 else:
916 # Called from class statement.
917 assert tvars is None, tvars
918 assert args is None, args
919 assert origin is None, origin
920
921 # Get the full set of tvars from the bases.
922 tvars = _type_vars(bases)
923 # Look for Generic[T1, ..., Tn].
924 # If found, tvars must be a subset of it.
925 # If not found, tvars is it.
926 # Also check for and reject plain Generic,
927 # and reject multiple Generic[...].
928 gvars = None
929 for base in bases:
930 if base is Generic:
931 raise TypeError("Cannot inherit from plain Generic")
932 if (isinstance(base, GenericMeta) and
933 base.__origin__ is Generic):
934 if gvars is not None:
935 raise TypeError(
936 "Cannot inherit from Generic[...] multiple types.")
937 gvars = base.__parameters__
938 if gvars is None:
939 gvars = tvars
940 else:
941 tvarset = set(tvars)
942 gvarset = set(gvars)
943 if not tvarset <= gvarset:
944 raise TypeError(
945 "Some type variables (%s) "
946 "are not listed in Generic[%s]" %
947 (", ".join(str(t) for t in tvars if t not in gvarset),
948 ", ".join(str(g) for g in gvars)))
949 tvars = gvars
950
951 self.__parameters__ = tvars
952 self.__args__ = args
953 self.__origin__ = origin
Guido van Rossum1cea70f2016-05-18 08:35:00 -0700954 self.__extra__ = extra
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700955 # Speed hack (https://github.com/python/typing/issues/196).
956 self.__next_in_mro__ = _next_in_mro(self)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700957 return self
958
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700959 def _get_type_vars(self, tvars):
960 if self.__origin__ and self.__parameters__:
961 _get_type_vars(self.__parameters__, tvars)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700962
963 def __repr__(self):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700964 if self.__origin__ is not None:
965 r = repr(self.__origin__)
966 else:
967 r = super().__repr__()
968 if self.__args__:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700969 r += '[%s]' % (
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700970 ', '.join(_type_repr(p) for p in self.__args__))
971 if self.__parameters__:
972 r += '<%s>' % (
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700973 ', '.join(_type_repr(p) for p in self.__parameters__))
974 return r
975
976 def __eq__(self, other):
977 if not isinstance(other, GenericMeta):
978 return NotImplemented
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700979 if self.__origin__ is not None:
980 return (self.__origin__ is other.__origin__ and
981 self.__args__ == other.__args__ and
982 self.__parameters__ == other.__parameters__)
983 else:
984 return self is other
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700985
986 def __hash__(self):
987 return hash((self.__name__, self.__parameters__))
988
989 def __getitem__(self, params):
990 if not isinstance(params, tuple):
991 params = (params,)
992 if not params:
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700993 raise TypeError(
994 "Parameter list to %s[...] cannot be empty" % _qualname(self))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700995 msg = "Parameters to generic types must be types."
996 params = tuple(_type_check(p, msg) for p in params)
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700997 if self is Generic:
998 # Generic can only be subscripted with unique type variables.
999 if not all(isinstance(p, TypeVar) for p in params):
1000 raise TypeError(
1001 "Parameters to Generic[...] must all be type variables")
Guido van Rossumd70fe632015-08-05 12:11:06 +02001002 if len(set(params)) != len(params):
Guido van Rossum1b669102015-09-04 12:15:54 -07001003 raise TypeError(
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001004 "Parameters to Generic[...] must all be unique")
1005 tvars = params
1006 args = None
1007 elif self is _Protocol:
1008 # _Protocol is internal, don't check anything.
1009 tvars = params
1010 args = None
1011 elif self.__origin__ in (Generic, _Protocol):
1012 # Can't subscript Generic[...] or _Protocol[...].
1013 raise TypeError("Cannot subscript already-subscripted %s" %
1014 repr(self))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001015 else:
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001016 # Subscripting a regular Generic subclass.
1017 if not self.__parameters__:
1018 raise TypeError("%s is not a generic class" % repr(self))
1019 alen = len(params)
1020 elen = len(self.__parameters__)
1021 if alen != elen:
1022 raise TypeError(
1023 "Too %s parameters for %s; actual %s, expected %s" %
1024 ("many" if alen > elen else "few", repr(self), alen, elen))
1025 tvars = _type_vars(params)
1026 args = params
1027 return self.__class__(self.__name__,
1028 (self,) + self.__bases__,
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001029 dict(self.__dict__),
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001030 tvars=tvars,
1031 args=args,
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001032 origin=self,
1033 extra=self.__extra__)
1034
Guido van Rossum1b669102015-09-04 12:15:54 -07001035 def __instancecheck__(self, instance):
1036 # Since we extend ABC.__subclasscheck__ and
1037 # ABC.__instancecheck__ inlines the cache checking done by the
1038 # latter, we must extend __instancecheck__ too. For simplicity
1039 # we just skip the cache check -- instance checks for generic
1040 # classes are supposed to be rare anyways.
1041 return self.__subclasscheck__(instance.__class__)
1042
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001043 def __subclasscheck__(self, cls):
1044 if cls is Any:
1045 return True
1046 if isinstance(cls, GenericMeta):
1047 # For a class C(Generic[T]) where T is co-variant,
1048 # C[X] is a subclass of C[Y] iff X is a subclass of Y.
1049 origin = self.__origin__
1050 if origin is not None and origin is cls.__origin__:
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001051 assert len(self.__args__) == len(origin.__parameters__)
1052 assert len(cls.__args__) == len(origin.__parameters__)
1053 for p_self, p_cls, p_origin in zip(self.__args__,
1054 cls.__args__,
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001055 origin.__parameters__):
1056 if isinstance(p_origin, TypeVar):
1057 if p_origin.__covariant__:
1058 # Covariant -- p_cls must be a subclass of p_self.
1059 if not issubclass(p_cls, p_self):
1060 break
1061 elif p_origin.__contravariant__:
1062 # Contravariant. I think it's the opposite. :-)
1063 if not issubclass(p_self, p_cls):
1064 break
1065 else:
1066 # Invariant -- p_cls and p_self must equal.
1067 if p_self != p_cls:
1068 break
1069 else:
1070 # If the origin's parameter is not a typevar,
1071 # insist on invariance.
1072 if p_self != p_cls:
1073 break
1074 else:
1075 return True
1076 # If we break out of the loop, the superclass gets a chance.
1077 if super().__subclasscheck__(cls):
1078 return True
1079 if self.__extra__ is None or isinstance(cls, GenericMeta):
1080 return False
1081 return issubclass(cls, self.__extra__)
1082
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001083
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001084# Prevent checks for Generic to crash when defining Generic.
1085Generic = None
1086
1087
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001088class Generic(metaclass=GenericMeta):
1089 """Abstract base class for generic types.
1090
1091 A generic type is typically declared by inheriting from an
1092 instantiation of this class with one or more type variables.
1093 For example, a generic mapping type might be defined as::
1094
1095 class Mapping(Generic[KT, VT]):
1096 def __getitem__(self, key: KT) -> VT:
1097 ...
1098 # Etc.
1099
1100 This class can then be used as follows::
1101
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001102 def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001103 try:
1104 return mapping[key]
1105 except KeyError:
1106 return default
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001107 """
1108
Guido van Rossumd70fe632015-08-05 12:11:06 +02001109 __slots__ = ()
1110
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001111 def __new__(cls, *args, **kwds):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001112 if cls.__origin__ is None:
1113 return cls.__next_in_mro__.__new__(cls)
1114 else:
1115 origin = _gorg(cls)
1116 obj = cls.__next_in_mro__.__new__(origin)
1117 obj.__init__(*args, **kwds)
1118 return obj
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001119
1120
1121def cast(typ, val):
1122 """Cast a value to a type.
1123
1124 This returns the value unchanged. To the type checker this
1125 signals that the return value has the designated type, but at
1126 runtime we intentionally don't check anything (we want this
1127 to be as fast as possible).
1128 """
1129 return val
1130
1131
1132def _get_defaults(func):
1133 """Internal helper to extract the default arguments, by name."""
1134 code = func.__code__
1135 pos_count = code.co_argcount
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001136 arg_names = code.co_varnames
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001137 arg_names = arg_names[:pos_count]
1138 defaults = func.__defaults__ or ()
1139 kwdefaults = func.__kwdefaults__
1140 res = dict(kwdefaults) if kwdefaults else {}
1141 pos_offset = pos_count - len(defaults)
1142 for name, value in zip(arg_names[pos_offset:], defaults):
1143 assert name not in res
1144 res[name] = value
1145 return res
1146
1147
1148def get_type_hints(obj, globalns=None, localns=None):
1149 """Return type hints for a function or method object.
1150
1151 This is often the same as obj.__annotations__, but it handles
1152 forward references encoded as string literals, and if necessary
1153 adds Optional[t] if a default value equal to None is set.
1154
1155 BEWARE -- the behavior of globalns and localns is counterintuitive
1156 (unless you are familiar with how eval() and exec() work). The
1157 search order is locals first, then globals.
1158
1159 - If no dict arguments are passed, an attempt is made to use the
1160 globals from obj, and these are also used as the locals. If the
1161 object does not appear to have globals, an exception is raised.
1162
1163 - If one dict argument is passed, it is used for both globals and
1164 locals.
1165
1166 - If two dict arguments are passed, they specify globals and
1167 locals, respectively.
1168 """
1169 if getattr(obj, '__no_type_check__', None):
1170 return {}
1171 if globalns is None:
1172 globalns = getattr(obj, '__globals__', {})
1173 if localns is None:
1174 localns = globalns
1175 elif localns is None:
1176 localns = globalns
1177 defaults = _get_defaults(obj)
1178 hints = dict(obj.__annotations__)
1179 for name, value in hints.items():
1180 if isinstance(value, str):
1181 value = _ForwardRef(value)
1182 value = _eval_type(value, globalns, localns)
1183 if name in defaults and defaults[name] is None:
1184 value = Optional[value]
1185 hints[name] = value
1186 return hints
1187
1188
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001189def no_type_check(arg):
1190 """Decorator to indicate that annotations are not type hints.
1191
1192 The argument must be a class or function; if it is a class, it
1193 applies recursively to all methods defined in that class (but not
1194 to methods defined in its superclasses or subclasses).
1195
1196 This mutates the function(s) in place.
1197 """
1198 if isinstance(arg, type):
1199 for obj in arg.__dict__.values():
1200 if isinstance(obj, types.FunctionType):
1201 obj.__no_type_check__ = True
1202 else:
1203 arg.__no_type_check__ = True
1204 return arg
1205
1206
1207def no_type_check_decorator(decorator):
1208 """Decorator to give another decorator the @no_type_check effect.
1209
1210 This wraps the decorator with something that wraps the decorated
1211 function in @no_type_check.
1212 """
1213
1214 @functools.wraps(decorator)
1215 def wrapped_decorator(*args, **kwds):
1216 func = decorator(*args, **kwds)
1217 func = no_type_check(func)
1218 return func
1219
1220 return wrapped_decorator
1221
1222
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001223def _overload_dummy(*args, **kwds):
1224 """Helper for @overload to raise when called."""
1225 raise NotImplementedError(
1226 "You should not call an overloaded function. "
1227 "A series of @overload-decorated functions "
1228 "outside a stub module should always be followed "
1229 "by an implementation that is not @overload-ed.")
1230
1231
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001232def overload(func):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001233 """Decorator for overloaded functions/methods.
1234
1235 In a stub file, place two or more stub definitions for the same
1236 function in a row, each decorated with @overload. For example:
1237
1238 @overload
1239 def utf8(value: None) -> None: ...
1240 @overload
1241 def utf8(value: bytes) -> bytes: ...
1242 @overload
1243 def utf8(value: str) -> bytes: ...
1244
1245 In a non-stub file (i.e. a regular .py file), do the same but
1246 follow it with an implementation. The implementation should *not*
1247 be decorated with @overload. For example:
1248
1249 @overload
1250 def utf8(value: None) -> None: ...
1251 @overload
1252 def utf8(value: bytes) -> bytes: ...
1253 @overload
1254 def utf8(value: str) -> bytes: ...
1255 def utf8(value):
1256 # implementation goes here
1257 """
1258 return _overload_dummy
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001259
1260
1261class _ProtocolMeta(GenericMeta):
1262 """Internal metaclass for _Protocol.
1263
1264 This exists so _Protocol classes can be generic without deriving
1265 from Generic.
1266 """
1267
Guido van Rossumd70fe632015-08-05 12:11:06 +02001268 def __instancecheck__(self, obj):
1269 raise TypeError("Protocols cannot be used with isinstance().")
1270
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001271 def __subclasscheck__(self, cls):
1272 if not self._is_protocol:
1273 # No structural checks since this isn't a protocol.
1274 return NotImplemented
1275
1276 if self is _Protocol:
1277 # Every class is a subclass of the empty protocol.
1278 return True
1279
1280 # Find all attributes defined in the protocol.
1281 attrs = self._get_protocol_attrs()
1282
1283 for attr in attrs:
1284 if not any(attr in d.__dict__ for d in cls.__mro__):
1285 return False
1286 return True
1287
1288 def _get_protocol_attrs(self):
1289 # Get all Protocol base classes.
1290 protocol_bases = []
1291 for c in self.__mro__:
1292 if getattr(c, '_is_protocol', False) and c.__name__ != '_Protocol':
1293 protocol_bases.append(c)
1294
1295 # Get attributes included in protocol.
1296 attrs = set()
1297 for base in protocol_bases:
1298 for attr in base.__dict__.keys():
1299 # Include attributes not defined in any non-protocol bases.
1300 for c in self.__mro__:
1301 if (c is not base and attr in c.__dict__ and
1302 not getattr(c, '_is_protocol', False)):
1303 break
1304 else:
1305 if (not attr.startswith('_abc_') and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001306 attr != '__abstractmethods__' and
1307 attr != '_is_protocol' and
1308 attr != '__dict__' and
1309 attr != '__args__' and
1310 attr != '__slots__' and
1311 attr != '_get_protocol_attrs' and
1312 attr != '__next_in_mro__' and
1313 attr != '__parameters__' and
1314 attr != '__origin__' and
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001315 attr != '__extra__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001316 attr != '__module__'):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001317 attrs.add(attr)
1318
1319 return attrs
1320
1321
1322class _Protocol(metaclass=_ProtocolMeta):
1323 """Internal base class for protocol classes.
1324
1325 This implements a simple-minded structural isinstance check
1326 (similar but more general than the one-offs in collections.abc
1327 such as Hashable).
1328 """
1329
Guido van Rossumd70fe632015-08-05 12:11:06 +02001330 __slots__ = ()
1331
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001332 _is_protocol = True
1333
1334
1335# Various ABCs mimicking those in collections.abc.
1336# A few are simply re-exported for completeness.
1337
1338Hashable = collections_abc.Hashable # Not generic.
1339
1340
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001341if hasattr(collections_abc, 'Awaitable'):
1342 class Awaitable(Generic[T_co], extra=collections_abc.Awaitable):
1343 __slots__ = ()
1344else:
1345 Awaitable = None
Guido van Rossumf17c2002015-12-03 17:31:24 -08001346
1347
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001348if hasattr(collections_abc, 'AsyncIterable'):
Guido van Rossumf17c2002015-12-03 17:31:24 -08001349
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001350 class AsyncIterable(Generic[T_co], extra=collections_abc.AsyncIterable):
1351 __slots__ = ()
Guido van Rossumf17c2002015-12-03 17:31:24 -08001352
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001353 class AsyncIterator(AsyncIterable[T_co],
1354 extra=collections_abc.AsyncIterator):
1355 __slots__ = ()
1356
1357else:
1358 AsyncIterable = None
1359 AsyncIterator = None
Guido van Rossumf17c2002015-12-03 17:31:24 -08001360
1361
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001362class Iterable(Generic[T_co], extra=collections_abc.Iterable):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001363 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001364
1365
1366class Iterator(Iterable[T_co], extra=collections_abc.Iterator):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001367 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001368
1369
1370class SupportsInt(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001371 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001372
1373 @abstractmethod
1374 def __int__(self) -> int:
1375 pass
1376
1377
1378class SupportsFloat(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001379 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001380
1381 @abstractmethod
1382 def __float__(self) -> float:
1383 pass
1384
1385
1386class SupportsComplex(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001387 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001388
1389 @abstractmethod
1390 def __complex__(self) -> complex:
1391 pass
1392
1393
1394class SupportsBytes(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001395 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001396
1397 @abstractmethod
1398 def __bytes__(self) -> bytes:
1399 pass
1400
1401
Guido van Rossumd70fe632015-08-05 12:11:06 +02001402class SupportsAbs(_Protocol[T_co]):
1403 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001404
1405 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001406 def __abs__(self) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001407 pass
1408
1409
Guido van Rossumd70fe632015-08-05 12:11:06 +02001410class SupportsRound(_Protocol[T_co]):
1411 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001412
1413 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001414 def __round__(self, ndigits: int = 0) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001415 pass
1416
1417
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001418if hasattr(collections_abc, 'Reversible'):
1419 class Reversible(Iterable[T_co], extra=collections_abc.Reversible):
1420 __slots__ = ()
1421else:
1422 class Reversible(_Protocol[T_co]):
1423 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001424
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001425 @abstractmethod
1426 def __reversed__(self) -> 'Iterator[T_co]':
1427 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001428
1429
1430Sized = collections_abc.Sized # Not generic.
1431
1432
1433class Container(Generic[T_co], extra=collections_abc.Container):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001434 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001435
1436
1437# Callable was defined earlier.
1438
1439
1440class AbstractSet(Sized, Iterable[T_co], Container[T_co],
1441 extra=collections_abc.Set):
1442 pass
1443
1444
1445class MutableSet(AbstractSet[T], extra=collections_abc.MutableSet):
1446 pass
1447
1448
Guido van Rossumd70fe632015-08-05 12:11:06 +02001449# NOTE: Only the value type is covariant.
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001450class Mapping(Sized, Iterable[KT], Container[KT], Generic[KT, VT_co],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001451 extra=collections_abc.Mapping):
1452 pass
1453
1454
1455class MutableMapping(Mapping[KT, VT], extra=collections_abc.MutableMapping):
1456 pass
1457
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001458if hasattr(collections_abc, 'Reversible'):
1459 class Sequence(Sized, Reversible[T_co], Container[T_co],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001460 extra=collections_abc.Sequence):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001461 pass
1462else:
1463 class Sequence(Sized, Iterable[T_co], Container[T_co],
1464 extra=collections_abc.Sequence):
1465 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001466
1467
1468class MutableSequence(Sequence[T], extra=collections_abc.MutableSequence):
1469 pass
1470
1471
1472class ByteString(Sequence[int], extra=collections_abc.ByteString):
1473 pass
1474
1475
1476ByteString.register(type(memoryview(b'')))
1477
1478
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001479class List(list, MutableSequence[T], extra=list):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001480
1481 def __new__(cls, *args, **kwds):
1482 if _geqv(cls, List):
1483 raise TypeError("Type List cannot be instantiated; "
1484 "use list() instead")
1485 return list.__new__(cls, *args, **kwds)
1486
1487
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001488class Set(set, MutableSet[T], extra=set):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001489
1490 def __new__(cls, *args, **kwds):
1491 if _geqv(cls, Set):
1492 raise TypeError("Type Set cannot be instantiated; "
1493 "use set() instead")
1494 return set.__new__(cls, *args, **kwds)
1495
1496
Guido van Rossumd70fe632015-08-05 12:11:06 +02001497class _FrozenSetMeta(GenericMeta):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001498 """This metaclass ensures set is not a subclass of FrozenSet.
1499
1500 Without this metaclass, set would be considered a subclass of
1501 FrozenSet, because FrozenSet.__extra__ is collections.abc.Set, and
1502 set is a subclass of that.
1503 """
1504
1505 def __subclasscheck__(self, cls):
1506 if issubclass(cls, Set):
1507 return False
1508 return super().__subclasscheck__(cls)
1509
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001510
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001511class FrozenSet(frozenset, AbstractSet[T_co], metaclass=_FrozenSetMeta,
1512 extra=frozenset):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001513 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001514
1515 def __new__(cls, *args, **kwds):
1516 if _geqv(cls, FrozenSet):
1517 raise TypeError("Type FrozenSet cannot be instantiated; "
1518 "use frozenset() instead")
1519 return frozenset.__new__(cls, *args, **kwds)
1520
1521
1522class MappingView(Sized, Iterable[T_co], extra=collections_abc.MappingView):
1523 pass
1524
1525
Guido van Rossumd70fe632015-08-05 12:11:06 +02001526class KeysView(MappingView[KT], AbstractSet[KT],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001527 extra=collections_abc.KeysView):
1528 pass
1529
1530
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001531class ItemsView(MappingView[Tuple[KT, VT_co]],
Guido van Rossum0e0563c2016-04-05 14:54:25 -07001532 AbstractSet[Tuple[KT, VT_co]],
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001533 Generic[KT, VT_co],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001534 extra=collections_abc.ItemsView):
1535 pass
1536
1537
1538class ValuesView(MappingView[VT_co], extra=collections_abc.ValuesView):
1539 pass
1540
1541
Brett Cannonf3ad0422016-04-15 10:51:30 -07001542if hasattr(contextlib, 'AbstractContextManager'):
1543 class ContextManager(Generic[T_co], extra=contextlib.AbstractContextManager):
1544 __slots__ = ()
1545 __all__.append('ContextManager')
1546
1547
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001548class Dict(dict, MutableMapping[KT, VT], extra=dict):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001549
1550 def __new__(cls, *args, **kwds):
1551 if _geqv(cls, Dict):
1552 raise TypeError("Type Dict cannot be instantiated; "
1553 "use dict() instead")
1554 return dict.__new__(cls, *args, **kwds)
1555
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001556class DefaultDict(collections.defaultdict, MutableMapping[KT, VT],
1557 extra=collections.defaultdict):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001558
1559 def __new__(cls, *args, **kwds):
1560 if _geqv(cls, DefaultDict):
1561 raise TypeError("Type DefaultDict cannot be instantiated; "
1562 "use collections.defaultdict() instead")
1563 return collections.defaultdict.__new__(cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001564
1565# Determine what base class to use for Generator.
1566if hasattr(collections_abc, 'Generator'):
1567 # Sufficiently recent versions of 3.5 have a Generator ABC.
1568 _G_base = collections_abc.Generator
1569else:
1570 # Fall back on the exact type.
1571 _G_base = types.GeneratorType
1572
1573
1574class Generator(Iterator[T_co], Generic[T_co, T_contra, V_co],
1575 extra=_G_base):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001576 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001577
1578 def __new__(cls, *args, **kwds):
1579 if _geqv(cls, Generator):
1580 raise TypeError("Type Generator cannot be instantiated; "
1581 "create a subclass instead")
1582 return super().__new__(cls, *args, **kwds)
1583
1584
Guido van Rossumeb9aca32016-05-24 16:38:22 -07001585# Internal type variable used for Type[].
1586CT = TypeVar('CT', covariant=True, bound=type)
1587
1588
Guido van Rossumb22c7082016-05-26 09:56:19 -07001589# This is not a real generic class. Don't use outside annotations.
Guido van Rossumeb9aca32016-05-24 16:38:22 -07001590class Type(type, Generic[CT], extra=type):
Guido van Rossumb22c7082016-05-26 09:56:19 -07001591 """A special construct usable to annotate class objects.
Guido van Rossumeb9aca32016-05-24 16:38:22 -07001592
1593 For example, suppose we have the following classes::
1594
1595 class User: ... # Abstract base for User classes
1596 class BasicUser(User): ...
1597 class ProUser(User): ...
1598 class TeamUser(User): ...
1599
1600 And a function that takes a class argument that's a subclass of
1601 User and returns an instance of the corresponding class::
1602
1603 U = TypeVar('U', bound=User)
1604 def new_user(user_class: Type[U]) -> U:
1605 user = user_class()
1606 # (Here we could write the user object to a database)
1607 return user
1608
1609 joe = new_user(BasicUser)
1610
1611 At this point the type checker knows that joe has type BasicUser.
1612 """
1613
1614
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001615def NamedTuple(typename, fields):
1616 """Typed version of namedtuple.
1617
1618 Usage::
1619
1620 Employee = typing.NamedTuple('Employee', [('name', str), 'id', int)])
1621
1622 This is equivalent to::
1623
1624 Employee = collections.namedtuple('Employee', ['name', 'id'])
1625
1626 The resulting class has one extra attribute: _field_types,
1627 giving a dict mapping field names to types. (The field names
1628 are in the _fields attribute, which is part of the namedtuple
1629 API.)
1630 """
1631 fields = [(n, t) for n, t in fields]
1632 cls = collections.namedtuple(typename, [n for n, t in fields])
1633 cls._field_types = dict(fields)
Guido van Rossum557d1eb2015-11-19 08:16:31 -08001634 # Set the module to the caller's module (otherwise it'd be 'typing').
1635 try:
1636 cls.__module__ = sys._getframe(1).f_globals.get('__name__', '__main__')
1637 except (AttributeError, ValueError):
1638 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001639 return cls
1640
1641
Guido van Rossum91185fe2016-06-08 11:19:11 -07001642def NewType(name, tp):
1643 """NewType creates simple unique types with almost zero
1644 runtime overhead. NewType(name, tp) is considered a subtype of tp
1645 by static type checkers. At runtime, NewType(name, tp) returns
1646 a dummy function that simply returns its argument. Usage::
1647
1648 UserId = NewType('UserId', int)
1649
1650 def name_by_id(user_id: UserId) -> str:
1651 ...
1652
1653 UserId('user') # Fails type check
1654
1655 name_by_id(42) # Fails type check
1656 name_by_id(UserId(42)) # OK
1657
1658 num = UserId(5) + 1 # type: int
1659 """
1660
1661 def new_type(x):
1662 return x
1663
1664 new_type.__name__ = name
1665 new_type.__supertype__ = tp
1666 return new_type
1667
1668
Guido van Rossum0e0563c2016-04-05 14:54:25 -07001669# Python-version-specific alias (Python 2: unicode; Python 3: str)
1670Text = str
1671
1672
Guido van Rossum91185fe2016-06-08 11:19:11 -07001673# Constant that's True when type checking, but False here.
1674TYPE_CHECKING = False
1675
1676
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001677class IO(Generic[AnyStr]):
1678 """Generic base class for TextIO and BinaryIO.
1679
1680 This is an abstract, generic version of the return of open().
1681
1682 NOTE: This does not distinguish between the different possible
1683 classes (text vs. binary, read vs. write vs. read/write,
1684 append-only, unbuffered). The TextIO and BinaryIO subclasses
1685 below capture the distinctions between text vs. binary, which is
1686 pervasive in the interface; however we currently do not offer a
1687 way to track the other distinctions in the type system.
1688 """
1689
Guido van Rossumd70fe632015-08-05 12:11:06 +02001690 __slots__ = ()
1691
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001692 @abstractproperty
1693 def mode(self) -> str:
1694 pass
1695
1696 @abstractproperty
1697 def name(self) -> str:
1698 pass
1699
1700 @abstractmethod
1701 def close(self) -> None:
1702 pass
1703
1704 @abstractmethod
1705 def closed(self) -> bool:
1706 pass
1707
1708 @abstractmethod
1709 def fileno(self) -> int:
1710 pass
1711
1712 @abstractmethod
1713 def flush(self) -> None:
1714 pass
1715
1716 @abstractmethod
1717 def isatty(self) -> bool:
1718 pass
1719
1720 @abstractmethod
1721 def read(self, n: int = -1) -> AnyStr:
1722 pass
1723
1724 @abstractmethod
1725 def readable(self) -> bool:
1726 pass
1727
1728 @abstractmethod
1729 def readline(self, limit: int = -1) -> AnyStr:
1730 pass
1731
1732 @abstractmethod
1733 def readlines(self, hint: int = -1) -> List[AnyStr]:
1734 pass
1735
1736 @abstractmethod
1737 def seek(self, offset: int, whence: int = 0) -> int:
1738 pass
1739
1740 @abstractmethod
1741 def seekable(self) -> bool:
1742 pass
1743
1744 @abstractmethod
1745 def tell(self) -> int:
1746 pass
1747
1748 @abstractmethod
1749 def truncate(self, size: int = None) -> int:
1750 pass
1751
1752 @abstractmethod
1753 def writable(self) -> bool:
1754 pass
1755
1756 @abstractmethod
1757 def write(self, s: AnyStr) -> int:
1758 pass
1759
1760 @abstractmethod
1761 def writelines(self, lines: List[AnyStr]) -> None:
1762 pass
1763
1764 @abstractmethod
1765 def __enter__(self) -> 'IO[AnyStr]':
1766 pass
1767
1768 @abstractmethod
1769 def __exit__(self, type, value, traceback) -> None:
1770 pass
1771
1772
1773class BinaryIO(IO[bytes]):
1774 """Typed version of the return of open() in binary mode."""
1775
Guido van Rossumd70fe632015-08-05 12:11:06 +02001776 __slots__ = ()
1777
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001778 @abstractmethod
1779 def write(self, s: Union[bytes, bytearray]) -> int:
1780 pass
1781
1782 @abstractmethod
1783 def __enter__(self) -> 'BinaryIO':
1784 pass
1785
1786
1787class TextIO(IO[str]):
1788 """Typed version of the return of open() in text mode."""
1789
Guido van Rossumd70fe632015-08-05 12:11:06 +02001790 __slots__ = ()
1791
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001792 @abstractproperty
1793 def buffer(self) -> BinaryIO:
1794 pass
1795
1796 @abstractproperty
1797 def encoding(self) -> str:
1798 pass
1799
1800 @abstractproperty
1801 def errors(self) -> str:
1802 pass
1803
1804 @abstractproperty
1805 def line_buffering(self) -> bool:
1806 pass
1807
1808 @abstractproperty
1809 def newlines(self) -> Any:
1810 pass
1811
1812 @abstractmethod
1813 def __enter__(self) -> 'TextIO':
1814 pass
1815
1816
1817class io:
1818 """Wrapper namespace for IO generic classes."""
1819
1820 __all__ = ['IO', 'TextIO', 'BinaryIO']
1821 IO = IO
1822 TextIO = TextIO
1823 BinaryIO = BinaryIO
1824
1825io.__name__ = __name__ + '.io'
1826sys.modules[io.__name__] = io
1827
1828
1829Pattern = _TypeAlias('Pattern', AnyStr, type(stdlib_re.compile('')),
1830 lambda p: p.pattern)
1831Match = _TypeAlias('Match', AnyStr, type(stdlib_re.match('', '')),
1832 lambda m: m.re.pattern)
1833
1834
1835class re:
1836 """Wrapper namespace for re type aliases."""
1837
1838 __all__ = ['Pattern', 'Match']
1839 Pattern = Pattern
1840 Match = Match
1841
1842re.__name__ = __name__ + '.re'
1843sys.modules[re.__name__] = re