blob: 261da5d5e2fb109477a757c7561eb244cd98f0b7 [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):
Guido van Rossum9f91e852016-10-21 14:30:50 -0700896 for i, tvar in enumerate(tvars):
Guido van Rossum3b557992016-10-21 17:30:29 -0700897 if arg == tvar:
Guido van Rossum9f91e852016-10-21 14:30:50 -0700898 return args[i]
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700899 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 {}
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001325 for name, value in hints.items():
1326 if value is None:
1327 value = type(None)
1328 if isinstance(value, str):
1329 value = _ForwardRef(value)
1330 value = _eval_type(value, globalns, localns)
1331 hints[name] = value
1332 return hints
1333
1334 if isinstance(object, type):
1335 cmap = None
1336 for base in reversed(obj.__mro__):
1337 new_map = collections.ChainMap if cmap is None else cmap.new_child
1338 try:
1339 hints = base.__dict__['__annotations__']
1340 except KeyError:
1341 cmap = new_map()
1342 else:
1343 for name, value in hints.items():
1344 if value is None:
1345 value = type(None)
1346 if isinstance(value, str):
1347 value = _ForwardRef(value)
1348 value = _eval_type(value, globalns, localns)
1349 hints[name] = value
1350 cmap = new_map(hints)
1351 return cmap
1352
1353 raise TypeError('{!r} is not a module, class, method, '
1354 'or function.'.format(obj))
1355
1356else:
1357 def get_type_hints(obj, globalns=None, localns=None):
1358 """Return type hints for a function or method object.
1359
1360 This is often the same as obj.__annotations__, but it handles
1361 forward references encoded as string literals, and if necessary
1362 adds Optional[t] if a default value equal to None is set.
1363
1364 BEWARE -- the behavior of globalns and localns is counterintuitive
1365 (unless you are familiar with how eval() and exec() work). The
1366 search order is locals first, then globals.
1367
1368 - If no dict arguments are passed, an attempt is made to use the
1369 globals from obj, and these are also used as the locals. If the
1370 object does not appear to have globals, an exception is raised.
1371
1372 - If one dict argument is passed, it is used for both globals and
1373 locals.
1374
1375 - If two dict arguments are passed, they specify globals and
1376 locals, respectively.
1377 """
1378 if getattr(obj, '__no_type_check__', None):
1379 return {}
1380 if globalns is None:
1381 globalns = getattr(obj, '__globals__', {})
1382 if localns is None:
1383 localns = globalns
1384 elif localns is None:
1385 localns = globalns
1386 defaults = _get_defaults(obj)
1387 hints = dict(obj.__annotations__)
1388 for name, value in hints.items():
1389 if isinstance(value, str):
1390 value = _ForwardRef(value)
1391 value = _eval_type(value, globalns, localns)
1392 if name in defaults and defaults[name] is None:
1393 value = Optional[value]
1394 hints[name] = value
1395 return hints
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001396
1397
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001398def no_type_check(arg):
1399 """Decorator to indicate that annotations are not type hints.
1400
1401 The argument must be a class or function; if it is a class, it
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001402 applies recursively to all methods and classes defined in that class
1403 (but not to methods defined in its superclasses or subclasses).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001404
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001405 This mutates the function(s) or class(es) in place.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001406 """
1407 if isinstance(arg, type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001408 arg_attrs = arg.__dict__.copy()
1409 for attr, val in arg.__dict__.items():
1410 if val in arg.__bases__:
1411 arg_attrs.pop(attr)
1412 for obj in arg_attrs.values():
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001413 if isinstance(obj, types.FunctionType):
1414 obj.__no_type_check__ = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001415 if isinstance(obj, type):
1416 no_type_check(obj)
1417 try:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001418 arg.__no_type_check__ = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001419 except TypeError: # built-in classes
1420 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001421 return arg
1422
1423
1424def no_type_check_decorator(decorator):
1425 """Decorator to give another decorator the @no_type_check effect.
1426
1427 This wraps the decorator with something that wraps the decorated
1428 function in @no_type_check.
1429 """
1430
1431 @functools.wraps(decorator)
1432 def wrapped_decorator(*args, **kwds):
1433 func = decorator(*args, **kwds)
1434 func = no_type_check(func)
1435 return func
1436
1437 return wrapped_decorator
1438
1439
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001440def _overload_dummy(*args, **kwds):
1441 """Helper for @overload to raise when called."""
1442 raise NotImplementedError(
1443 "You should not call an overloaded function. "
1444 "A series of @overload-decorated functions "
1445 "outside a stub module should always be followed "
1446 "by an implementation that is not @overload-ed.")
1447
1448
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001449def overload(func):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001450 """Decorator for overloaded functions/methods.
1451
1452 In a stub file, place two or more stub definitions for the same
1453 function in a row, each decorated with @overload. For example:
1454
1455 @overload
1456 def utf8(value: None) -> None: ...
1457 @overload
1458 def utf8(value: bytes) -> bytes: ...
1459 @overload
1460 def utf8(value: str) -> bytes: ...
1461
1462 In a non-stub file (i.e. a regular .py file), do the same but
1463 follow it with an implementation. The implementation should *not*
1464 be decorated with @overload. For example:
1465
1466 @overload
1467 def utf8(value: None) -> None: ...
1468 @overload
1469 def utf8(value: bytes) -> bytes: ...
1470 @overload
1471 def utf8(value: str) -> bytes: ...
1472 def utf8(value):
1473 # implementation goes here
1474 """
1475 return _overload_dummy
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001476
1477
1478class _ProtocolMeta(GenericMeta):
1479 """Internal metaclass for _Protocol.
1480
1481 This exists so _Protocol classes can be generic without deriving
1482 from Generic.
1483 """
1484
Guido van Rossumd70fe632015-08-05 12:11:06 +02001485 def __instancecheck__(self, obj):
1486 raise TypeError("Protocols cannot be used with isinstance().")
1487
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001488 def __subclasscheck__(self, cls):
1489 if not self._is_protocol:
1490 # No structural checks since this isn't a protocol.
1491 return NotImplemented
1492
1493 if self is _Protocol:
1494 # Every class is a subclass of the empty protocol.
1495 return True
1496
1497 # Find all attributes defined in the protocol.
1498 attrs = self._get_protocol_attrs()
1499
1500 for attr in attrs:
1501 if not any(attr in d.__dict__ for d in cls.__mro__):
1502 return False
1503 return True
1504
1505 def _get_protocol_attrs(self):
1506 # Get all Protocol base classes.
1507 protocol_bases = []
1508 for c in self.__mro__:
1509 if getattr(c, '_is_protocol', False) and c.__name__ != '_Protocol':
1510 protocol_bases.append(c)
1511
1512 # Get attributes included in protocol.
1513 attrs = set()
1514 for base in protocol_bases:
1515 for attr in base.__dict__.keys():
1516 # Include attributes not defined in any non-protocol bases.
1517 for c in self.__mro__:
1518 if (c is not base and attr in c.__dict__ and
1519 not getattr(c, '_is_protocol', False)):
1520 break
1521 else:
1522 if (not attr.startswith('_abc_') and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001523 attr != '__abstractmethods__' and
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001524 attr != '__annotations__' and
1525 attr != '__weakref__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001526 attr != '_is_protocol' and
1527 attr != '__dict__' and
1528 attr != '__args__' and
1529 attr != '__slots__' and
1530 attr != '_get_protocol_attrs' and
1531 attr != '__next_in_mro__' and
1532 attr != '__parameters__' and
1533 attr != '__origin__' and
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001534 attr != '__orig_bases__' and
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001535 attr != '__extra__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001536 attr != '__module__'):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001537 attrs.add(attr)
1538
1539 return attrs
1540
1541
1542class _Protocol(metaclass=_ProtocolMeta):
1543 """Internal base class for protocol classes.
1544
1545 This implements a simple-minded structural isinstance check
1546 (similar but more general than the one-offs in collections.abc
1547 such as Hashable).
1548 """
1549
Guido van Rossumd70fe632015-08-05 12:11:06 +02001550 __slots__ = ()
1551
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001552 _is_protocol = True
1553
1554
1555# Various ABCs mimicking those in collections.abc.
1556# A few are simply re-exported for completeness.
1557
1558Hashable = collections_abc.Hashable # Not generic.
1559
1560
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001561if hasattr(collections_abc, 'Awaitable'):
1562 class Awaitable(Generic[T_co], extra=collections_abc.Awaitable):
1563 __slots__ = ()
1564else:
1565 Awaitable = None
Guido van Rossumf17c2002015-12-03 17:31:24 -08001566
1567
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001568if hasattr(collections_abc, 'AsyncIterable'):
Guido van Rossumf17c2002015-12-03 17:31:24 -08001569
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001570 class AsyncIterable(Generic[T_co], extra=collections_abc.AsyncIterable):
1571 __slots__ = ()
Guido van Rossumf17c2002015-12-03 17:31:24 -08001572
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001573 class AsyncIterator(AsyncIterable[T_co],
1574 extra=collections_abc.AsyncIterator):
1575 __slots__ = ()
1576
1577else:
1578 AsyncIterable = None
1579 AsyncIterator = None
Guido van Rossumf17c2002015-12-03 17:31:24 -08001580
1581
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001582class Iterable(Generic[T_co], extra=collections_abc.Iterable):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001583 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001584
1585
1586class Iterator(Iterable[T_co], extra=collections_abc.Iterator):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001587 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001588
1589
1590class SupportsInt(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001591 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001592
1593 @abstractmethod
1594 def __int__(self) -> int:
1595 pass
1596
1597
1598class SupportsFloat(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001599 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001600
1601 @abstractmethod
1602 def __float__(self) -> float:
1603 pass
1604
1605
1606class SupportsComplex(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001607 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001608
1609 @abstractmethod
1610 def __complex__(self) -> complex:
1611 pass
1612
1613
1614class SupportsBytes(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001615 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001616
1617 @abstractmethod
1618 def __bytes__(self) -> bytes:
1619 pass
1620
1621
Guido van Rossumd70fe632015-08-05 12:11:06 +02001622class SupportsAbs(_Protocol[T_co]):
1623 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001624
1625 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001626 def __abs__(self) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001627 pass
1628
1629
Guido van Rossumd70fe632015-08-05 12:11:06 +02001630class SupportsRound(_Protocol[T_co]):
1631 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001632
1633 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001634 def __round__(self, ndigits: int = 0) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001635 pass
1636
1637
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001638if hasattr(collections_abc, 'Reversible'):
1639 class Reversible(Iterable[T_co], extra=collections_abc.Reversible):
1640 __slots__ = ()
1641else:
1642 class Reversible(_Protocol[T_co]):
1643 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001644
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001645 @abstractmethod
1646 def __reversed__(self) -> 'Iterator[T_co]':
1647 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001648
1649
1650Sized = collections_abc.Sized # Not generic.
1651
1652
1653class Container(Generic[T_co], extra=collections_abc.Container):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001654 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001655
1656
Guido van Rossumefa798d2016-08-23 11:01:50 -07001657if hasattr(collections_abc, 'Collection'):
1658 class Collection(Sized, Iterable[T_co], Container[T_co],
1659 extra=collections_abc.Collection):
1660 __slots__ = ()
1661
1662 __all__.append('Collection')
1663
1664
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001665# Callable was defined earlier.
1666
Guido van Rossumefa798d2016-08-23 11:01:50 -07001667if hasattr(collections_abc, 'Collection'):
1668 class AbstractSet(Collection[T_co],
1669 extra=collections_abc.Set):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001670 __slots__ = ()
Guido van Rossumefa798d2016-08-23 11:01:50 -07001671else:
1672 class AbstractSet(Sized, Iterable[T_co], Container[T_co],
1673 extra=collections_abc.Set):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001674 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001675
1676
1677class MutableSet(AbstractSet[T], extra=collections_abc.MutableSet):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001678 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001679
1680
Guido van Rossumefa798d2016-08-23 11:01:50 -07001681# NOTE: It is only covariant in the value type.
1682if hasattr(collections_abc, 'Collection'):
1683 class Mapping(Collection[KT], Generic[KT, VT_co],
1684 extra=collections_abc.Mapping):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001685 __slots__ = ()
Guido van Rossumefa798d2016-08-23 11:01:50 -07001686else:
1687 class Mapping(Sized, Iterable[KT], Container[KT], Generic[KT, VT_co],
1688 extra=collections_abc.Mapping):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001689 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001690
1691
1692class MutableMapping(Mapping[KT, VT], extra=collections_abc.MutableMapping):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001693 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001694
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001695if hasattr(collections_abc, 'Reversible'):
Guido van Rossumefa798d2016-08-23 11:01:50 -07001696 if hasattr(collections_abc, 'Collection'):
1697 class Sequence(Reversible[T_co], Collection[T_co],
1698 extra=collections_abc.Sequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001699 __slots__ = ()
Guido van Rossumefa798d2016-08-23 11:01:50 -07001700 else:
1701 class Sequence(Sized, Reversible[T_co], Container[T_co],
1702 extra=collections_abc.Sequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001703 __slots__ = ()
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001704else:
1705 class Sequence(Sized, Iterable[T_co], Container[T_co],
1706 extra=collections_abc.Sequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001707 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001708
1709
1710class MutableSequence(Sequence[T], extra=collections_abc.MutableSequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001711 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001712
1713
1714class ByteString(Sequence[int], extra=collections_abc.ByteString):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001715 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001716
1717
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001718class List(list, MutableSequence[T], extra=list):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001719
Guido van Rossum4cefe742016-09-27 15:20:12 -07001720 __slots__ = ()
1721
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001722 def __new__(cls, *args, **kwds):
1723 if _geqv(cls, List):
1724 raise TypeError("Type List cannot be instantiated; "
1725 "use list() instead")
1726 return list.__new__(cls, *args, **kwds)
1727
1728
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001729class Set(set, MutableSet[T], extra=set):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001730
Guido van Rossum4cefe742016-09-27 15:20:12 -07001731 __slots__ = ()
1732
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001733 def __new__(cls, *args, **kwds):
1734 if _geqv(cls, Set):
1735 raise TypeError("Type Set cannot be instantiated; "
1736 "use set() instead")
1737 return set.__new__(cls, *args, **kwds)
1738
1739
Guido van Rossum4cefe742016-09-27 15:20:12 -07001740class FrozenSet(frozenset, AbstractSet[T_co], extra=frozenset):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001741 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001742
1743 def __new__(cls, *args, **kwds):
1744 if _geqv(cls, FrozenSet):
1745 raise TypeError("Type FrozenSet cannot be instantiated; "
1746 "use frozenset() instead")
1747 return frozenset.__new__(cls, *args, **kwds)
1748
1749
1750class MappingView(Sized, Iterable[T_co], extra=collections_abc.MappingView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001751 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001752
1753
Guido van Rossumd70fe632015-08-05 12:11:06 +02001754class KeysView(MappingView[KT], AbstractSet[KT],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001755 extra=collections_abc.KeysView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001756 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001757
1758
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001759class ItemsView(MappingView[Tuple[KT, VT_co]],
Guido van Rossum0e0563c2016-04-05 14:54:25 -07001760 AbstractSet[Tuple[KT, VT_co]],
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001761 Generic[KT, VT_co],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001762 extra=collections_abc.ItemsView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001763 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001764
1765
1766class ValuesView(MappingView[VT_co], extra=collections_abc.ValuesView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001767 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001768
1769
Brett Cannonf3ad0422016-04-15 10:51:30 -07001770if hasattr(contextlib, 'AbstractContextManager'):
1771 class ContextManager(Generic[T_co], extra=contextlib.AbstractContextManager):
1772 __slots__ = ()
1773 __all__.append('ContextManager')
1774
1775
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001776class Dict(dict, MutableMapping[KT, VT], extra=dict):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001777
Guido van Rossum4cefe742016-09-27 15:20:12 -07001778 __slots__ = ()
1779
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001780 def __new__(cls, *args, **kwds):
1781 if _geqv(cls, Dict):
1782 raise TypeError("Type Dict cannot be instantiated; "
1783 "use dict() instead")
1784 return dict.__new__(cls, *args, **kwds)
1785
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001786class DefaultDict(collections.defaultdict, MutableMapping[KT, VT],
1787 extra=collections.defaultdict):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001788
Guido van Rossum4cefe742016-09-27 15:20:12 -07001789 __slots__ = ()
1790
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001791 def __new__(cls, *args, **kwds):
1792 if _geqv(cls, DefaultDict):
1793 raise TypeError("Type DefaultDict cannot be instantiated; "
1794 "use collections.defaultdict() instead")
1795 return collections.defaultdict.__new__(cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001796
1797# Determine what base class to use for Generator.
1798if hasattr(collections_abc, 'Generator'):
1799 # Sufficiently recent versions of 3.5 have a Generator ABC.
1800 _G_base = collections_abc.Generator
1801else:
1802 # Fall back on the exact type.
1803 _G_base = types.GeneratorType
1804
1805
1806class Generator(Iterator[T_co], Generic[T_co, T_contra, V_co],
1807 extra=_G_base):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001808 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001809
1810 def __new__(cls, *args, **kwds):
1811 if _geqv(cls, Generator):
1812 raise TypeError("Type Generator cannot be instantiated; "
1813 "create a subclass instead")
1814 return super().__new__(cls, *args, **kwds)
1815
1816
Guido van Rossumeb9aca32016-05-24 16:38:22 -07001817# Internal type variable used for Type[].
Guido van Rossumefa798d2016-08-23 11:01:50 -07001818CT_co = TypeVar('CT_co', covariant=True, bound=type)
Guido van Rossumeb9aca32016-05-24 16:38:22 -07001819
1820
Guido van Rossumb22c7082016-05-26 09:56:19 -07001821# This is not a real generic class. Don't use outside annotations.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001822class Type(Generic[CT_co], extra=type):
Guido van Rossumb22c7082016-05-26 09:56:19 -07001823 """A special construct usable to annotate class objects.
Guido van Rossumeb9aca32016-05-24 16:38:22 -07001824
1825 For example, suppose we have the following classes::
1826
1827 class User: ... # Abstract base for User classes
1828 class BasicUser(User): ...
1829 class ProUser(User): ...
1830 class TeamUser(User): ...
1831
1832 And a function that takes a class argument that's a subclass of
1833 User and returns an instance of the corresponding class::
1834
1835 U = TypeVar('U', bound=User)
1836 def new_user(user_class: Type[U]) -> U:
1837 user = user_class()
1838 # (Here we could write the user object to a database)
1839 return user
1840
1841 joe = new_user(BasicUser)
1842
1843 At this point the type checker knows that joe has type BasicUser.
1844 """
1845
Guido van Rossum4cefe742016-09-27 15:20:12 -07001846 __slots__ = ()
1847
Guido van Rossumeb9aca32016-05-24 16:38:22 -07001848
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001849def _make_nmtuple(name, types):
1850 nm_tpl = collections.namedtuple(name, [n for n, t in types])
1851 nm_tpl._field_types = dict(types)
Guido van Rossum557d1eb2015-11-19 08:16:31 -08001852 try:
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001853 nm_tpl.__module__ = sys._getframe(2).f_globals.get('__name__', '__main__')
Guido van Rossum557d1eb2015-11-19 08:16:31 -08001854 except (AttributeError, ValueError):
1855 pass
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001856 return nm_tpl
1857
1858
1859if sys.version_info[:2] >= (3, 6):
1860 class NamedTupleMeta(type):
1861
1862 def __new__(cls, typename, bases, ns, *, _root=False):
1863 if _root:
1864 return super().__new__(cls, typename, bases, ns)
1865 types = ns.get('__annotations__', {})
1866 return _make_nmtuple(typename, types.items())
1867
1868 class NamedTuple(metaclass=NamedTupleMeta, _root=True):
1869 """Typed version of namedtuple.
1870
1871 Usage::
1872
1873 class Employee(NamedTuple):
1874 name: str
1875 id: int
1876
1877 This is equivalent to::
1878
1879 Employee = collections.namedtuple('Employee', ['name', 'id'])
1880
1881 The resulting class has one extra attribute: _field_types,
1882 giving a dict mapping field names to types. (The field names
1883 are in the _fields attribute, which is part of the namedtuple
1884 API.) Backward-compatible usage::
1885
1886 Employee = NamedTuple('Employee', [('name', str), ('id', int)])
1887 """
1888
1889 def __new__(self, typename, fields):
1890 return _make_nmtuple(typename, fields)
1891else:
1892 def NamedTuple(typename, fields):
1893 """Typed version of namedtuple.
1894
1895 Usage::
1896
1897 Employee = typing.NamedTuple('Employee', [('name', str), 'id', int)])
1898
1899 This is equivalent to::
1900
1901 Employee = collections.namedtuple('Employee', ['name', 'id'])
1902
1903 The resulting class has one extra attribute: _field_types,
1904 giving a dict mapping field names to types. (The field names
1905 are in the _fields attribute, which is part of the namedtuple
1906 API.)
1907 """
1908 return _make_nmtuple(typename, fields)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001909
1910
Guido van Rossum91185fe2016-06-08 11:19:11 -07001911def NewType(name, tp):
1912 """NewType creates simple unique types with almost zero
1913 runtime overhead. NewType(name, tp) is considered a subtype of tp
1914 by static type checkers. At runtime, NewType(name, tp) returns
1915 a dummy function that simply returns its argument. Usage::
1916
1917 UserId = NewType('UserId', int)
1918
1919 def name_by_id(user_id: UserId) -> str:
1920 ...
1921
1922 UserId('user') # Fails type check
1923
1924 name_by_id(42) # Fails type check
1925 name_by_id(UserId(42)) # OK
1926
1927 num = UserId(5) + 1 # type: int
1928 """
1929
1930 def new_type(x):
1931 return x
1932
1933 new_type.__name__ = name
1934 new_type.__supertype__ = tp
1935 return new_type
1936
1937
Guido van Rossum0e0563c2016-04-05 14:54:25 -07001938# Python-version-specific alias (Python 2: unicode; Python 3: str)
1939Text = str
1940
1941
Guido van Rossum91185fe2016-06-08 11:19:11 -07001942# Constant that's True when type checking, but False here.
1943TYPE_CHECKING = False
1944
1945
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001946class IO(Generic[AnyStr]):
1947 """Generic base class for TextIO and BinaryIO.
1948
1949 This is an abstract, generic version of the return of open().
1950
1951 NOTE: This does not distinguish between the different possible
1952 classes (text vs. binary, read vs. write vs. read/write,
1953 append-only, unbuffered). The TextIO and BinaryIO subclasses
1954 below capture the distinctions between text vs. binary, which is
1955 pervasive in the interface; however we currently do not offer a
1956 way to track the other distinctions in the type system.
1957 """
1958
Guido van Rossumd70fe632015-08-05 12:11:06 +02001959 __slots__ = ()
1960
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001961 @abstractproperty
1962 def mode(self) -> str:
1963 pass
1964
1965 @abstractproperty
1966 def name(self) -> str:
1967 pass
1968
1969 @abstractmethod
1970 def close(self) -> None:
1971 pass
1972
1973 @abstractmethod
1974 def closed(self) -> bool:
1975 pass
1976
1977 @abstractmethod
1978 def fileno(self) -> int:
1979 pass
1980
1981 @abstractmethod
1982 def flush(self) -> None:
1983 pass
1984
1985 @abstractmethod
1986 def isatty(self) -> bool:
1987 pass
1988
1989 @abstractmethod
1990 def read(self, n: int = -1) -> AnyStr:
1991 pass
1992
1993 @abstractmethod
1994 def readable(self) -> bool:
1995 pass
1996
1997 @abstractmethod
1998 def readline(self, limit: int = -1) -> AnyStr:
1999 pass
2000
2001 @abstractmethod
2002 def readlines(self, hint: int = -1) -> List[AnyStr]:
2003 pass
2004
2005 @abstractmethod
2006 def seek(self, offset: int, whence: int = 0) -> int:
2007 pass
2008
2009 @abstractmethod
2010 def seekable(self) -> bool:
2011 pass
2012
2013 @abstractmethod
2014 def tell(self) -> int:
2015 pass
2016
2017 @abstractmethod
2018 def truncate(self, size: int = None) -> int:
2019 pass
2020
2021 @abstractmethod
2022 def writable(self) -> bool:
2023 pass
2024
2025 @abstractmethod
2026 def write(self, s: AnyStr) -> int:
2027 pass
2028
2029 @abstractmethod
2030 def writelines(self, lines: List[AnyStr]) -> None:
2031 pass
2032
2033 @abstractmethod
2034 def __enter__(self) -> 'IO[AnyStr]':
2035 pass
2036
2037 @abstractmethod
2038 def __exit__(self, type, value, traceback) -> None:
2039 pass
2040
2041
2042class BinaryIO(IO[bytes]):
2043 """Typed version of the return of open() in binary mode."""
2044
Guido van Rossumd70fe632015-08-05 12:11:06 +02002045 __slots__ = ()
2046
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002047 @abstractmethod
2048 def write(self, s: Union[bytes, bytearray]) -> int:
2049 pass
2050
2051 @abstractmethod
2052 def __enter__(self) -> 'BinaryIO':
2053 pass
2054
2055
2056class TextIO(IO[str]):
2057 """Typed version of the return of open() in text mode."""
2058
Guido van Rossumd70fe632015-08-05 12:11:06 +02002059 __slots__ = ()
2060
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002061 @abstractproperty
2062 def buffer(self) -> BinaryIO:
2063 pass
2064
2065 @abstractproperty
2066 def encoding(self) -> str:
2067 pass
2068
2069 @abstractproperty
2070 def errors(self) -> str:
2071 pass
2072
2073 @abstractproperty
2074 def line_buffering(self) -> bool:
2075 pass
2076
2077 @abstractproperty
2078 def newlines(self) -> Any:
2079 pass
2080
2081 @abstractmethod
2082 def __enter__(self) -> 'TextIO':
2083 pass
2084
2085
2086class io:
2087 """Wrapper namespace for IO generic classes."""
2088
2089 __all__ = ['IO', 'TextIO', 'BinaryIO']
2090 IO = IO
2091 TextIO = TextIO
2092 BinaryIO = BinaryIO
2093
2094io.__name__ = __name__ + '.io'
2095sys.modules[io.__name__] = io
2096
2097
2098Pattern = _TypeAlias('Pattern', AnyStr, type(stdlib_re.compile('')),
2099 lambda p: p.pattern)
2100Match = _TypeAlias('Match', AnyStr, type(stdlib_re.match('', '')),
2101 lambda m: m.re.pattern)
2102
2103
2104class re:
2105 """Wrapper namespace for re type aliases."""
2106
2107 __all__ = ['Pattern', 'Match']
2108 Pattern = Pattern
2109 Match = Match
2110
2111re.__name__ = __name__ + '.re'
2112sys.modules[re.__name__] = re