blob: 188c94e5ee8214a4eac944c200af4888e31f21b7 [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.
Guido van Rossum0a6976d2016-09-11 15:34:56 -070013if sys.version_info[:2] >= (3, 3):
14 from collections import ChainMap
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070015
16
17# Please keep __all__ alphabetized within each category.
18__all__ = [
19 # Super-special typing primitives.
20 'Any',
21 'Callable',
Guido van Rossum0a6976d2016-09-11 15:34:56 -070022 'ClassVar',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070023 'Generic',
24 'Optional',
Guido van Rossumeb9aca32016-05-24 16:38:22 -070025 'Tuple',
26 'Type',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070027 'TypeVar',
28 'Union',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070029
30 # ABCs (from collections.abc).
31 'AbstractSet', # collections.abc.Set.
Guido van Rossumf17c2002015-12-03 17:31:24 -080032 'Awaitable',
33 'AsyncIterator',
34 'AsyncIterable',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070035 'ByteString',
36 'Container',
37 'Hashable',
38 'ItemsView',
39 'Iterable',
40 'Iterator',
41 'KeysView',
42 'Mapping',
43 'MappingView',
44 'MutableMapping',
45 'MutableSequence',
46 'MutableSet',
47 'Sequence',
48 'Sized',
49 'ValuesView',
50
51 # Structural checks, a.k.a. protocols.
52 'Reversible',
53 'SupportsAbs',
54 'SupportsFloat',
55 'SupportsInt',
56 'SupportsRound',
57
58 # Concrete collection types.
59 'Dict',
Guido van Rossumbd5b9a02016-04-05 08:28:52 -070060 'DefaultDict',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070061 'List',
62 'Set',
Guido van Rossumefa798d2016-08-23 11:01:50 -070063 'FrozenSet',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070064 'NamedTuple', # Not really a type.
65 'Generator',
66
67 # One-off things.
68 'AnyStr',
69 'cast',
70 'get_type_hints',
Guido van Rossum91185fe2016-06-08 11:19:11 -070071 'NewType',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070072 'no_type_check',
73 'no_type_check_decorator',
74 'overload',
Guido van Rossum0e0563c2016-04-05 14:54:25 -070075 'Text',
Guido van Rossum91185fe2016-06-08 11:19:11 -070076 'TYPE_CHECKING',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070077]
78
Guido van Rossumbd5b9a02016-04-05 08:28:52 -070079# The pseudo-submodules 're' and 'io' are part of the public
80# namespace, but excluded from __all__ because they might stomp on
81# legitimate imports of those modules.
82
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070083
84def _qualname(x):
85 if sys.version_info[:2] >= (3, 3):
86 return x.__qualname__
87 else:
88 # Fall back to just name.
89 return x.__name__
90
91
Guido van Rossum4cefe742016-09-27 15:20:12 -070092def _trim_name(nm):
93 if nm.startswith('_') and nm not in ('_TypeAlias',
94 '_ForwardRef', '_TypingBase', '_FinalTypingBase'):
95 nm = nm[1:]
96 return nm
97
98
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070099class TypingMeta(type):
100 """Metaclass for every type defined below.
101
102 This overrides __new__() to require an extra keyword parameter
103 '_root', which serves as a guard against naive subclassing of the
104 typing classes. Any legitimate class defined using a metaclass
105 derived from TypingMeta (including internal subclasses created by
106 e.g. Union[X, Y]) must pass _root=True.
107
108 This also defines a dummy constructor (all the work is done in
109 __new__) and a nicer repr().
110 """
111
112 _is_protocol = False
113
114 def __new__(cls, name, bases, namespace, *, _root=False):
115 if not _root:
116 raise TypeError("Cannot subclass %s" %
117 (', '.join(map(_type_repr, bases)) or '()'))
118 return super().__new__(cls, name, bases, namespace)
119
120 def __init__(self, *args, **kwds):
121 pass
122
123 def _eval_type(self, globalns, localns):
124 """Override this in subclasses to interpret forward references.
125
126 For example, Union['C'] is internally stored as
127 Union[_ForwardRef('C')], which should evaluate to _Union[C],
128 where C is an object found in globalns or localns (searching
129 localns first, of course).
130 """
131 return self
132
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700133 def _get_type_vars(self, tvars):
134 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700135
136 def __repr__(self):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700137 qname = _trim_name(_qualname(self))
138 return '%s.%s' % (self.__module__, qname)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700139
140
Guido van Rossum4cefe742016-09-27 15:20:12 -0700141class _TypingBase(metaclass=TypingMeta, _root=True):
142 """Indicator of special typing constructs."""
143
144 __slots__ = ()
145
Guido van Rossum4cefe742016-09-27 15:20:12 -0700146 def __init__(self, *args, **kwds):
147 pass
148
149 def __new__(cls, *args, **kwds):
150 """Constructor.
151
152 This only exists to give a better error message in case
153 someone tries to subclass a special typing object (not a good idea).
154 """
155 if (len(args) == 3 and
156 isinstance(args[0], str) and
157 isinstance(args[1], tuple)):
158 # Close enough.
159 raise TypeError("Cannot subclass %r" % cls)
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700160 return super().__new__(cls)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700161
162 # Things that are not classes also need these.
163 def _eval_type(self, globalns, localns):
164 return self
165
166 def _get_type_vars(self, tvars):
167 pass
168
169 def __repr__(self):
170 cls = type(self)
171 qname = _trim_name(_qualname(cls))
172 return '%s.%s' % (cls.__module__, qname)
173
174 def __call__(self, *args, **kwds):
175 raise TypeError("Cannot instantiate %r" % type(self))
176
177
178class _FinalTypingBase(_TypingBase, _root=True):
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700179 """Mix-in class to prevent instantiation.
180
181 Prevents instantiation unless _root=True is given in class call.
182 It is used to create pseudo-singleton instances Any, Union, Tuple, etc.
183 """
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700184
Guido van Rossumd70fe632015-08-05 12:11:06 +0200185 __slots__ = ()
186
Guido van Rossum4cefe742016-09-27 15:20:12 -0700187 def __new__(cls, *args, _root=False, **kwds):
188 self = super().__new__(cls, *args, **kwds)
189 if _root is True:
190 return self
191 raise TypeError("Cannot instantiate %r" % cls)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700192
193
Guido van Rossum4cefe742016-09-27 15:20:12 -0700194class _ForwardRef(_TypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700195 """Wrapper to hold a forward reference."""
196
Guido van Rossum4cefe742016-09-27 15:20:12 -0700197 __slots__ = ('__forward_arg__', '__forward_code__',
198 '__forward_evaluated__', '__forward_value__',
199 '__forward_frame__')
200
201 def __init__(self, arg):
202 super().__init__(arg)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700203 if not isinstance(arg, str):
204 raise TypeError('ForwardRef must be a string -- got %r' % (arg,))
205 try:
206 code = compile(arg, '<string>', 'eval')
207 except SyntaxError:
208 raise SyntaxError('ForwardRef must be an expression -- got %r' %
209 (arg,))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700210 self.__forward_arg__ = arg
211 self.__forward_code__ = code
212 self.__forward_evaluated__ = False
213 self.__forward_value__ = None
214 typing_globals = globals()
215 frame = sys._getframe(1)
216 while frame is not None and frame.f_globals is typing_globals:
217 frame = frame.f_back
218 assert frame is not None
219 self.__forward_frame__ = frame
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700220
221 def _eval_type(self, globalns, localns):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700222 if not self.__forward_evaluated__:
223 if globalns is None and localns is None:
224 globalns = localns = {}
225 elif globalns is None:
226 globalns = localns
227 elif localns is None:
228 localns = globalns
229 self.__forward_value__ = _type_check(
230 eval(self.__forward_code__, globalns, localns),
231 "Forward references must evaluate to types.")
232 self.__forward_evaluated__ = True
233 return self.__forward_value__
234
Guido van Rossum4cefe742016-09-27 15:20:12 -0700235 def __eq__(self, other):
236 if not isinstance(other, _ForwardRef):
237 return NotImplemented
238 return (self.__forward_arg__ == other.__forward_arg__ and
239 self.__forward_frame__ == other.__forward_frame__)
240
241 def __hash__(self):
242 return hash((self.__forward_arg__, self.__forward_frame__))
243
Guido van Rossumd70fe632015-08-05 12:11:06 +0200244 def __instancecheck__(self, obj):
245 raise TypeError("Forward references cannot be used with isinstance().")
246
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700247 def __subclasscheck__(self, cls):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700248 raise TypeError("Forward references cannot be used with issubclass().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700249
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700250 def __repr__(self):
251 return '_ForwardRef(%r)' % (self.__forward_arg__,)
252
253
Guido van Rossum4cefe742016-09-27 15:20:12 -0700254class _TypeAlias(_TypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700255 """Internal helper class for defining generic variants of concrete types.
256
Guido van Rossum4cefe742016-09-27 15:20:12 -0700257 Note that this is not a type; let's call it a pseudo-type. It cannot
258 be used in instance and subclass checks in parameterized form, i.e.
259 ``isinstance(42, Match[str])`` raises ``TypeError`` instead of returning
260 ``False``.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700261 """
262
Guido van Rossumd70fe632015-08-05 12:11:06 +0200263 __slots__ = ('name', 'type_var', 'impl_type', 'type_checker')
264
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700265 def __init__(self, name, type_var, impl_type, type_checker):
266 """Initializer.
267
268 Args:
269 name: The name, e.g. 'Pattern'.
270 type_var: The type parameter, e.g. AnyStr, or the
271 specific type, e.g. str.
272 impl_type: The implementation type.
273 type_checker: Function that takes an impl_type instance.
274 and returns a value that should be a type_var instance.
275 """
276 assert isinstance(name, str), repr(name)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700277 assert isinstance(impl_type, type), repr(impl_type)
278 assert not isinstance(impl_type, TypingMeta), repr(impl_type)
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700279 assert isinstance(type_var, (type, _TypingBase)), repr(type_var)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700280 self.name = name
281 self.type_var = type_var
282 self.impl_type = impl_type
283 self.type_checker = type_checker
284
285 def __repr__(self):
286 return "%s[%s]" % (self.name, _type_repr(self.type_var))
287
288 def __getitem__(self, parameter):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700289 if not isinstance(self.type_var, TypeVar):
290 raise TypeError("%s cannot be further parameterized." % self)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700291 if self.type_var.__constraints__ and isinstance(parameter, type):
292 if not issubclass(parameter, self.type_var.__constraints__):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700293 raise TypeError("%s is not a valid substitution for %s." %
294 (parameter, self.type_var))
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700295 if isinstance(parameter, TypeVar) and parameter is not self.type_var:
296 raise TypeError("%s cannot be re-parameterized." % self)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700297 return self.__class__(self.name, parameter,
298 self.impl_type, self.type_checker)
299
Guido van Rossum4cefe742016-09-27 15:20:12 -0700300 def __eq__(self, other):
301 if not isinstance(other, _TypeAlias):
302 return NotImplemented
303 return self.name == other.name and self.type_var == other.type_var
304
305 def __hash__(self):
306 return hash((self.name, self.type_var))
307
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700308 def __instancecheck__(self, obj):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700309 if not isinstance(self.type_var, TypeVar):
310 raise TypeError("Parameterized type aliases cannot be used "
311 "with isinstance().")
312 return isinstance(obj, self.impl_type)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700313
314 def __subclasscheck__(self, cls):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700315 if not isinstance(self.type_var, TypeVar):
316 raise TypeError("Parameterized type aliases cannot be used "
317 "with issubclass().")
318 return issubclass(cls, self.impl_type)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700319
320
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700321def _get_type_vars(types, tvars):
322 for t in types:
Guido van Rossum4cefe742016-09-27 15:20:12 -0700323 if isinstance(t, TypingMeta) or isinstance(t, _TypingBase):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700324 t._get_type_vars(tvars)
325
326
327def _type_vars(types):
328 tvars = []
329 _get_type_vars(types, tvars)
330 return tuple(tvars)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700331
332
333def _eval_type(t, globalns, localns):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700334 if isinstance(t, TypingMeta) or isinstance(t, _TypingBase):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700335 return t._eval_type(globalns, localns)
336 else:
337 return t
338
339
340def _type_check(arg, msg):
341 """Check that the argument is a type, and return it.
342
343 As a special case, accept None and return type(None) instead.
344 Also, _TypeAlias instances (e.g. Match, Pattern) are acceptable.
345
346 The msg argument is a human-readable error message, e.g.
347
348 "Union[arg, ...]: arg should be a type."
349
350 We append the repr() of the actual value (truncated to 100 chars).
351 """
352 if arg is None:
353 return type(None)
354 if isinstance(arg, str):
355 arg = _ForwardRef(arg)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700356 if not isinstance(arg, (type, _TypingBase)) and not callable(arg):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700357 raise TypeError(msg + " Got %.100r." % (arg,))
358 return arg
359
360
361def _type_repr(obj):
362 """Return the repr() of an object, special-casing types.
363
364 If obj is a type, we return a shorter version than the default
365 type.__repr__, based on the module and qualified name, which is
366 typically enough to uniquely identify a type. For everything
367 else, we fall back on repr(obj).
368 """
369 if isinstance(obj, type) and not isinstance(obj, TypingMeta):
370 if obj.__module__ == 'builtins':
371 return _qualname(obj)
372 else:
373 return '%s.%s' % (obj.__module__, _qualname(obj))
374 else:
375 return repr(obj)
376
377
Guido van Rossum4cefe742016-09-27 15:20:12 -0700378class _Any(_FinalTypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700379 """Special type indicating an unconstrained type.
380
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700381 - Any is compatible with every type.
382 - Any assumed to have all methods.
383 - All values assumed to be instances of Any.
384
385 Note that all the above statements are true from the point of view of
386 static type checkers. At runtime, Any should not be used with instance
387 or class checks.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700388 """
389
Guido van Rossumd70fe632015-08-05 12:11:06 +0200390 __slots__ = ()
391
Guido van Rossum4cefe742016-09-27 15:20:12 -0700392 def __instancecheck__(self, obj):
393 raise TypeError("Any cannot be used with isinstance().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700394
Guido van Rossum4cefe742016-09-27 15:20:12 -0700395 def __subclasscheck__(self, cls):
396 raise TypeError("Any cannot be used with issubclass().")
397
398
399Any = _Any(_root=True)
400
401
402class TypeVar(_TypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700403 """Type variable.
404
405 Usage::
406
407 T = TypeVar('T') # Can be anything
408 A = TypeVar('A', str, bytes) # Must be str or bytes
409
410 Type variables exist primarily for the benefit of static type
411 checkers. They serve as the parameters for generic types as well
412 as for generic function definitions. See class Generic for more
413 information on generic types. Generic functions work as follows:
414
415 def repeat(x: T, n: int) -> Sequence[T]:
416 '''Return a list containing n references to x.'''
417 return [x]*n
418
419 def longest(x: A, y: A) -> A:
420 '''Return the longest of two strings.'''
421 return x if len(x) >= len(y) else y
422
423 The latter example's signature is essentially the overloading
424 of (str, str) -> str and (bytes, bytes) -> bytes. Also note
425 that if the arguments are instances of some subclass of str,
426 the return type is still plain str.
427
428 At runtime, isinstance(x, T) will raise TypeError. However,
429 issubclass(C, T) is true for any class C, and issubclass(str, A)
430 and issubclass(bytes, A) are true, and issubclass(int, A) is
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700431 false. (TODO: Why is this needed? This may change. See #136.)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700432
Guido van Rossumefa798d2016-08-23 11:01:50 -0700433 Type variables defined with covariant=True or contravariant=True
434 can be used do declare covariant or contravariant generic types.
435 See PEP 484 for more details. By default generic types are invariant
436 in all type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700437
438 Type variables can be introspected. e.g.:
439
440 T.__name__ == 'T'
441 T.__constraints__ == ()
442 T.__covariant__ == False
443 T.__contravariant__ = False
444 A.__constraints__ == (str, bytes)
445 """
446
Guido van Rossum4cefe742016-09-27 15:20:12 -0700447 __slots__ = ('__name__', '__bound__', '__constraints__',
448 '__covariant__', '__contravariant__')
449
450 def __init__(self, name, *constraints, bound=None,
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700451 covariant=False, contravariant=False):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700452 super().__init__(name, *constraints, bound=bound,
453 covariant=covariant, contravariant=contravariant)
454 self.__name__ = name
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700455 if covariant and contravariant:
Guido van Rossumefa798d2016-08-23 11:01:50 -0700456 raise ValueError("Bivariant types are not supported.")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700457 self.__covariant__ = bool(covariant)
458 self.__contravariant__ = bool(contravariant)
459 if constraints and bound is not None:
460 raise TypeError("Constraints cannot be combined with bound=...")
461 if constraints and len(constraints) == 1:
462 raise TypeError("A single constraint is not allowed")
463 msg = "TypeVar(name, constraint, ...): constraints must be types."
464 self.__constraints__ = tuple(_type_check(t, msg) for t in constraints)
465 if bound:
466 self.__bound__ = _type_check(bound, "Bound must be a type.")
467 else:
468 self.__bound__ = None
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700469
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700470 def _get_type_vars(self, tvars):
471 if self not in tvars:
472 tvars.append(self)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700473
474 def __repr__(self):
475 if self.__covariant__:
476 prefix = '+'
477 elif self.__contravariant__:
478 prefix = '-'
479 else:
480 prefix = '~'
481 return prefix + self.__name__
482
483 def __instancecheck__(self, instance):
484 raise TypeError("Type variables cannot be used with isinstance().")
485
486 def __subclasscheck__(self, cls):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700487 raise TypeError("Type variables cannot be used with issubclass().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700488
489
490# Some unconstrained type variables. These are used by the container types.
Guido van Rossumeb9aca32016-05-24 16:38:22 -0700491# (These are not for export.)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700492T = TypeVar('T') # Any type.
493KT = TypeVar('KT') # Key type.
494VT = TypeVar('VT') # Value type.
495T_co = TypeVar('T_co', covariant=True) # Any type covariant containers.
496V_co = TypeVar('V_co', covariant=True) # Any type covariant containers.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700497VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
498T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
499
500# A useful type variable with constraints. This represents string types.
Guido van Rossumeb9aca32016-05-24 16:38:22 -0700501# (This one *is* for export!)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700502AnyStr = TypeVar('AnyStr', bytes, str)
503
504
Guido van Rossum4cefe742016-09-27 15:20:12 -0700505def _tp_cache(func):
506 cached = functools.lru_cache()(func)
507 @functools.wraps(func)
508 def inner(*args, **kwds):
509 try:
510 return cached(*args, **kwds)
511 except TypeError:
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700512 pass # All real errors (not unhashable args) are raised below.
Guido van Rossum4cefe742016-09-27 15:20:12 -0700513 return func(*args, **kwds)
514 return inner
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700515
516
Guido van Rossum4cefe742016-09-27 15:20:12 -0700517class _Union(_FinalTypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700518 """Union type; Union[X, Y] means either X or Y.
519
520 To define a union, use e.g. Union[int, str]. Details:
521
522 - The arguments must be types and there must be at least one.
523
524 - None as an argument is a special case and is replaced by
525 type(None).
526
527 - Unions of unions are flattened, e.g.::
528
529 Union[Union[int, str], float] == Union[int, str, float]
530
531 - Unions of a single argument vanish, e.g.::
532
533 Union[int] == int # The constructor actually returns int
534
535 - Redundant arguments are skipped, e.g.::
536
537 Union[int, str, int] == Union[int, str]
538
539 - When comparing unions, the argument order is ignored, e.g.::
540
541 Union[int, str] == Union[str, int]
542
543 - When two arguments have a subclass relationship, the least
544 derived argument is kept, e.g.::
545
546 class Employee: pass
547 class Manager(Employee): pass
548 Union[int, Employee, Manager] == Union[int, Employee]
549 Union[Manager, int, Employee] == Union[int, Employee]
550 Union[Employee, Manager] == Employee
551
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700552 - Similar for object::
553
554 Union[int, object] == object
555
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700556 - You cannot subclass or instantiate a union.
557
558 - You cannot write Union[X][Y] (what would it mean?).
559
560 - You can use Optional[X] as a shorthand for Union[X, None].
561 """
562
Guido van Rossum4cefe742016-09-27 15:20:12 -0700563 __slots__ = ('__union_params__', '__union_set_params__')
564
565 def __new__(cls, parameters=None, *args, _root=False):
566 self = super().__new__(cls, parameters, *args, _root=_root)
567 if parameters is None:
568 self.__union_params__ = None
569 self.__union_set_params__ = None
570 return self
571 if not isinstance(parameters, tuple):
572 raise TypeError("Expected parameters=<tuple>")
573 # Flatten out Union[Union[...], ...] and type-check non-Union args.
574 params = []
575 msg = "Union[arg, ...]: each arg must be a type."
576 for p in parameters:
577 if isinstance(p, _Union):
578 params.extend(p.__union_params__)
579 else:
580 params.append(_type_check(p, msg))
581 # Weed out strict duplicates, preserving the first of each occurrence.
582 all_params = set(params)
583 if len(all_params) < len(params):
584 new_params = []
585 for t in params:
586 if t in all_params:
587 new_params.append(t)
588 all_params.remove(t)
589 params = new_params
590 assert not all_params, all_params
591 # Weed out subclasses.
592 # E.g. Union[int, Employee, Manager] == Union[int, Employee].
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700593 # If object is present it will be sole survivor among proper classes.
594 # Never discard type variables.
Guido van Rossum4cefe742016-09-27 15:20:12 -0700595 # (In particular, Union[str, AnyStr] != AnyStr.)
596 all_params = set(params)
597 for t1 in params:
Guido van Rossum4cefe742016-09-27 15:20:12 -0700598 if not isinstance(t1, type):
599 continue
600 if any(isinstance(t2, type) and issubclass(t1, t2)
601 for t2 in all_params - {t1}
602 if not (isinstance(t2, GenericMeta) and
603 t2.__origin__ is not None)):
604 all_params.remove(t1)
605 # It's not a union if there's only one type left.
606 if len(all_params) == 1:
607 return all_params.pop()
608 self.__union_params__ = tuple(t for t in params if t in all_params)
609 self.__union_set_params__ = frozenset(self.__union_params__)
610 return self
611
612 def _eval_type(self, globalns, localns):
613 p = tuple(_eval_type(t, globalns, localns)
614 for t in self.__union_params__)
615 if p == self.__union_params__:
616 return self
617 else:
618 return self.__class__(p, _root=True)
619
620 def _get_type_vars(self, tvars):
621 if self.__union_params__:
622 _get_type_vars(self.__union_params__, tvars)
623
624 def __repr__(self):
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700625 return self._subs_repr([], [])
626
627 def _subs_repr(self, tvars, args):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700628 r = super().__repr__()
629 if self.__union_params__:
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700630 r += '[%s]' % (', '.join(_replace_arg(t, tvars, args)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700631 for t in self.__union_params__))
632 return r
633
634 @_tp_cache
635 def __getitem__(self, parameters):
636 if self.__union_params__ is not None:
637 raise TypeError(
638 "Cannot subscript an existing Union. Use Union[u, t] instead.")
639 if parameters == ():
640 raise TypeError("Cannot take a Union of no types.")
641 if not isinstance(parameters, tuple):
642 parameters = (parameters,)
643 return self.__class__(parameters, _root=True)
644
645 def __eq__(self, other):
646 if not isinstance(other, _Union):
647 return NotImplemented
648 return self.__union_set_params__ == other.__union_set_params__
649
650 def __hash__(self):
651 return hash(self.__union_set_params__)
652
653 def __instancecheck__(self, obj):
654 raise TypeError("Unions cannot be used with isinstance().")
655
656 def __subclasscheck__(self, cls):
657 raise TypeError("Unions cannot be used with issubclass().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700658
659
Guido van Rossum4cefe742016-09-27 15:20:12 -0700660Union = _Union(_root=True)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700661
662
Guido van Rossum4cefe742016-09-27 15:20:12 -0700663class _Optional(_FinalTypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700664 """Optional type.
665
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700666 Optional[X] is equivalent to Union[X, None].
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700667 """
668
Guido van Rossumd70fe632015-08-05 12:11:06 +0200669 __slots__ = ()
670
Guido van Rossum4cefe742016-09-27 15:20:12 -0700671 @_tp_cache
672 def __getitem__(self, arg):
673 arg = _type_check(arg, "Optional[t] requires a single type.")
674 return Union[arg, type(None)]
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700675
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700676
Guido van Rossum4cefe742016-09-27 15:20:12 -0700677Optional = _Optional(_root=True)
678
679
680class _Tuple(_FinalTypingBase, _root=True):
681 """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
682
683 Example: Tuple[T1, T2] is a tuple of two elements corresponding
684 to type variables T1 and T2. Tuple[int, float, str] is a tuple
685 of an int, a float and a string.
686
687 To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
688 """
689
690 __slots__ = ('__tuple_params__', '__tuple_use_ellipsis__')
691
692 def __init__(self, parameters=None,
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700693 use_ellipsis=False, _root=False):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700694 self.__tuple_params__ = parameters
695 self.__tuple_use_ellipsis__ = use_ellipsis
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700696
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700697 def _get_type_vars(self, tvars):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700698 if self.__tuple_params__:
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700699 _get_type_vars(self.__tuple_params__, tvars)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700700
701 def _eval_type(self, globalns, localns):
702 tp = self.__tuple_params__
703 if tp is None:
704 return self
705 p = tuple(_eval_type(t, globalns, localns) for t in tp)
706 if p == self.__tuple_params__:
707 return self
708 else:
Guido van Rossum4cefe742016-09-27 15:20:12 -0700709 return self.__class__(p, _root=True)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700710
711 def __repr__(self):
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700712 return self._subs_repr([], [])
713
714 def _subs_repr(self, tvars, args):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700715 r = super().__repr__()
716 if self.__tuple_params__ is not None:
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700717 params = [_replace_arg(p, tvars, args) for p in self.__tuple_params__]
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700718 if self.__tuple_use_ellipsis__:
719 params.append('...')
Guido van Rossum91185fe2016-06-08 11:19:11 -0700720 if not params:
721 params.append('()')
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700722 r += '[%s]' % (
723 ', '.join(params))
724 return r
725
Guido van Rossum4cefe742016-09-27 15:20:12 -0700726 @_tp_cache
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700727 def __getitem__(self, parameters):
728 if self.__tuple_params__ is not None:
729 raise TypeError("Cannot re-parameterize %r" % (self,))
730 if not isinstance(parameters, tuple):
731 parameters = (parameters,)
732 if len(parameters) == 2 and parameters[1] == Ellipsis:
733 parameters = parameters[:1]
734 use_ellipsis = True
735 msg = "Tuple[t, ...]: t must be a type."
736 else:
737 use_ellipsis = False
738 msg = "Tuple[t0, t1, ...]: each t must be a type."
739 parameters = tuple(_type_check(p, msg) for p in parameters)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700740 return self.__class__(parameters,
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700741 use_ellipsis=use_ellipsis, _root=True)
742
743 def __eq__(self, other):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700744 if not isinstance(other, _Tuple):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700745 return NotImplemented
Guido van Rossum5abcbb32016-04-18 07:37:41 -0700746 return (self.__tuple_params__ == other.__tuple_params__ and
747 self.__tuple_use_ellipsis__ == other.__tuple_use_ellipsis__)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700748
749 def __hash__(self):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700750 return hash((self.__tuple_params__, self.__tuple_use_ellipsis__))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700751
Guido van Rossumd70fe632015-08-05 12:11:06 +0200752 def __instancecheck__(self, obj):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700753 if self.__tuple_params__ == None:
754 return isinstance(obj, tuple)
755 raise TypeError("Parameterized Tuple cannot be used "
756 "with isinstance().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700757
758 def __subclasscheck__(self, cls):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700759 if self.__tuple_params__ == None:
760 return issubclass(cls, tuple)
761 raise TypeError("Parameterized Tuple cannot be used "
762 "with issubclass().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700763
764
Guido van Rossum4cefe742016-09-27 15:20:12 -0700765Tuple = _Tuple(_root=True)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700766
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700767
Guido van Rossum4cefe742016-09-27 15:20:12 -0700768class _Callable(_FinalTypingBase, _root=True):
769 """Callable type; Callable[[int], str] is a function of (int) -> str.
770
771 The subscription syntax must always be used with exactly two
772 values: the argument list and the return type. The argument list
773 must be a list of types; the return type must be a single type.
774
775 There is no syntax to indicate optional or keyword arguments,
776 such function types are rarely used as callback types.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700777 """
778
Guido van Rossum4cefe742016-09-27 15:20:12 -0700779 __slots__ = ('__args__', '__result__')
Guido van Rossumd70fe632015-08-05 12:11:06 +0200780
Guido van Rossum4cefe742016-09-27 15:20:12 -0700781 def __init__(self, args=None, result=None, _root=False):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700782 if args is None and result is None:
Guido van Rossum4cefe742016-09-27 15:20:12 -0700783 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700784 else:
785 if args is not Ellipsis:
786 if not isinstance(args, list):
787 raise TypeError("Callable[args, result]: "
788 "args must be a list."
789 " Got %.100r." % (args,))
790 msg = "Callable[[arg, ...], result]: each arg must be a type."
791 args = tuple(_type_check(arg, msg) for arg in args)
792 msg = "Callable[args, result]: result must be a type."
793 result = _type_check(result, msg)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700794 self.__args__ = args
795 self.__result__ = result
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700796
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700797 def _get_type_vars(self, tvars):
Guido van Rossumefa798d2016-08-23 11:01:50 -0700798 if self.__args__ and self.__args__ is not Ellipsis:
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700799 _get_type_vars(self.__args__, tvars)
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700800 if self.__result__:
801 _get_type_vars([self.__result__], tvars)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700802
803 def _eval_type(self, globalns, localns):
804 if self.__args__ is None and self.__result__ is None:
805 return self
Guido van Rossumd70fe632015-08-05 12:11:06 +0200806 if self.__args__ is Ellipsis:
807 args = self.__args__
808 else:
809 args = [_eval_type(t, globalns, localns) for t in self.__args__]
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700810 result = _eval_type(self.__result__, globalns, localns)
811 if args == self.__args__ and result == self.__result__:
812 return self
813 else:
Guido van Rossum4cefe742016-09-27 15:20:12 -0700814 return self.__class__(args, result, _root=True)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700815
816 def __repr__(self):
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700817 return self._subs_repr([], [])
818
819 def _subs_repr(self, tvars, args):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700820 r = super().__repr__()
821 if self.__args__ is not None or self.__result__ is not None:
822 if self.__args__ is Ellipsis:
823 args_r = '...'
824 else:
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700825 args_r = '[%s]' % ', '.join(_replace_arg(t, tvars, args)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700826 for t in self.__args__)
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700827 r += '[%s, %s]' % (args_r, _replace_arg(self.__result__, tvars, args))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700828 return r
829
830 def __getitem__(self, parameters):
831 if self.__args__ is not None or self.__result__ is not None:
832 raise TypeError("This Callable type is already parameterized.")
833 if not isinstance(parameters, tuple) or len(parameters) != 2:
834 raise TypeError(
835 "Callable must be used as Callable[[arg, ...], result].")
836 args, result = parameters
Guido van Rossum4cefe742016-09-27 15:20:12 -0700837 return self.__class__(args, result, _root=True)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700838
839 def __eq__(self, other):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700840 if not isinstance(other, _Callable):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700841 return NotImplemented
842 return (self.__args__ == other.__args__ and
843 self.__result__ == other.__result__)
844
845 def __hash__(self):
846 return hash(self.__args__) ^ hash(self.__result__)
847
Guido van Rossumd70fe632015-08-05 12:11:06 +0200848 def __instancecheck__(self, obj):
849 # For unparametrized Callable we allow this, because
850 # typing.Callable should be equivalent to
851 # collections.abc.Callable.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700852 if self.__args__ is None and self.__result__ is None:
Guido van Rossumd70fe632015-08-05 12:11:06 +0200853 return isinstance(obj, collections_abc.Callable)
854 else:
Guido van Rossum4cefe742016-09-27 15:20:12 -0700855 raise TypeError("Parameterized Callable cannot be used "
856 "with isinstance().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700857
858 def __subclasscheck__(self, cls):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700859 if self.__args__ is None and self.__result__ is None:
Guido van Rossum4cefe742016-09-27 15:20:12 -0700860 return issubclass(cls, collections_abc.Callable)
861 else:
862 raise TypeError("Parameterized Callable cannot be used "
863 "with issubclass().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700864
865
Guido van Rossum4cefe742016-09-27 15:20:12 -0700866Callable = _Callable(_root=True)
Guido van Rossumd70fe632015-08-05 12:11:06 +0200867
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700868
869def _gorg(a):
870 """Return the farthest origin of a generic class."""
871 assert isinstance(a, GenericMeta)
872 while a.__origin__ is not None:
873 a = a.__origin__
874 return a
875
876
877def _geqv(a, b):
878 """Return whether two generic classes are equivalent.
879
880 The intention is to consider generic class X and any of its
881 parameterized forms (X[T], X[int], etc.) as equivalent.
882
883 However, X is not equivalent to a subclass of X.
884
885 The relation is reflexive, symmetric and transitive.
886 """
887 assert isinstance(a, GenericMeta) and isinstance(b, GenericMeta)
888 # Reduce each to its origin.
889 return _gorg(a) is _gorg(b)
890
891
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700892def _replace_arg(arg, tvars, args):
893 if hasattr(arg, '_subs_repr'):
894 return arg._subs_repr(tvars, args)
895 if isinstance(arg, TypeVar):
896 for i, tvar in enumerate(tvars):
897 if arg.__name__ == tvar.__name__:
898 return args[i]
899 return _type_repr(arg)
900
901
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700902def _next_in_mro(cls):
903 """Helper for Generic.__new__.
904
905 Returns the class after the last occurrence of Generic or
906 Generic[...] in cls.__mro__.
907 """
908 next_in_mro = object
909 # Look for the last occurrence of Generic or Generic[...].
910 for i, c in enumerate(cls.__mro__[:-1]):
911 if isinstance(c, GenericMeta) and _gorg(c) is Generic:
912 next_in_mro = cls.__mro__[i+1]
913 return next_in_mro
914
915
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700916def _valid_for_check(cls):
917 if cls is Generic:
918 raise TypeError("Class %r cannot be used with class "
919 "or instance checks" % cls)
920 if (cls.__origin__ is not None and
921 sys._getframe(3).f_globals['__name__'] not in ['abc', 'functools']):
922 raise TypeError("Parameterized generics cannot be used with class "
923 "or instance checks")
924
925
926def _make_subclasshook(cls):
927 """Construct a __subclasshook__ callable that incorporates
928 the associated __extra__ class in subclass checks performed
929 against cls.
930 """
931 if isinstance(cls.__extra__, abc.ABCMeta):
932 # The logic mirrors that of ABCMeta.__subclasscheck__.
933 # Registered classes need not be checked here because
934 # cls and its extra share the same _abc_registry.
935 def __extrahook__(subclass):
936 _valid_for_check(cls)
937 res = cls.__extra__.__subclasshook__(subclass)
938 if res is not NotImplemented:
939 return res
940 if cls.__extra__ in subclass.__mro__:
941 return True
942 for scls in cls.__extra__.__subclasses__():
943 if isinstance(scls, GenericMeta):
944 continue
945 if issubclass(subclass, scls):
946 return True
947 return NotImplemented
948 else:
949 # For non-ABC extras we'll just call issubclass().
950 def __extrahook__(subclass):
951 _valid_for_check(cls)
952 if cls.__extra__ and issubclass(subclass, cls.__extra__):
953 return True
954 return NotImplemented
955 return __extrahook__
956
957
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700958class GenericMeta(TypingMeta, abc.ABCMeta):
959 """Metaclass for generic types."""
960
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700961 def __new__(cls, name, bases, namespace,
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700962 tvars=None, args=None, origin=None, extra=None, orig_bases=None):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700963 if tvars is not None:
964 # Called from __getitem__() below.
965 assert origin is not None
966 assert all(isinstance(t, TypeVar) for t in tvars), tvars
967 else:
968 # Called from class statement.
969 assert tvars is None, tvars
970 assert args is None, args
971 assert origin is None, origin
972
973 # Get the full set of tvars from the bases.
974 tvars = _type_vars(bases)
975 # Look for Generic[T1, ..., Tn].
976 # If found, tvars must be a subset of it.
977 # If not found, tvars is it.
978 # Also check for and reject plain Generic,
979 # and reject multiple Generic[...].
980 gvars = None
981 for base in bases:
982 if base is Generic:
983 raise TypeError("Cannot inherit from plain Generic")
984 if (isinstance(base, GenericMeta) and
985 base.__origin__ is Generic):
986 if gvars is not None:
987 raise TypeError(
988 "Cannot inherit from Generic[...] multiple types.")
989 gvars = base.__parameters__
990 if gvars is None:
991 gvars = tvars
992 else:
993 tvarset = set(tvars)
994 gvarset = set(gvars)
995 if not tvarset <= gvarset:
996 raise TypeError(
997 "Some type variables (%s) "
998 "are not listed in Generic[%s]" %
999 (", ".join(str(t) for t in tvars if t not in gvarset),
1000 ", ".join(str(g) for g in gvars)))
1001 tvars = gvars
1002
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001003 initial_bases = bases
1004 if extra is not None and type(extra) is abc.ABCMeta and extra not in bases:
1005 bases = (extra,) + bases
1006 bases = tuple(_gorg(b) if isinstance(b, GenericMeta) else b for b in bases)
1007
1008 # remove bare Generic from bases if there are other generic bases
1009 if any(isinstance(b, GenericMeta) and b is not Generic for b in bases):
1010 bases = tuple(b for b in bases if b is not Generic)
1011 self = super().__new__(cls, name, bases, namespace, _root=True)
1012
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001013 self.__parameters__ = tvars
1014 self.__args__ = args
1015 self.__origin__ = origin
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001016 self.__extra__ = extra
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001017 # Speed hack (https://github.com/python/typing/issues/196).
1018 self.__next_in_mro__ = _next_in_mro(self)
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001019 # Preserve base classes on subclassing (__bases__ are type erased now).
1020 if orig_bases is None:
1021 self.__orig_bases__ = initial_bases
Guido van Rossumb47c9d22016-10-03 08:40:50 -07001022
1023 # This allows unparameterized generic collections to be used
1024 # with issubclass() and isinstance() in the same way as their
1025 # collections.abc counterparts (e.g., isinstance([], Iterable)).
Guido van Rossume2592672016-10-08 20:27:22 -07001026 if ('__subclasshook__' not in namespace and extra # allow overriding
1027 or hasattr(self.__subclasshook__, '__name__') and
1028 self.__subclasshook__.__name__ == '__extrahook__'):
1029 self.__subclasshook__ = _make_subclasshook(self)
Guido van Rossumb47c9d22016-10-03 08:40:50 -07001030 if isinstance(extra, abc.ABCMeta):
1031 self._abc_registry = extra._abc_registry
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001032 return self
1033
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001034 def _get_type_vars(self, tvars):
1035 if self.__origin__ and self.__parameters__:
1036 _get_type_vars(self.__parameters__, tvars)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001037
1038 def __repr__(self):
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001039 if self.__origin__ is None:
1040 return super().__repr__()
1041 return self._subs_repr([], [])
1042
1043 def _subs_repr(self, tvars, args):
1044 assert len(tvars) == len(args)
1045 # Construct the chain of __origin__'s.
1046 current = self.__origin__
1047 orig_chain = []
1048 while current.__origin__ is not None:
1049 orig_chain.append(current)
1050 current = current.__origin__
1051 # Replace type variables in __args__ if asked ...
1052 str_args = []
1053 for arg in self.__args__:
1054 str_args.append(_replace_arg(arg, tvars, args))
1055 # ... then continue replacing down the origin chain.
1056 for cls in orig_chain:
1057 new_str_args = []
1058 for i, arg in enumerate(cls.__args__):
1059 new_str_args.append(_replace_arg(arg, cls.__parameters__, str_args))
1060 str_args = new_str_args
1061 return super().__repr__() + '[%s]' % ', '.join(str_args)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001062
1063 def __eq__(self, other):
1064 if not isinstance(other, GenericMeta):
1065 return NotImplemented
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001066 if self.__origin__ is not None:
1067 return (self.__origin__ is other.__origin__ and
1068 self.__args__ == other.__args__ and
1069 self.__parameters__ == other.__parameters__)
1070 else:
1071 return self is other
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001072
1073 def __hash__(self):
1074 return hash((self.__name__, self.__parameters__))
1075
Guido van Rossum4cefe742016-09-27 15:20:12 -07001076 @_tp_cache
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001077 def __getitem__(self, params):
1078 if not isinstance(params, tuple):
1079 params = (params,)
1080 if not params:
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001081 raise TypeError(
1082 "Parameter list to %s[...] cannot be empty" % _qualname(self))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001083 msg = "Parameters to generic types must be types."
1084 params = tuple(_type_check(p, msg) for p in params)
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001085 if self is Generic:
1086 # Generic can only be subscripted with unique type variables.
1087 if not all(isinstance(p, TypeVar) for p in params):
1088 raise TypeError(
1089 "Parameters to Generic[...] must all be type variables")
Guido van Rossumd70fe632015-08-05 12:11:06 +02001090 if len(set(params)) != len(params):
Guido van Rossum1b669102015-09-04 12:15:54 -07001091 raise TypeError(
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001092 "Parameters to Generic[...] must all be unique")
1093 tvars = params
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001094 args = params
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001095 elif self is _Protocol:
1096 # _Protocol is internal, don't check anything.
1097 tvars = params
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001098 args = params
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001099 elif self.__origin__ in (Generic, _Protocol):
1100 # Can't subscript Generic[...] or _Protocol[...].
1101 raise TypeError("Cannot subscript already-subscripted %s" %
1102 repr(self))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001103 else:
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001104 # Subscripting a regular Generic subclass.
1105 if not self.__parameters__:
1106 raise TypeError("%s is not a generic class" % repr(self))
1107 alen = len(params)
1108 elen = len(self.__parameters__)
1109 if alen != elen:
1110 raise TypeError(
1111 "Too %s parameters for %s; actual %s, expected %s" %
1112 ("many" if alen > elen else "few", repr(self), alen, elen))
1113 tvars = _type_vars(params)
1114 args = params
1115 return self.__class__(self.__name__,
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001116 self.__bases__,
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001117 dict(self.__dict__),
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001118 tvars=tvars,
1119 args=args,
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001120 origin=self,
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001121 extra=self.__extra__,
1122 orig_bases=self.__orig_bases__)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001123
Guido van Rossum1b669102015-09-04 12:15:54 -07001124 def __instancecheck__(self, instance):
1125 # Since we extend ABC.__subclasscheck__ and
1126 # ABC.__instancecheck__ inlines the cache checking done by the
1127 # latter, we must extend __instancecheck__ too. For simplicity
1128 # we just skip the cache check -- instance checks for generic
1129 # classes are supposed to be rare anyways.
Guido van Rossumb47c9d22016-10-03 08:40:50 -07001130 return issubclass(instance.__class__, self)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001131
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001132
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001133# Prevent checks for Generic to crash when defining Generic.
1134Generic = None
1135
1136
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001137class Generic(metaclass=GenericMeta):
1138 """Abstract base class for generic types.
1139
1140 A generic type is typically declared by inheriting from an
1141 instantiation of this class with one or more type variables.
1142 For example, a generic mapping type might be defined as::
1143
1144 class Mapping(Generic[KT, VT]):
1145 def __getitem__(self, key: KT) -> VT:
1146 ...
1147 # Etc.
1148
1149 This class can then be used as follows::
1150
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001151 def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001152 try:
1153 return mapping[key]
1154 except KeyError:
1155 return default
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001156 """
1157
Guido van Rossumd70fe632015-08-05 12:11:06 +02001158 __slots__ = ()
1159
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001160 def __new__(cls, *args, **kwds):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001161 if cls.__origin__ is None:
1162 return cls.__next_in_mro__.__new__(cls)
1163 else:
1164 origin = _gorg(cls)
1165 obj = cls.__next_in_mro__.__new__(origin)
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001166 try:
1167 obj.__orig_class__ = cls
1168 except AttributeError:
1169 pass
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001170 obj.__init__(*args, **kwds)
1171 return obj
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001172
1173
Guido van Rossum4cefe742016-09-27 15:20:12 -07001174class _ClassVar(_FinalTypingBase, _root=True):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001175 """Special type construct to mark class variables.
1176
1177 An annotation wrapped in ClassVar indicates that a given
1178 attribute is intended to be used as a class variable and
1179 should not be set on instances of that class. Usage::
1180
1181 class Starship:
1182 stats: ClassVar[Dict[str, int]] = {} # class variable
1183 damage: int = 10 # instance variable
1184
1185 ClassVar accepts only types and cannot be further subscribed.
1186
1187 Note that ClassVar is not a class itself, and should not
1188 be used with isinstance() or issubclass().
1189 """
1190
Guido van Rossum4cefe742016-09-27 15:20:12 -07001191 __slots__ = ('__type__',)
1192
1193 def __init__(self, tp=None, **kwds):
1194 self.__type__ = tp
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001195
1196 def __getitem__(self, item):
1197 cls = type(self)
1198 if self.__type__ is None:
1199 return cls(_type_check(item,
Guido van Rossum4cefe742016-09-27 15:20:12 -07001200 '{} accepts only single type.'.format(cls.__name__[1:])),
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001201 _root=True)
1202 raise TypeError('{} cannot be further subscripted'
1203 .format(cls.__name__[1:]))
1204
1205 def _eval_type(self, globalns, localns):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001206 new_tp = _eval_type(self.__type__, globalns, localns)
1207 if new_tp == self.__type__:
1208 return self
1209 return type(self)(new_tp, _root=True)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001210
1211 def _get_type_vars(self, tvars):
1212 if self.__type__:
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001213 _get_type_vars([self.__type__], tvars)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001214
1215 def __repr__(self):
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001216 return self._subs_repr([], [])
1217
1218 def _subs_repr(self, tvars, args):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001219 r = super().__repr__()
1220 if self.__type__ is not None:
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001221 r += '[{}]'.format(_replace_arg(self.__type__, tvars, args))
Guido van Rossum4cefe742016-09-27 15:20:12 -07001222 return r
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001223
1224 def __hash__(self):
1225 return hash((type(self).__name__, self.__type__))
1226
1227 def __eq__(self, other):
1228 if not isinstance(other, _ClassVar):
1229 return NotImplemented
1230 if self.__type__ is not None:
1231 return self.__type__ == other.__type__
1232 return self is other
1233
1234ClassVar = _ClassVar(_root=True)
1235
1236
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001237def cast(typ, val):
1238 """Cast a value to a type.
1239
1240 This returns the value unchanged. To the type checker this
1241 signals that the return value has the designated type, but at
1242 runtime we intentionally don't check anything (we want this
1243 to be as fast as possible).
1244 """
1245 return val
1246
1247
1248def _get_defaults(func):
1249 """Internal helper to extract the default arguments, by name."""
1250 code = func.__code__
1251 pos_count = code.co_argcount
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001252 arg_names = code.co_varnames
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001253 arg_names = arg_names[:pos_count]
1254 defaults = func.__defaults__ or ()
1255 kwdefaults = func.__kwdefaults__
1256 res = dict(kwdefaults) if kwdefaults else {}
1257 pos_offset = pos_count - len(defaults)
1258 for name, value in zip(arg_names[pos_offset:], defaults):
1259 assert name not in res
1260 res[name] = value
1261 return res
1262
1263
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001264if sys.version_info[:2] >= (3, 3):
1265 def get_type_hints(obj, globalns=None, localns=None):
1266 """Return type hints for an object.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001267
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001268 This is often the same as obj.__annotations__, but it handles
1269 forward references encoded as string literals, and if necessary
1270 adds Optional[t] if a default value equal to None is set.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001271
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001272 The argument may be a module, class, method, or function. The annotations
1273 are returned as a dictionary, or in the case of a class, a ChainMap of
1274 dictionaries.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001275
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001276 TypeError is raised if the argument is not of a type that can contain
1277 annotations, and an empty dictionary is returned if no annotations are
1278 present.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001279
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001280 BEWARE -- the behavior of globalns and localns is counterintuitive
1281 (unless you are familiar with how eval() and exec() work). The
1282 search order is locals first, then globals.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001283
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001284 - If no dict arguments are passed, an attempt is made to use the
1285 globals from obj, and these are also used as the locals. If the
1286 object does not appear to have globals, an exception is raised.
1287
1288 - If one dict argument is passed, it is used for both globals and
1289 locals.
1290
1291 - If two dict arguments are passed, they specify globals and
1292 locals, respectively.
1293 """
1294
1295 if getattr(obj, '__no_type_check__', None):
1296 return {}
1297 if globalns is None:
1298 globalns = getattr(obj, '__globals__', {})
1299 if localns is None:
1300 localns = globalns
1301 elif localns is None:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001302 localns = globalns
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001303
1304 if (isinstance(obj, types.FunctionType) or
1305 isinstance(obj, types.BuiltinFunctionType) or
1306 isinstance(obj, types.MethodType)):
1307 defaults = _get_defaults(obj)
1308 hints = obj.__annotations__
1309 for name, value in hints.items():
1310 if value is None:
1311 value = type(None)
1312 if isinstance(value, str):
1313 value = _ForwardRef(value)
1314 value = _eval_type(value, globalns, localns)
1315 if name in defaults and defaults[name] is None:
1316 value = Optional[value]
1317 hints[name] = value
1318 return hints
1319
1320 if isinstance(obj, types.ModuleType):
1321 try:
1322 hints = obj.__annotations__
1323 except AttributeError:
1324 return {}
1325 # we keep only those annotations that can be accessed on module
1326 members = obj.__dict__
1327 hints = {name: value for name, value in hints.items()
1328 if name in members}
1329 for name, value in hints.items():
1330 if value is None:
1331 value = type(None)
1332 if isinstance(value, str):
1333 value = _ForwardRef(value)
1334 value = _eval_type(value, globalns, localns)
1335 hints[name] = value
1336 return hints
1337
1338 if isinstance(object, type):
1339 cmap = None
1340 for base in reversed(obj.__mro__):
1341 new_map = collections.ChainMap if cmap is None else cmap.new_child
1342 try:
1343 hints = base.__dict__['__annotations__']
1344 except KeyError:
1345 cmap = new_map()
1346 else:
1347 for name, value in hints.items():
1348 if value is None:
1349 value = type(None)
1350 if isinstance(value, str):
1351 value = _ForwardRef(value)
1352 value = _eval_type(value, globalns, localns)
1353 hints[name] = value
1354 cmap = new_map(hints)
1355 return cmap
1356
1357 raise TypeError('{!r} is not a module, class, method, '
1358 'or function.'.format(obj))
1359
1360else:
1361 def get_type_hints(obj, globalns=None, localns=None):
1362 """Return type hints for a function or method object.
1363
1364 This is often the same as obj.__annotations__, but it handles
1365 forward references encoded as string literals, and if necessary
1366 adds Optional[t] if a default value equal to None is set.
1367
1368 BEWARE -- the behavior of globalns and localns is counterintuitive
1369 (unless you are familiar with how eval() and exec() work). The
1370 search order is locals first, then globals.
1371
1372 - If no dict arguments are passed, an attempt is made to use the
1373 globals from obj, and these are also used as the locals. If the
1374 object does not appear to have globals, an exception is raised.
1375
1376 - If one dict argument is passed, it is used for both globals and
1377 locals.
1378
1379 - If two dict arguments are passed, they specify globals and
1380 locals, respectively.
1381 """
1382 if getattr(obj, '__no_type_check__', None):
1383 return {}
1384 if globalns is None:
1385 globalns = getattr(obj, '__globals__', {})
1386 if localns is None:
1387 localns = globalns
1388 elif localns is None:
1389 localns = globalns
1390 defaults = _get_defaults(obj)
1391 hints = dict(obj.__annotations__)
1392 for name, value in hints.items():
1393 if isinstance(value, str):
1394 value = _ForwardRef(value)
1395 value = _eval_type(value, globalns, localns)
1396 if name in defaults and defaults[name] is None:
1397 value = Optional[value]
1398 hints[name] = value
1399 return hints
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001400
1401
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001402def no_type_check(arg):
1403 """Decorator to indicate that annotations are not type hints.
1404
1405 The argument must be a class or function; if it is a class, it
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001406 applies recursively to all methods and classes defined in that class
1407 (but not to methods defined in its superclasses or subclasses).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001408
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001409 This mutates the function(s) or class(es) in place.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001410 """
1411 if isinstance(arg, type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001412 arg_attrs = arg.__dict__.copy()
1413 for attr, val in arg.__dict__.items():
1414 if val in arg.__bases__:
1415 arg_attrs.pop(attr)
1416 for obj in arg_attrs.values():
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001417 if isinstance(obj, types.FunctionType):
1418 obj.__no_type_check__ = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001419 if isinstance(obj, type):
1420 no_type_check(obj)
1421 try:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001422 arg.__no_type_check__ = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001423 except TypeError: # built-in classes
1424 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001425 return arg
1426
1427
1428def no_type_check_decorator(decorator):
1429 """Decorator to give another decorator the @no_type_check effect.
1430
1431 This wraps the decorator with something that wraps the decorated
1432 function in @no_type_check.
1433 """
1434
1435 @functools.wraps(decorator)
1436 def wrapped_decorator(*args, **kwds):
1437 func = decorator(*args, **kwds)
1438 func = no_type_check(func)
1439 return func
1440
1441 return wrapped_decorator
1442
1443
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001444def _overload_dummy(*args, **kwds):
1445 """Helper for @overload to raise when called."""
1446 raise NotImplementedError(
1447 "You should not call an overloaded function. "
1448 "A series of @overload-decorated functions "
1449 "outside a stub module should always be followed "
1450 "by an implementation that is not @overload-ed.")
1451
1452
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001453def overload(func):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001454 """Decorator for overloaded functions/methods.
1455
1456 In a stub file, place two or more stub definitions for the same
1457 function in a row, each decorated with @overload. For example:
1458
1459 @overload
1460 def utf8(value: None) -> None: ...
1461 @overload
1462 def utf8(value: bytes) -> bytes: ...
1463 @overload
1464 def utf8(value: str) -> bytes: ...
1465
1466 In a non-stub file (i.e. a regular .py file), do the same but
1467 follow it with an implementation. The implementation should *not*
1468 be decorated with @overload. For example:
1469
1470 @overload
1471 def utf8(value: None) -> None: ...
1472 @overload
1473 def utf8(value: bytes) -> bytes: ...
1474 @overload
1475 def utf8(value: str) -> bytes: ...
1476 def utf8(value):
1477 # implementation goes here
1478 """
1479 return _overload_dummy
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001480
1481
1482class _ProtocolMeta(GenericMeta):
1483 """Internal metaclass for _Protocol.
1484
1485 This exists so _Protocol classes can be generic without deriving
1486 from Generic.
1487 """
1488
Guido van Rossumd70fe632015-08-05 12:11:06 +02001489 def __instancecheck__(self, obj):
1490 raise TypeError("Protocols cannot be used with isinstance().")
1491
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001492 def __subclasscheck__(self, cls):
1493 if not self._is_protocol:
1494 # No structural checks since this isn't a protocol.
1495 return NotImplemented
1496
1497 if self is _Protocol:
1498 # Every class is a subclass of the empty protocol.
1499 return True
1500
1501 # Find all attributes defined in the protocol.
1502 attrs = self._get_protocol_attrs()
1503
1504 for attr in attrs:
1505 if not any(attr in d.__dict__ for d in cls.__mro__):
1506 return False
1507 return True
1508
1509 def _get_protocol_attrs(self):
1510 # Get all Protocol base classes.
1511 protocol_bases = []
1512 for c in self.__mro__:
1513 if getattr(c, '_is_protocol', False) and c.__name__ != '_Protocol':
1514 protocol_bases.append(c)
1515
1516 # Get attributes included in protocol.
1517 attrs = set()
1518 for base in protocol_bases:
1519 for attr in base.__dict__.keys():
1520 # Include attributes not defined in any non-protocol bases.
1521 for c in self.__mro__:
1522 if (c is not base and attr in c.__dict__ and
1523 not getattr(c, '_is_protocol', False)):
1524 break
1525 else:
1526 if (not attr.startswith('_abc_') and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001527 attr != '__abstractmethods__' and
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001528 attr != '__annotations__' and
1529 attr != '__weakref__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001530 attr != '_is_protocol' and
1531 attr != '__dict__' and
1532 attr != '__args__' and
1533 attr != '__slots__' and
1534 attr != '_get_protocol_attrs' and
1535 attr != '__next_in_mro__' and
1536 attr != '__parameters__' and
1537 attr != '__origin__' and
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001538 attr != '__orig_bases__' and
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001539 attr != '__extra__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001540 attr != '__module__'):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001541 attrs.add(attr)
1542
1543 return attrs
1544
1545
1546class _Protocol(metaclass=_ProtocolMeta):
1547 """Internal base class for protocol classes.
1548
1549 This implements a simple-minded structural isinstance check
1550 (similar but more general than the one-offs in collections.abc
1551 such as Hashable).
1552 """
1553
Guido van Rossumd70fe632015-08-05 12:11:06 +02001554 __slots__ = ()
1555
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001556 _is_protocol = True
1557
1558
1559# Various ABCs mimicking those in collections.abc.
1560# A few are simply re-exported for completeness.
1561
1562Hashable = collections_abc.Hashable # Not generic.
1563
1564
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001565if hasattr(collections_abc, 'Awaitable'):
1566 class Awaitable(Generic[T_co], extra=collections_abc.Awaitable):
1567 __slots__ = ()
1568else:
1569 Awaitable = None
Guido van Rossumf17c2002015-12-03 17:31:24 -08001570
1571
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001572if hasattr(collections_abc, 'AsyncIterable'):
Guido van Rossumf17c2002015-12-03 17:31:24 -08001573
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001574 class AsyncIterable(Generic[T_co], extra=collections_abc.AsyncIterable):
1575 __slots__ = ()
Guido van Rossumf17c2002015-12-03 17:31:24 -08001576
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001577 class AsyncIterator(AsyncIterable[T_co],
1578 extra=collections_abc.AsyncIterator):
1579 __slots__ = ()
1580
1581else:
1582 AsyncIterable = None
1583 AsyncIterator = None
Guido van Rossumf17c2002015-12-03 17:31:24 -08001584
1585
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001586class Iterable(Generic[T_co], extra=collections_abc.Iterable):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001587 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001588
1589
1590class Iterator(Iterable[T_co], extra=collections_abc.Iterator):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001591 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001592
1593
1594class SupportsInt(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001595 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001596
1597 @abstractmethod
1598 def __int__(self) -> int:
1599 pass
1600
1601
1602class SupportsFloat(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001603 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001604
1605 @abstractmethod
1606 def __float__(self) -> float:
1607 pass
1608
1609
1610class SupportsComplex(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001611 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001612
1613 @abstractmethod
1614 def __complex__(self) -> complex:
1615 pass
1616
1617
1618class SupportsBytes(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001619 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001620
1621 @abstractmethod
1622 def __bytes__(self) -> bytes:
1623 pass
1624
1625
Guido van Rossumd70fe632015-08-05 12:11:06 +02001626class SupportsAbs(_Protocol[T_co]):
1627 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001628
1629 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001630 def __abs__(self) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001631 pass
1632
1633
Guido van Rossumd70fe632015-08-05 12:11:06 +02001634class SupportsRound(_Protocol[T_co]):
1635 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001636
1637 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001638 def __round__(self, ndigits: int = 0) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001639 pass
1640
1641
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001642if hasattr(collections_abc, 'Reversible'):
1643 class Reversible(Iterable[T_co], extra=collections_abc.Reversible):
1644 __slots__ = ()
1645else:
1646 class Reversible(_Protocol[T_co]):
1647 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001648
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001649 @abstractmethod
1650 def __reversed__(self) -> 'Iterator[T_co]':
1651 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001652
1653
1654Sized = collections_abc.Sized # Not generic.
1655
1656
1657class Container(Generic[T_co], extra=collections_abc.Container):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001658 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001659
1660
Guido van Rossumefa798d2016-08-23 11:01:50 -07001661if hasattr(collections_abc, 'Collection'):
1662 class Collection(Sized, Iterable[T_co], Container[T_co],
1663 extra=collections_abc.Collection):
1664 __slots__ = ()
1665
1666 __all__.append('Collection')
1667
1668
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001669# Callable was defined earlier.
1670
Guido van Rossumefa798d2016-08-23 11:01:50 -07001671if hasattr(collections_abc, 'Collection'):
1672 class AbstractSet(Collection[T_co],
1673 extra=collections_abc.Set):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001674 __slots__ = ()
Guido van Rossumefa798d2016-08-23 11:01:50 -07001675else:
1676 class AbstractSet(Sized, Iterable[T_co], Container[T_co],
1677 extra=collections_abc.Set):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001678 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001679
1680
1681class MutableSet(AbstractSet[T], extra=collections_abc.MutableSet):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001682 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001683
1684
Guido van Rossumefa798d2016-08-23 11:01:50 -07001685# NOTE: It is only covariant in the value type.
1686if hasattr(collections_abc, 'Collection'):
1687 class Mapping(Collection[KT], Generic[KT, VT_co],
1688 extra=collections_abc.Mapping):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001689 __slots__ = ()
Guido van Rossumefa798d2016-08-23 11:01:50 -07001690else:
1691 class Mapping(Sized, Iterable[KT], Container[KT], Generic[KT, VT_co],
1692 extra=collections_abc.Mapping):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001693 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001694
1695
1696class MutableMapping(Mapping[KT, VT], extra=collections_abc.MutableMapping):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001697 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001698
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001699if hasattr(collections_abc, 'Reversible'):
Guido van Rossumefa798d2016-08-23 11:01:50 -07001700 if hasattr(collections_abc, 'Collection'):
1701 class Sequence(Reversible[T_co], Collection[T_co],
1702 extra=collections_abc.Sequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001703 __slots__ = ()
Guido van Rossumefa798d2016-08-23 11:01:50 -07001704 else:
1705 class Sequence(Sized, Reversible[T_co], Container[T_co],
1706 extra=collections_abc.Sequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001707 __slots__ = ()
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001708else:
1709 class Sequence(Sized, Iterable[T_co], Container[T_co],
1710 extra=collections_abc.Sequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001711 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001712
1713
1714class MutableSequence(Sequence[T], extra=collections_abc.MutableSequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001715 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001716
1717
1718class ByteString(Sequence[int], extra=collections_abc.ByteString):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001719 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001720
1721
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001722class List(list, MutableSequence[T], extra=list):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001723
Guido van Rossum4cefe742016-09-27 15:20:12 -07001724 __slots__ = ()
1725
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001726 def __new__(cls, *args, **kwds):
1727 if _geqv(cls, List):
1728 raise TypeError("Type List cannot be instantiated; "
1729 "use list() instead")
1730 return list.__new__(cls, *args, **kwds)
1731
1732
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001733class Set(set, MutableSet[T], extra=set):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001734
Guido van Rossum4cefe742016-09-27 15:20:12 -07001735 __slots__ = ()
1736
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001737 def __new__(cls, *args, **kwds):
1738 if _geqv(cls, Set):
1739 raise TypeError("Type Set cannot be instantiated; "
1740 "use set() instead")
1741 return set.__new__(cls, *args, **kwds)
1742
1743
Guido van Rossum4cefe742016-09-27 15:20:12 -07001744class FrozenSet(frozenset, AbstractSet[T_co], extra=frozenset):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001745 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001746
1747 def __new__(cls, *args, **kwds):
1748 if _geqv(cls, FrozenSet):
1749 raise TypeError("Type FrozenSet cannot be instantiated; "
1750 "use frozenset() instead")
1751 return frozenset.__new__(cls, *args, **kwds)
1752
1753
1754class MappingView(Sized, Iterable[T_co], extra=collections_abc.MappingView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001755 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001756
1757
Guido van Rossumd70fe632015-08-05 12:11:06 +02001758class KeysView(MappingView[KT], AbstractSet[KT],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001759 extra=collections_abc.KeysView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001760 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001761
1762
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001763class ItemsView(MappingView[Tuple[KT, VT_co]],
Guido van Rossum0e0563c2016-04-05 14:54:25 -07001764 AbstractSet[Tuple[KT, VT_co]],
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001765 Generic[KT, VT_co],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001766 extra=collections_abc.ItemsView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001767 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001768
1769
1770class ValuesView(MappingView[VT_co], extra=collections_abc.ValuesView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001771 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001772
1773
Brett Cannonf3ad0422016-04-15 10:51:30 -07001774if hasattr(contextlib, 'AbstractContextManager'):
1775 class ContextManager(Generic[T_co], extra=contextlib.AbstractContextManager):
1776 __slots__ = ()
1777 __all__.append('ContextManager')
1778
1779
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001780class Dict(dict, MutableMapping[KT, VT], extra=dict):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001781
Guido van Rossum4cefe742016-09-27 15:20:12 -07001782 __slots__ = ()
1783
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001784 def __new__(cls, *args, **kwds):
1785 if _geqv(cls, Dict):
1786 raise TypeError("Type Dict cannot be instantiated; "
1787 "use dict() instead")
1788 return dict.__new__(cls, *args, **kwds)
1789
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001790class DefaultDict(collections.defaultdict, MutableMapping[KT, VT],
1791 extra=collections.defaultdict):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001792
Guido van Rossum4cefe742016-09-27 15:20:12 -07001793 __slots__ = ()
1794
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001795 def __new__(cls, *args, **kwds):
1796 if _geqv(cls, DefaultDict):
1797 raise TypeError("Type DefaultDict cannot be instantiated; "
1798 "use collections.defaultdict() instead")
1799 return collections.defaultdict.__new__(cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001800
1801# Determine what base class to use for Generator.
1802if hasattr(collections_abc, 'Generator'):
1803 # Sufficiently recent versions of 3.5 have a Generator ABC.
1804 _G_base = collections_abc.Generator
1805else:
1806 # Fall back on the exact type.
1807 _G_base = types.GeneratorType
1808
1809
1810class Generator(Iterator[T_co], Generic[T_co, T_contra, V_co],
1811 extra=_G_base):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001812 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001813
1814 def __new__(cls, *args, **kwds):
1815 if _geqv(cls, Generator):
1816 raise TypeError("Type Generator cannot be instantiated; "
1817 "create a subclass instead")
1818 return super().__new__(cls, *args, **kwds)
1819
1820
Guido van Rossumeb9aca32016-05-24 16:38:22 -07001821# Internal type variable used for Type[].
Guido van Rossumefa798d2016-08-23 11:01:50 -07001822CT_co = TypeVar('CT_co', covariant=True, bound=type)
Guido van Rossumeb9aca32016-05-24 16:38:22 -07001823
1824
Guido van Rossumb22c7082016-05-26 09:56:19 -07001825# This is not a real generic class. Don't use outside annotations.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001826class Type(Generic[CT_co], extra=type):
Guido van Rossumb22c7082016-05-26 09:56:19 -07001827 """A special construct usable to annotate class objects.
Guido van Rossumeb9aca32016-05-24 16:38:22 -07001828
1829 For example, suppose we have the following classes::
1830
1831 class User: ... # Abstract base for User classes
1832 class BasicUser(User): ...
1833 class ProUser(User): ...
1834 class TeamUser(User): ...
1835
1836 And a function that takes a class argument that's a subclass of
1837 User and returns an instance of the corresponding class::
1838
1839 U = TypeVar('U', bound=User)
1840 def new_user(user_class: Type[U]) -> U:
1841 user = user_class()
1842 # (Here we could write the user object to a database)
1843 return user
1844
1845 joe = new_user(BasicUser)
1846
1847 At this point the type checker knows that joe has type BasicUser.
1848 """
1849
Guido van Rossum4cefe742016-09-27 15:20:12 -07001850 __slots__ = ()
1851
Guido van Rossumeb9aca32016-05-24 16:38:22 -07001852
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001853def _make_nmtuple(name, types):
1854 nm_tpl = collections.namedtuple(name, [n for n, t in types])
1855 nm_tpl._field_types = dict(types)
Guido van Rossum557d1eb2015-11-19 08:16:31 -08001856 try:
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001857 nm_tpl.__module__ = sys._getframe(2).f_globals.get('__name__', '__main__')
Guido van Rossum557d1eb2015-11-19 08:16:31 -08001858 except (AttributeError, ValueError):
1859 pass
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001860 return nm_tpl
1861
1862
1863if sys.version_info[:2] >= (3, 6):
1864 class NamedTupleMeta(type):
1865
1866 def __new__(cls, typename, bases, ns, *, _root=False):
1867 if _root:
1868 return super().__new__(cls, typename, bases, ns)
1869 types = ns.get('__annotations__', {})
1870 return _make_nmtuple(typename, types.items())
1871
1872 class NamedTuple(metaclass=NamedTupleMeta, _root=True):
1873 """Typed version of namedtuple.
1874
1875 Usage::
1876
1877 class Employee(NamedTuple):
1878 name: str
1879 id: int
1880
1881 This is equivalent to::
1882
1883 Employee = collections.namedtuple('Employee', ['name', 'id'])
1884
1885 The resulting class has one extra attribute: _field_types,
1886 giving a dict mapping field names to types. (The field names
1887 are in the _fields attribute, which is part of the namedtuple
1888 API.) Backward-compatible usage::
1889
1890 Employee = NamedTuple('Employee', [('name', str), ('id', int)])
1891 """
1892
1893 def __new__(self, typename, fields):
1894 return _make_nmtuple(typename, fields)
1895else:
1896 def NamedTuple(typename, fields):
1897 """Typed version of namedtuple.
1898
1899 Usage::
1900
1901 Employee = typing.NamedTuple('Employee', [('name', str), 'id', int)])
1902
1903 This is equivalent to::
1904
1905 Employee = collections.namedtuple('Employee', ['name', 'id'])
1906
1907 The resulting class has one extra attribute: _field_types,
1908 giving a dict mapping field names to types. (The field names
1909 are in the _fields attribute, which is part of the namedtuple
1910 API.)
1911 """
1912 return _make_nmtuple(typename, fields)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001913
1914
Guido van Rossum91185fe2016-06-08 11:19:11 -07001915def NewType(name, tp):
1916 """NewType creates simple unique types with almost zero
1917 runtime overhead. NewType(name, tp) is considered a subtype of tp
1918 by static type checkers. At runtime, NewType(name, tp) returns
1919 a dummy function that simply returns its argument. Usage::
1920
1921 UserId = NewType('UserId', int)
1922
1923 def name_by_id(user_id: UserId) -> str:
1924 ...
1925
1926 UserId('user') # Fails type check
1927
1928 name_by_id(42) # Fails type check
1929 name_by_id(UserId(42)) # OK
1930
1931 num = UserId(5) + 1 # type: int
1932 """
1933
1934 def new_type(x):
1935 return x
1936
1937 new_type.__name__ = name
1938 new_type.__supertype__ = tp
1939 return new_type
1940
1941
Guido van Rossum0e0563c2016-04-05 14:54:25 -07001942# Python-version-specific alias (Python 2: unicode; Python 3: str)
1943Text = str
1944
1945
Guido van Rossum91185fe2016-06-08 11:19:11 -07001946# Constant that's True when type checking, but False here.
1947TYPE_CHECKING = False
1948
1949
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001950class IO(Generic[AnyStr]):
1951 """Generic base class for TextIO and BinaryIO.
1952
1953 This is an abstract, generic version of the return of open().
1954
1955 NOTE: This does not distinguish between the different possible
1956 classes (text vs. binary, read vs. write vs. read/write,
1957 append-only, unbuffered). The TextIO and BinaryIO subclasses
1958 below capture the distinctions between text vs. binary, which is
1959 pervasive in the interface; however we currently do not offer a
1960 way to track the other distinctions in the type system.
1961 """
1962
Guido van Rossumd70fe632015-08-05 12:11:06 +02001963 __slots__ = ()
1964
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001965 @abstractproperty
1966 def mode(self) -> str:
1967 pass
1968
1969 @abstractproperty
1970 def name(self) -> str:
1971 pass
1972
1973 @abstractmethod
1974 def close(self) -> None:
1975 pass
1976
1977 @abstractmethod
1978 def closed(self) -> bool:
1979 pass
1980
1981 @abstractmethod
1982 def fileno(self) -> int:
1983 pass
1984
1985 @abstractmethod
1986 def flush(self) -> None:
1987 pass
1988
1989 @abstractmethod
1990 def isatty(self) -> bool:
1991 pass
1992
1993 @abstractmethod
1994 def read(self, n: int = -1) -> AnyStr:
1995 pass
1996
1997 @abstractmethod
1998 def readable(self) -> bool:
1999 pass
2000
2001 @abstractmethod
2002 def readline(self, limit: int = -1) -> AnyStr:
2003 pass
2004
2005 @abstractmethod
2006 def readlines(self, hint: int = -1) -> List[AnyStr]:
2007 pass
2008
2009 @abstractmethod
2010 def seek(self, offset: int, whence: int = 0) -> int:
2011 pass
2012
2013 @abstractmethod
2014 def seekable(self) -> bool:
2015 pass
2016
2017 @abstractmethod
2018 def tell(self) -> int:
2019 pass
2020
2021 @abstractmethod
2022 def truncate(self, size: int = None) -> int:
2023 pass
2024
2025 @abstractmethod
2026 def writable(self) -> bool:
2027 pass
2028
2029 @abstractmethod
2030 def write(self, s: AnyStr) -> int:
2031 pass
2032
2033 @abstractmethod
2034 def writelines(self, lines: List[AnyStr]) -> None:
2035 pass
2036
2037 @abstractmethod
2038 def __enter__(self) -> 'IO[AnyStr]':
2039 pass
2040
2041 @abstractmethod
2042 def __exit__(self, type, value, traceback) -> None:
2043 pass
2044
2045
2046class BinaryIO(IO[bytes]):
2047 """Typed version of the return of open() in binary mode."""
2048
Guido van Rossumd70fe632015-08-05 12:11:06 +02002049 __slots__ = ()
2050
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002051 @abstractmethod
2052 def write(self, s: Union[bytes, bytearray]) -> int:
2053 pass
2054
2055 @abstractmethod
2056 def __enter__(self) -> 'BinaryIO':
2057 pass
2058
2059
2060class TextIO(IO[str]):
2061 """Typed version of the return of open() in text mode."""
2062
Guido van Rossumd70fe632015-08-05 12:11:06 +02002063 __slots__ = ()
2064
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002065 @abstractproperty
2066 def buffer(self) -> BinaryIO:
2067 pass
2068
2069 @abstractproperty
2070 def encoding(self) -> str:
2071 pass
2072
2073 @abstractproperty
2074 def errors(self) -> str:
2075 pass
2076
2077 @abstractproperty
2078 def line_buffering(self) -> bool:
2079 pass
2080
2081 @abstractproperty
2082 def newlines(self) -> Any:
2083 pass
2084
2085 @abstractmethod
2086 def __enter__(self) -> 'TextIO':
2087 pass
2088
2089
2090class io:
2091 """Wrapper namespace for IO generic classes."""
2092
2093 __all__ = ['IO', 'TextIO', 'BinaryIO']
2094 IO = IO
2095 TextIO = TextIO
2096 BinaryIO = BinaryIO
2097
2098io.__name__ = __name__ + '.io'
2099sys.modules[io.__name__] = io
2100
2101
2102Pattern = _TypeAlias('Pattern', AnyStr, type(stdlib_re.compile('')),
2103 lambda p: p.pattern)
2104Match = _TypeAlias('Match', AnyStr, type(stdlib_re.match('', '')),
2105 lambda m: m.re.pattern)
2106
2107
2108class re:
2109 """Wrapper namespace for re type aliases."""
2110
2111 __all__ = ['Pattern', 'Match']
2112 Pattern = Pattern
2113 Match = Match
2114
2115re.__name__ = __name__ + '.re'
2116sys.modules[re.__name__] = re