blob: 645bc6f8ae0eddf9dc835f245c330b00ebb85c2c [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.
Ivan Levkivskyib692dc82017-02-13 22:50:14 +010013try:
Ivan Levkivskyif06e0212017-05-02 19:14:07 +020014 from types import WrapperDescriptorType, MethodWrapperType, MethodDescriptorType
Ivan Levkivskyib692dc82017-02-13 22:50:14 +010015except ImportError:
Ivan Levkivskyif06e0212017-05-02 19:14:07 +020016 WrapperDescriptorType = type(object.__init__)
Ivan Levkivskyib692dc82017-02-13 22:50:14 +010017 MethodWrapperType = type(object().__str__)
18 MethodDescriptorType = type(str.join)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070019
20
21# Please keep __all__ alphabetized within each category.
22__all__ = [
23 # Super-special typing primitives.
24 'Any',
25 'Callable',
Guido van Rossum0a6976d2016-09-11 15:34:56 -070026 'ClassVar',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070027 'Generic',
28 'Optional',
Guido van Rossumeb9aca32016-05-24 16:38:22 -070029 'Tuple',
30 'Type',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070031 'TypeVar',
32 'Union',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070033
34 # ABCs (from collections.abc).
35 'AbstractSet', # collections.abc.Set.
Guido van Rossum83ec3022017-01-17 20:43:28 -080036 'GenericMeta', # subclass of abc.ABCMeta and a metaclass
37 # for 'Generic' and ABCs below.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070038 'ByteString',
39 'Container',
40 'Hashable',
41 'ItemsView',
42 'Iterable',
43 'Iterator',
44 'KeysView',
45 'Mapping',
46 'MappingView',
47 'MutableMapping',
48 'MutableSequence',
49 'MutableSet',
50 'Sequence',
51 'Sized',
52 'ValuesView',
Guido van Rossum62fe1bb2016-10-29 16:05:26 -070053 # The following are added depending on presence
54 # of their non-generic counterparts in stdlib:
55 # Awaitable,
56 # AsyncIterator,
57 # AsyncIterable,
58 # Coroutine,
59 # Collection,
Guido van Rossume9ed5602017-01-18 13:10:31 -080060 # ContextManager,
61 # AsyncGenerator,
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070062
63 # Structural checks, a.k.a. protocols.
64 'Reversible',
65 'SupportsAbs',
Ivan Levkivskyif06e0212017-05-02 19:14:07 +020066 'SupportsBytes',
67 'SupportsComplex',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070068 'SupportsFloat',
69 'SupportsInt',
70 'SupportsRound',
71
72 # Concrete collection types.
Ivan Levkivskyib692dc82017-02-13 22:50:14 +010073 'Counter',
Raymond Hettinger80490522017-01-16 22:42:37 -080074 'Deque',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070075 'Dict',
Guido van Rossumbd5b9a02016-04-05 08:28:52 -070076 'DefaultDict',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070077 'List',
78 'Set',
Guido van Rossumefa798d2016-08-23 11:01:50 -070079 'FrozenSet',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070080 'NamedTuple', # Not really a type.
81 'Generator',
82
83 # One-off things.
84 'AnyStr',
85 'cast',
86 'get_type_hints',
Guido van Rossum91185fe2016-06-08 11:19:11 -070087 'NewType',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070088 'no_type_check',
89 'no_type_check_decorator',
90 'overload',
Guido van Rossum0e0563c2016-04-05 14:54:25 -070091 'Text',
Guido van Rossum91185fe2016-06-08 11:19:11 -070092 'TYPE_CHECKING',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070093]
94
Guido van Rossumbd5b9a02016-04-05 08:28:52 -070095# The pseudo-submodules 're' and 'io' are part of the public
96# namespace, but excluded from __all__ because they might stomp on
97# legitimate imports of those modules.
98
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070099
100def _qualname(x):
101 if sys.version_info[:2] >= (3, 3):
102 return x.__qualname__
103 else:
104 # Fall back to just name.
105 return x.__name__
106
107
Guido van Rossum4cefe742016-09-27 15:20:12 -0700108def _trim_name(nm):
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800109 whitelist = ('_TypeAlias', '_ForwardRef', '_TypingBase', '_FinalTypingBase')
110 if nm.startswith('_') and nm not in whitelist:
Guido van Rossum4cefe742016-09-27 15:20:12 -0700111 nm = nm[1:]
112 return nm
113
114
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700115class TypingMeta(type):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800116 """Metaclass for most types defined in typing module
117 (not a part of public API).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700118
119 This overrides __new__() to require an extra keyword parameter
120 '_root', which serves as a guard against naive subclassing of the
121 typing classes. Any legitimate class defined using a metaclass
Guido van Rossumb24569a2016-11-20 18:01:29 -0800122 derived from TypingMeta must pass _root=True.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700123
Guido van Rossumb24569a2016-11-20 18:01:29 -0800124 This also defines a dummy constructor (all the work for most typing
125 constructs is done in __new__) and a nicer repr().
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700126 """
127
128 _is_protocol = False
129
130 def __new__(cls, name, bases, namespace, *, _root=False):
131 if not _root:
132 raise TypeError("Cannot subclass %s" %
133 (', '.join(map(_type_repr, bases)) or '()'))
134 return super().__new__(cls, name, bases, namespace)
135
136 def __init__(self, *args, **kwds):
137 pass
138
139 def _eval_type(self, globalns, localns):
140 """Override this in subclasses to interpret forward references.
141
Guido van Rossumb24569a2016-11-20 18:01:29 -0800142 For example, List['C'] is internally stored as
143 List[_ForwardRef('C')], which should evaluate to List[C],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700144 where C is an object found in globalns or localns (searching
145 localns first, of course).
146 """
147 return self
148
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700149 def _get_type_vars(self, tvars):
150 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700151
152 def __repr__(self):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700153 qname = _trim_name(_qualname(self))
154 return '%s.%s' % (self.__module__, qname)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700155
156
Guido van Rossum4cefe742016-09-27 15:20:12 -0700157class _TypingBase(metaclass=TypingMeta, _root=True):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800158 """Internal indicator of special typing constructs."""
Guido van Rossum4cefe742016-09-27 15:20:12 -0700159
Guido van Rossum83ec3022017-01-17 20:43:28 -0800160 __slots__ = ('__weakref__',)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700161
Guido van Rossum4cefe742016-09-27 15:20:12 -0700162 def __init__(self, *args, **kwds):
163 pass
164
165 def __new__(cls, *args, **kwds):
166 """Constructor.
167
168 This only exists to give a better error message in case
169 someone tries to subclass a special typing object (not a good idea).
170 """
171 if (len(args) == 3 and
172 isinstance(args[0], str) and
173 isinstance(args[1], tuple)):
174 # Close enough.
175 raise TypeError("Cannot subclass %r" % cls)
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700176 return super().__new__(cls)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700177
178 # Things that are not classes also need these.
179 def _eval_type(self, globalns, localns):
180 return self
181
182 def _get_type_vars(self, tvars):
183 pass
184
185 def __repr__(self):
186 cls = type(self)
187 qname = _trim_name(_qualname(cls))
188 return '%s.%s' % (cls.__module__, qname)
189
190 def __call__(self, *args, **kwds):
191 raise TypeError("Cannot instantiate %r" % type(self))
192
193
194class _FinalTypingBase(_TypingBase, _root=True):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800195 """Internal mix-in class to prevent instantiation.
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700196
197 Prevents instantiation unless _root=True is given in class call.
Guido van Rossumb24569a2016-11-20 18:01:29 -0800198 It is used to create pseudo-singleton instances Any, Union, Optional, etc.
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700199 """
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700200
Guido van Rossumd70fe632015-08-05 12:11:06 +0200201 __slots__ = ()
202
Guido van Rossum4cefe742016-09-27 15:20:12 -0700203 def __new__(cls, *args, _root=False, **kwds):
204 self = super().__new__(cls, *args, **kwds)
205 if _root is True:
206 return self
207 raise TypeError("Cannot instantiate %r" % cls)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700208
Guido van Rossumb7dedc82016-10-29 12:44:29 -0700209 def __reduce__(self):
210 return _trim_name(type(self).__name__)
211
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700212
Guido van Rossum4cefe742016-09-27 15:20:12 -0700213class _ForwardRef(_TypingBase, _root=True):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800214 """Internal wrapper to hold a forward reference."""
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700215
Guido van Rossum4cefe742016-09-27 15:20:12 -0700216 __slots__ = ('__forward_arg__', '__forward_code__',
Guido van Rossumc7b92952016-11-10 08:24:06 -0800217 '__forward_evaluated__', '__forward_value__')
Guido van Rossum4cefe742016-09-27 15:20:12 -0700218
219 def __init__(self, arg):
220 super().__init__(arg)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700221 if not isinstance(arg, str):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800222 raise TypeError('Forward reference must be a string -- got %r' % (arg,))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700223 try:
224 code = compile(arg, '<string>', 'eval')
225 except SyntaxError:
Guido van Rossumb24569a2016-11-20 18:01:29 -0800226 raise SyntaxError('Forward reference must be an expression -- got %r' %
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700227 (arg,))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700228 self.__forward_arg__ = arg
229 self.__forward_code__ = code
230 self.__forward_evaluated__ = False
231 self.__forward_value__ = None
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700232
233 def _eval_type(self, globalns, localns):
Guido van Rossumdad17902016-11-10 08:29:18 -0800234 if not self.__forward_evaluated__ or localns is not globalns:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700235 if globalns is None and localns is None:
236 globalns = localns = {}
237 elif globalns is None:
238 globalns = localns
239 elif localns is None:
240 localns = globalns
241 self.__forward_value__ = _type_check(
242 eval(self.__forward_code__, globalns, localns),
243 "Forward references must evaluate to types.")
244 self.__forward_evaluated__ = True
245 return self.__forward_value__
246
Guido van Rossum4cefe742016-09-27 15:20:12 -0700247 def __eq__(self, other):
248 if not isinstance(other, _ForwardRef):
249 return NotImplemented
250 return (self.__forward_arg__ == other.__forward_arg__ and
Guido van Rossumc7b92952016-11-10 08:24:06 -0800251 self.__forward_value__ == other.__forward_value__)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700252
253 def __hash__(self):
Guido van Rossumc7b92952016-11-10 08:24:06 -0800254 return hash((self.__forward_arg__, self.__forward_value__))
Guido van Rossum4cefe742016-09-27 15:20:12 -0700255
Guido van Rossumd70fe632015-08-05 12:11:06 +0200256 def __instancecheck__(self, obj):
257 raise TypeError("Forward references cannot be used with isinstance().")
258
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700259 def __subclasscheck__(self, cls):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700260 raise TypeError("Forward references cannot be used with issubclass().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700261
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700262 def __repr__(self):
263 return '_ForwardRef(%r)' % (self.__forward_arg__,)
264
265
Guido van Rossum4cefe742016-09-27 15:20:12 -0700266class _TypeAlias(_TypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700267 """Internal helper class for defining generic variants of concrete types.
268
Guido van Rossum4cefe742016-09-27 15:20:12 -0700269 Note that this is not a type; let's call it a pseudo-type. It cannot
270 be used in instance and subclass checks in parameterized form, i.e.
271 ``isinstance(42, Match[str])`` raises ``TypeError`` instead of returning
272 ``False``.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700273 """
274
Guido van Rossumd70fe632015-08-05 12:11:06 +0200275 __slots__ = ('name', 'type_var', 'impl_type', 'type_checker')
276
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700277 def __init__(self, name, type_var, impl_type, type_checker):
278 """Initializer.
279
280 Args:
281 name: The name, e.g. 'Pattern'.
282 type_var: The type parameter, e.g. AnyStr, or the
283 specific type, e.g. str.
284 impl_type: The implementation type.
285 type_checker: Function that takes an impl_type instance.
286 and returns a value that should be a type_var instance.
287 """
288 assert isinstance(name, str), repr(name)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700289 assert isinstance(impl_type, type), repr(impl_type)
290 assert not isinstance(impl_type, TypingMeta), repr(impl_type)
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700291 assert isinstance(type_var, (type, _TypingBase)), repr(type_var)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700292 self.name = name
293 self.type_var = type_var
294 self.impl_type = impl_type
295 self.type_checker = type_checker
296
297 def __repr__(self):
298 return "%s[%s]" % (self.name, _type_repr(self.type_var))
299
300 def __getitem__(self, parameter):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700301 if not isinstance(self.type_var, TypeVar):
302 raise TypeError("%s cannot be further parameterized." % self)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700303 if self.type_var.__constraints__ and isinstance(parameter, type):
304 if not issubclass(parameter, self.type_var.__constraints__):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700305 raise TypeError("%s is not a valid substitution for %s." %
306 (parameter, self.type_var))
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700307 if isinstance(parameter, TypeVar) and parameter is not self.type_var:
308 raise TypeError("%s cannot be re-parameterized." % self)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700309 return self.__class__(self.name, parameter,
310 self.impl_type, self.type_checker)
311
Guido van Rossum4cefe742016-09-27 15:20:12 -0700312 def __eq__(self, other):
313 if not isinstance(other, _TypeAlias):
314 return NotImplemented
315 return self.name == other.name and self.type_var == other.type_var
316
317 def __hash__(self):
318 return hash((self.name, self.type_var))
319
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700320 def __instancecheck__(self, obj):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700321 if not isinstance(self.type_var, TypeVar):
322 raise TypeError("Parameterized type aliases cannot be used "
323 "with isinstance().")
324 return isinstance(obj, self.impl_type)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700325
326 def __subclasscheck__(self, cls):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700327 if not isinstance(self.type_var, TypeVar):
328 raise TypeError("Parameterized type aliases cannot be used "
329 "with issubclass().")
330 return issubclass(cls, self.impl_type)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700331
332
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700333def _get_type_vars(types, tvars):
334 for t in types:
Guido van Rossum4cefe742016-09-27 15:20:12 -0700335 if isinstance(t, TypingMeta) or isinstance(t, _TypingBase):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700336 t._get_type_vars(tvars)
337
338
339def _type_vars(types):
340 tvars = []
341 _get_type_vars(types, tvars)
342 return tuple(tvars)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700343
344
345def _eval_type(t, globalns, localns):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700346 if isinstance(t, TypingMeta) or isinstance(t, _TypingBase):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700347 return t._eval_type(globalns, localns)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700348 return t
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700349
350
351def _type_check(arg, msg):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800352 """Check that the argument is a type, and return it (internal helper).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700353
354 As a special case, accept None and return type(None) instead.
355 Also, _TypeAlias instances (e.g. Match, Pattern) are acceptable.
356
357 The msg argument is a human-readable error message, e.g.
358
359 "Union[arg, ...]: arg should be a type."
360
361 We append the repr() of the actual value (truncated to 100 chars).
362 """
363 if arg is None:
364 return type(None)
365 if isinstance(arg, str):
366 arg = _ForwardRef(arg)
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800367 if (
368 isinstance(arg, _TypingBase) and type(arg).__name__ == '_ClassVar' or
369 not isinstance(arg, (type, _TypingBase)) and not callable(arg)
370 ):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700371 raise TypeError(msg + " Got %.100r." % (arg,))
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700372 # Bare Union etc. are not valid as type arguments
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800373 if (
374 type(arg).__name__ in ('_Union', '_Optional') and
375 not getattr(arg, '__origin__', None) or
376 isinstance(arg, TypingMeta) and _gorg(arg) in (Generic, _Protocol)
377 ):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700378 raise TypeError("Plain %s is not valid as type argument" % arg)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700379 return arg
380
381
382def _type_repr(obj):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800383 """Return the repr() of an object, special-casing types (internal helper).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700384
385 If obj is a type, we return a shorter version than the default
386 type.__repr__, based on the module and qualified name, which is
387 typically enough to uniquely identify a type. For everything
388 else, we fall back on repr(obj).
389 """
390 if isinstance(obj, type) and not isinstance(obj, TypingMeta):
391 if obj.__module__ == 'builtins':
392 return _qualname(obj)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700393 return '%s.%s' % (obj.__module__, _qualname(obj))
394 if obj is ...:
395 return('...')
396 if isinstance(obj, types.FunctionType):
397 return obj.__name__
398 return repr(obj)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700399
400
Guido van Rossum4cefe742016-09-27 15:20:12 -0700401class _Any(_FinalTypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700402 """Special type indicating an unconstrained type.
403
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700404 - Any is compatible with every type.
405 - Any assumed to have all methods.
406 - All values assumed to be instances of Any.
407
408 Note that all the above statements are true from the point of view of
409 static type checkers. At runtime, Any should not be used with instance
410 or class checks.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700411 """
412
Guido van Rossumd70fe632015-08-05 12:11:06 +0200413 __slots__ = ()
414
Guido van Rossum4cefe742016-09-27 15:20:12 -0700415 def __instancecheck__(self, obj):
416 raise TypeError("Any cannot be used with isinstance().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700417
Guido van Rossum4cefe742016-09-27 15:20:12 -0700418 def __subclasscheck__(self, cls):
419 raise TypeError("Any cannot be used with issubclass().")
420
421
422Any = _Any(_root=True)
423
424
Ivan Levkivskyif06e0212017-05-02 19:14:07 +0200425class _NoReturn(_FinalTypingBase, _root=True):
426 """Special type indicating functions that never return.
427 Example::
428
429 from typing import NoReturn
430
431 def stop() -> NoReturn:
432 raise Exception('no way')
433
434 This type is invalid in other positions, e.g., ``List[NoReturn]``
435 will fail in static type checkers.
436 """
437
438 __slots__ = ()
439
440 def __instancecheck__(self, obj):
441 raise TypeError("NoReturn cannot be used with isinstance().")
442
443 def __subclasscheck__(self, cls):
444 raise TypeError("NoReturn cannot be used with issubclass().")
445
446
447NoReturn = _NoReturn(_root=True)
448
449
Guido van Rossum4cefe742016-09-27 15:20:12 -0700450class TypeVar(_TypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700451 """Type variable.
452
453 Usage::
454
455 T = TypeVar('T') # Can be anything
456 A = TypeVar('A', str, bytes) # Must be str or bytes
457
458 Type variables exist primarily for the benefit of static type
459 checkers. They serve as the parameters for generic types as well
460 as for generic function definitions. See class Generic for more
461 information on generic types. Generic functions work as follows:
462
Guido van Rossumb24569a2016-11-20 18:01:29 -0800463 def repeat(x: T, n: int) -> List[T]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700464 '''Return a list containing n references to x.'''
465 return [x]*n
466
467 def longest(x: A, y: A) -> A:
468 '''Return the longest of two strings.'''
469 return x if len(x) >= len(y) else y
470
471 The latter example's signature is essentially the overloading
472 of (str, str) -> str and (bytes, bytes) -> bytes. Also note
473 that if the arguments are instances of some subclass of str,
474 the return type is still plain str.
475
Guido van Rossumb24569a2016-11-20 18:01:29 -0800476 At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700477
Guido van Rossumefa798d2016-08-23 11:01:50 -0700478 Type variables defined with covariant=True or contravariant=True
479 can be used do declare covariant or contravariant generic types.
480 See PEP 484 for more details. By default generic types are invariant
481 in all type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700482
483 Type variables can be introspected. e.g.:
484
485 T.__name__ == 'T'
486 T.__constraints__ == ()
487 T.__covariant__ == False
488 T.__contravariant__ = False
489 A.__constraints__ == (str, bytes)
490 """
491
Guido van Rossum4cefe742016-09-27 15:20:12 -0700492 __slots__ = ('__name__', '__bound__', '__constraints__',
493 '__covariant__', '__contravariant__')
494
495 def __init__(self, name, *constraints, bound=None,
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800496 covariant=False, contravariant=False):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700497 super().__init__(name, *constraints, bound=bound,
498 covariant=covariant, contravariant=contravariant)
499 self.__name__ = name
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700500 if covariant and contravariant:
Guido van Rossumefa798d2016-08-23 11:01:50 -0700501 raise ValueError("Bivariant types are not supported.")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700502 self.__covariant__ = bool(covariant)
503 self.__contravariant__ = bool(contravariant)
504 if constraints and bound is not None:
505 raise TypeError("Constraints cannot be combined with bound=...")
506 if constraints and len(constraints) == 1:
507 raise TypeError("A single constraint is not allowed")
508 msg = "TypeVar(name, constraint, ...): constraints must be types."
509 self.__constraints__ = tuple(_type_check(t, msg) for t in constraints)
510 if bound:
511 self.__bound__ = _type_check(bound, "Bound must be a type.")
512 else:
513 self.__bound__ = None
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700514
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700515 def _get_type_vars(self, tvars):
516 if self not in tvars:
517 tvars.append(self)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700518
519 def __repr__(self):
520 if self.__covariant__:
521 prefix = '+'
522 elif self.__contravariant__:
523 prefix = '-'
524 else:
525 prefix = '~'
526 return prefix + self.__name__
527
528 def __instancecheck__(self, instance):
529 raise TypeError("Type variables cannot be used with isinstance().")
530
531 def __subclasscheck__(self, cls):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700532 raise TypeError("Type variables cannot be used with issubclass().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700533
534
535# Some unconstrained type variables. These are used by the container types.
Guido van Rossumeb9aca32016-05-24 16:38:22 -0700536# (These are not for export.)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700537T = TypeVar('T') # Any type.
538KT = TypeVar('KT') # Key type.
539VT = TypeVar('VT') # Value type.
540T_co = TypeVar('T_co', covariant=True) # Any type covariant containers.
541V_co = TypeVar('V_co', covariant=True) # Any type covariant containers.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700542VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
543T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
544
545# A useful type variable with constraints. This represents string types.
Guido van Rossumeb9aca32016-05-24 16:38:22 -0700546# (This one *is* for export!)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700547AnyStr = TypeVar('AnyStr', bytes, str)
548
549
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700550def _replace_arg(arg, tvars, args):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800551 """An internal helper function: replace arg if it is a type variable
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700552 found in tvars with corresponding substitution from args or
553 with corresponding substitution sub-tree if arg is a generic type.
554 """
555
556 if tvars is None:
557 tvars = []
Guido van Rossum83ec3022017-01-17 20:43:28 -0800558 if hasattr(arg, '_subs_tree') and isinstance(arg, (GenericMeta, _TypingBase)):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700559 return arg._subs_tree(tvars, args)
560 if isinstance(arg, TypeVar):
561 for i, tvar in enumerate(tvars):
562 if arg == tvar:
563 return args[i]
564 return arg
565
566
Guido van Rossum83ec3022017-01-17 20:43:28 -0800567# Special typing constructs Union, Optional, Generic, Callable and Tuple
568# use three special attributes for internal bookkeeping of generic types:
569# * __parameters__ is a tuple of unique free type parameters of a generic
570# type, for example, Dict[T, T].__parameters__ == (T,);
571# * __origin__ keeps a reference to a type that was subscripted,
572# e.g., Union[T, int].__origin__ == Union;
573# * __args__ is a tuple of all arguments used in subscripting,
574# e.g., Dict[T, int].__args__ == (T, int).
575
576
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700577def _subs_tree(cls, tvars=None, args=None):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800578 """An internal helper function: calculate substitution tree
579 for generic cls after replacing its type parameters with
580 substitutions in tvars -> args (if any).
581 Repeat the same following __origin__'s.
582
583 Return a list of arguments with all possible substitutions
584 performed. Arguments that are generic classes themselves are represented
585 as tuples (so that no new classes are created by this function).
586 For example: _subs_tree(List[Tuple[int, T]][str]) == [(Tuple, int, str)]
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700587 """
588
589 if cls.__origin__ is None:
590 return cls
591 # Make of chain of origins (i.e. cls -> cls.__origin__)
592 current = cls.__origin__
593 orig_chain = []
594 while current.__origin__ is not None:
595 orig_chain.append(current)
596 current = current.__origin__
597 # Replace type variables in __args__ if asked ...
598 tree_args = []
599 for arg in cls.__args__:
600 tree_args.append(_replace_arg(arg, tvars, args))
601 # ... then continue replacing down the origin chain.
602 for ocls in orig_chain:
603 new_tree_args = []
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800604 for arg in ocls.__args__:
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700605 new_tree_args.append(_replace_arg(arg, ocls.__parameters__, tree_args))
606 tree_args = new_tree_args
607 return tree_args
608
609
610def _remove_dups_flatten(parameters):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800611 """An internal helper for Union creation and substitution: flatten Union's
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700612 among parameters, then remove duplicates and strict subclasses.
613 """
614
615 # Flatten out Union[Union[...], ...].
616 params = []
617 for p in parameters:
618 if isinstance(p, _Union) and p.__origin__ is Union:
619 params.extend(p.__args__)
620 elif isinstance(p, tuple) and len(p) > 0 and p[0] is Union:
621 params.extend(p[1:])
622 else:
623 params.append(p)
624 # Weed out strict duplicates, preserving the first of each occurrence.
625 all_params = set(params)
626 if len(all_params) < len(params):
627 new_params = []
628 for t in params:
629 if t in all_params:
630 new_params.append(t)
631 all_params.remove(t)
632 params = new_params
633 assert not all_params, all_params
634 # Weed out subclasses.
635 # E.g. Union[int, Employee, Manager] == Union[int, Employee].
636 # If object is present it will be sole survivor among proper classes.
637 # Never discard type variables.
638 # (In particular, Union[str, AnyStr] != AnyStr.)
639 all_params = set(params)
640 for t1 in params:
641 if not isinstance(t1, type):
642 continue
643 if any(isinstance(t2, type) and issubclass(t1, t2)
644 for t2 in all_params - {t1}
645 if not (isinstance(t2, GenericMeta) and
646 t2.__origin__ is not None)):
647 all_params.remove(t1)
648 return tuple(t for t in params if t in all_params)
649
650
651def _check_generic(cls, parameters):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800652 # Check correct count for parameters of a generic cls (internal helper).
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700653 if not cls.__parameters__:
654 raise TypeError("%s is not a generic class" % repr(cls))
655 alen = len(parameters)
656 elen = len(cls.__parameters__)
657 if alen != elen:
658 raise TypeError("Too %s parameters for %s; actual %s, expected %s" %
659 ("many" if alen > elen else "few", repr(cls), alen, elen))
660
661
Guido van Rossum9b107562016-11-09 13:23:04 -0800662_cleanups = []
663
664
Guido van Rossum4cefe742016-09-27 15:20:12 -0700665def _tp_cache(func):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800666 """Internal wrapper caching __getitem__ of generic types with a fallback to
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700667 original function for non-hashable arguments.
668 """
669
Guido van Rossum4cefe742016-09-27 15:20:12 -0700670 cached = functools.lru_cache()(func)
Guido van Rossum9b107562016-11-09 13:23:04 -0800671 _cleanups.append(cached.cache_clear)
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800672
Guido van Rossum4cefe742016-09-27 15:20:12 -0700673 @functools.wraps(func)
674 def inner(*args, **kwds):
675 try:
676 return cached(*args, **kwds)
677 except TypeError:
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700678 pass # All real errors (not unhashable args) are raised below.
Guido van Rossum4cefe742016-09-27 15:20:12 -0700679 return func(*args, **kwds)
680 return inner
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700681
682
Guido van Rossum4cefe742016-09-27 15:20:12 -0700683class _Union(_FinalTypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700684 """Union type; Union[X, Y] means either X or Y.
685
686 To define a union, use e.g. Union[int, str]. Details:
687
688 - The arguments must be types and there must be at least one.
689
690 - None as an argument is a special case and is replaced by
691 type(None).
692
693 - Unions of unions are flattened, e.g.::
694
695 Union[Union[int, str], float] == Union[int, str, float]
696
697 - Unions of a single argument vanish, e.g.::
698
699 Union[int] == int # The constructor actually returns int
700
701 - Redundant arguments are skipped, e.g.::
702
703 Union[int, str, int] == Union[int, str]
704
705 - When comparing unions, the argument order is ignored, e.g.::
706
707 Union[int, str] == Union[str, int]
708
709 - When two arguments have a subclass relationship, the least
710 derived argument is kept, e.g.::
711
712 class Employee: pass
713 class Manager(Employee): pass
714 Union[int, Employee, Manager] == Union[int, Employee]
715 Union[Manager, int, Employee] == Union[int, Employee]
716 Union[Employee, Manager] == Employee
717
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700718 - Similar for object::
719
720 Union[int, object] == object
721
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700722 - You cannot subclass or instantiate a union.
723
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700724 - You can use Optional[X] as a shorthand for Union[X, None].
725 """
726
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700727 __slots__ = ('__parameters__', '__args__', '__origin__', '__tree_hash__')
Guido van Rossum4cefe742016-09-27 15:20:12 -0700728
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700729 def __new__(cls, parameters=None, origin=None, *args, _root=False):
730 self = super().__new__(cls, parameters, origin, *args, _root=_root)
731 if origin is None:
732 self.__parameters__ = None
733 self.__args__ = None
734 self.__origin__ = None
735 self.__tree_hash__ = hash(frozenset(('Union',)))
Guido van Rossum4cefe742016-09-27 15:20:12 -0700736 return self
737 if not isinstance(parameters, tuple):
738 raise TypeError("Expected parameters=<tuple>")
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700739 if origin is Union:
740 parameters = _remove_dups_flatten(parameters)
741 # It's not a union if there's only one type left.
742 if len(parameters) == 1:
743 return parameters[0]
744 self.__parameters__ = _type_vars(parameters)
745 self.__args__ = parameters
746 self.__origin__ = origin
747 # Pre-calculate the __hash__ on instantiation.
748 # This improves speed for complex substitutions.
749 subs_tree = self._subs_tree()
750 if isinstance(subs_tree, tuple):
751 self.__tree_hash__ = hash(frozenset(subs_tree))
752 else:
753 self.__tree_hash__ = hash(subs_tree)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700754 return self
755
756 def _eval_type(self, globalns, localns):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700757 if self.__args__ is None:
Guido van Rossum4cefe742016-09-27 15:20:12 -0700758 return self
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700759 ev_args = tuple(_eval_type(t, globalns, localns) for t in self.__args__)
760 ev_origin = _eval_type(self.__origin__, globalns, localns)
761 if ev_args == self.__args__ and ev_origin == self.__origin__:
762 # Everything is already evaluated.
763 return self
764 return self.__class__(ev_args, ev_origin, _root=True)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700765
766 def _get_type_vars(self, tvars):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700767 if self.__origin__ and self.__parameters__:
768 _get_type_vars(self.__parameters__, tvars)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700769
770 def __repr__(self):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700771 if self.__origin__ is None:
772 return super().__repr__()
773 tree = self._subs_tree()
774 if not isinstance(tree, tuple):
775 return repr(tree)
776 return tree[0]._tree_repr(tree)
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700777
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700778 def _tree_repr(self, tree):
779 arg_list = []
780 for arg in tree[1:]:
781 if not isinstance(arg, tuple):
782 arg_list.append(_type_repr(arg))
783 else:
784 arg_list.append(arg[0]._tree_repr(arg))
785 return super().__repr__() + '[%s]' % ', '.join(arg_list)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700786
787 @_tp_cache
788 def __getitem__(self, parameters):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700789 if parameters == ():
790 raise TypeError("Cannot take a Union of no types.")
791 if not isinstance(parameters, tuple):
792 parameters = (parameters,)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700793 if self.__origin__ is None:
794 msg = "Union[arg, ...]: each arg must be a type."
795 else:
796 msg = "Parameters to generic types must be types."
797 parameters = tuple(_type_check(p, msg) for p in parameters)
798 if self is not Union:
799 _check_generic(self, parameters)
800 return self.__class__(parameters, origin=self, _root=True)
801
802 def _subs_tree(self, tvars=None, args=None):
803 if self is Union:
804 return Union # Nothing to substitute
805 tree_args = _subs_tree(self, tvars, args)
806 tree_args = _remove_dups_flatten(tree_args)
807 if len(tree_args) == 1:
808 return tree_args[0] # Union of a single type is that type
809 return (Union,) + tree_args
Guido van Rossum4cefe742016-09-27 15:20:12 -0700810
811 def __eq__(self, other):
Guido van Rossum83ec3022017-01-17 20:43:28 -0800812 if isinstance(other, _Union):
813 return self.__tree_hash__ == other.__tree_hash__
814 elif self is not Union:
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700815 return self._subs_tree() == other
Guido van Rossum83ec3022017-01-17 20:43:28 -0800816 else:
817 return self is other
Guido van Rossum4cefe742016-09-27 15:20:12 -0700818
819 def __hash__(self):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700820 return self.__tree_hash__
Guido van Rossum4cefe742016-09-27 15:20:12 -0700821
822 def __instancecheck__(self, obj):
823 raise TypeError("Unions cannot be used with isinstance().")
824
825 def __subclasscheck__(self, cls):
826 raise TypeError("Unions cannot be used with issubclass().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700827
828
Guido van Rossum4cefe742016-09-27 15:20:12 -0700829Union = _Union(_root=True)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700830
831
Guido van Rossum4cefe742016-09-27 15:20:12 -0700832class _Optional(_FinalTypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700833 """Optional type.
834
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700835 Optional[X] is equivalent to Union[X, None].
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700836 """
837
Guido van Rossumd70fe632015-08-05 12:11:06 +0200838 __slots__ = ()
839
Guido van Rossum4cefe742016-09-27 15:20:12 -0700840 @_tp_cache
841 def __getitem__(self, arg):
842 arg = _type_check(arg, "Optional[t] requires a single type.")
843 return Union[arg, type(None)]
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700844
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700845
Guido van Rossum4cefe742016-09-27 15:20:12 -0700846Optional = _Optional(_root=True)
847
848
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700849def _gorg(a):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800850 """Return the farthest origin of a generic class (internal helper)."""
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700851 assert isinstance(a, GenericMeta)
852 while a.__origin__ is not None:
853 a = a.__origin__
854 return a
855
856
857def _geqv(a, b):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800858 """Return whether two generic classes are equivalent (internal helper).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700859
860 The intention is to consider generic class X and any of its
Guido van Rossumb24569a2016-11-20 18:01:29 -0800861 parameterized forms (X[T], X[int], etc.) as equivalent.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700862
863 However, X is not equivalent to a subclass of X.
864
865 The relation is reflexive, symmetric and transitive.
866 """
867 assert isinstance(a, GenericMeta) and isinstance(b, GenericMeta)
868 # Reduce each to its origin.
869 return _gorg(a) is _gorg(b)
870
871
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700872def _next_in_mro(cls):
873 """Helper for Generic.__new__.
874
875 Returns the class after the last occurrence of Generic or
876 Generic[...] in cls.__mro__.
877 """
878 next_in_mro = object
879 # Look for the last occurrence of Generic or Generic[...].
880 for i, c in enumerate(cls.__mro__[:-1]):
881 if isinstance(c, GenericMeta) and _gorg(c) is Generic:
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800882 next_in_mro = cls.__mro__[i + 1]
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700883 return next_in_mro
884
885
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700886def _make_subclasshook(cls):
887 """Construct a __subclasshook__ callable that incorporates
888 the associated __extra__ class in subclass checks performed
889 against cls.
890 """
891 if isinstance(cls.__extra__, abc.ABCMeta):
892 # The logic mirrors that of ABCMeta.__subclasscheck__.
893 # Registered classes need not be checked here because
894 # cls and its extra share the same _abc_registry.
895 def __extrahook__(subclass):
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700896 res = cls.__extra__.__subclasshook__(subclass)
897 if res is not NotImplemented:
898 return res
899 if cls.__extra__ in subclass.__mro__:
900 return True
901 for scls in cls.__extra__.__subclasses__():
902 if isinstance(scls, GenericMeta):
903 continue
904 if issubclass(subclass, scls):
905 return True
906 return NotImplemented
907 else:
908 # For non-ABC extras we'll just call issubclass().
909 def __extrahook__(subclass):
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700910 if cls.__extra__ and issubclass(subclass, cls.__extra__):
911 return True
912 return NotImplemented
913 return __extrahook__
914
915
Guido van Rossum61f0a022016-11-29 09:46:21 -0800916def _no_slots_copy(dct):
917 """Internal helper: copy class __dict__ and clean slots class variables.
918 (They will be re-created if necessary by normal class machinery.)
919 """
920 dict_copy = dict(dct)
921 if '__slots__' in dict_copy:
922 for slot in dict_copy['__slots__']:
923 dict_copy.pop(slot, None)
924 return dict_copy
925
926
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700927class GenericMeta(TypingMeta, abc.ABCMeta):
Guido van Rossum83ec3022017-01-17 20:43:28 -0800928 """Metaclass for generic types.
929
930 This is a metaclass for typing.Generic and generic ABCs defined in
931 typing module. User defined subclasses of GenericMeta can override
932 __new__ and invoke super().__new__. Note that GenericMeta.__new__
933 has strict rules on what is allowed in its bases argument:
934 * plain Generic is disallowed in bases;
935 * Generic[...] should appear in bases at most once;
936 * if Generic[...] is present, then it should list all type variables
937 that appear in other bases.
938 In addition, type of all generic bases is erased, e.g., C[int] is
939 stripped to plain C.
940 """
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700941
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700942 def __new__(cls, name, bases, namespace,
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700943 tvars=None, args=None, origin=None, extra=None, orig_bases=None):
Guido van Rossum83ec3022017-01-17 20:43:28 -0800944 """Create a new generic class. GenericMeta.__new__ accepts
945 keyword arguments that are used for internal bookkeeping, therefore
946 an override should pass unused keyword arguments to super().
947 """
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700948 if tvars is not None:
949 # Called from __getitem__() below.
950 assert origin is not None
951 assert all(isinstance(t, TypeVar) for t in tvars), tvars
952 else:
953 # Called from class statement.
954 assert tvars is None, tvars
955 assert args is None, args
956 assert origin is None, origin
957
958 # Get the full set of tvars from the bases.
959 tvars = _type_vars(bases)
960 # Look for Generic[T1, ..., Tn].
961 # If found, tvars must be a subset of it.
962 # If not found, tvars is it.
963 # Also check for and reject plain Generic,
964 # and reject multiple Generic[...].
965 gvars = None
966 for base in bases:
967 if base is Generic:
968 raise TypeError("Cannot inherit from plain Generic")
969 if (isinstance(base, GenericMeta) and
970 base.__origin__ is Generic):
971 if gvars is not None:
972 raise TypeError(
973 "Cannot inherit from Generic[...] multiple types.")
974 gvars = base.__parameters__
975 if gvars is None:
976 gvars = tvars
977 else:
978 tvarset = set(tvars)
979 gvarset = set(gvars)
980 if not tvarset <= gvarset:
981 raise TypeError(
982 "Some type variables (%s) "
983 "are not listed in Generic[%s]" %
984 (", ".join(str(t) for t in tvars if t not in gvarset),
985 ", ".join(str(g) for g in gvars)))
986 tvars = gvars
987
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700988 initial_bases = bases
989 if extra is not None and type(extra) is abc.ABCMeta and extra not in bases:
990 bases = (extra,) + bases
991 bases = tuple(_gorg(b) if isinstance(b, GenericMeta) else b for b in bases)
992
993 # remove bare Generic from bases if there are other generic bases
994 if any(isinstance(b, GenericMeta) and b is not Generic for b in bases):
995 bases = tuple(b for b in bases if b is not Generic)
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100996 namespace.update({'__origin__': origin, '__extra__': extra})
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700997 self = super().__new__(cls, name, bases, namespace, _root=True)
998
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700999 self.__parameters__ = tvars
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001000 # Be prepared that GenericMeta will be subclassed by TupleMeta
1001 # and CallableMeta, those two allow ..., (), or [] in __args___.
1002 self.__args__ = tuple(... if a is _TypingEllipsis else
1003 () if a is _TypingEmpty else
1004 a for a in args) if args else None
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001005 # Speed hack (https://github.com/python/typing/issues/196).
1006 self.__next_in_mro__ = _next_in_mro(self)
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001007 # Preserve base classes on subclassing (__bases__ are type erased now).
1008 if orig_bases is None:
1009 self.__orig_bases__ = initial_bases
Guido van Rossumb47c9d22016-10-03 08:40:50 -07001010
1011 # This allows unparameterized generic collections to be used
1012 # with issubclass() and isinstance() in the same way as their
1013 # collections.abc counterparts (e.g., isinstance([], Iterable)).
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001014 if (
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001015 '__subclasshook__' not in namespace and extra or
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001016 # allow overriding
1017 getattr(self.__subclasshook__, '__name__', '') == '__extrahook__'
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001018 ):
Guido van Rossume2592672016-10-08 20:27:22 -07001019 self.__subclasshook__ = _make_subclasshook(self)
Guido van Rossumb47c9d22016-10-03 08:40:50 -07001020 if isinstance(extra, abc.ABCMeta):
1021 self._abc_registry = extra._abc_registry
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001022 self._abc_cache = extra._abc_cache
1023 elif origin is not None:
1024 self._abc_registry = origin._abc_registry
1025 self._abc_cache = origin._abc_cache
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001026
1027 if origin and hasattr(origin, '__qualname__'): # Fix for Python 3.2.
1028 self.__qualname__ = origin.__qualname__
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001029 self.__tree_hash__ = (hash(self._subs_tree()) if origin else
1030 super(GenericMeta, self).__hash__())
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001031 return self
1032
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001033 # _abc_negative_cache and _abc_negative_cache_version
1034 # realised as descriptors, since GenClass[t1, t2, ...] always
1035 # share subclass info with GenClass.
1036 # This is an important memory optimization.
1037 @property
1038 def _abc_negative_cache(self):
1039 if isinstance(self.__extra__, abc.ABCMeta):
1040 return self.__extra__._abc_negative_cache
1041 return _gorg(self)._abc_generic_negative_cache
1042
1043 @_abc_negative_cache.setter
1044 def _abc_negative_cache(self, value):
1045 if self.__origin__ is None:
1046 if isinstance(self.__extra__, abc.ABCMeta):
1047 self.__extra__._abc_negative_cache = value
1048 else:
1049 self._abc_generic_negative_cache = value
1050
1051 @property
1052 def _abc_negative_cache_version(self):
1053 if isinstance(self.__extra__, abc.ABCMeta):
1054 return self.__extra__._abc_negative_cache_version
1055 return _gorg(self)._abc_generic_negative_cache_version
1056
1057 @_abc_negative_cache_version.setter
1058 def _abc_negative_cache_version(self, value):
1059 if self.__origin__ is None:
1060 if isinstance(self.__extra__, abc.ABCMeta):
1061 self.__extra__._abc_negative_cache_version = value
1062 else:
1063 self._abc_generic_negative_cache_version = value
1064
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001065 def _get_type_vars(self, tvars):
1066 if self.__origin__ and self.__parameters__:
1067 _get_type_vars(self.__parameters__, tvars)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001068
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001069 def _eval_type(self, globalns, localns):
1070 ev_origin = (self.__origin__._eval_type(globalns, localns)
1071 if self.__origin__ else None)
1072 ev_args = tuple(_eval_type(a, globalns, localns) for a
1073 in self.__args__) if self.__args__ else None
1074 if ev_origin == self.__origin__ and ev_args == self.__args__:
1075 return self
1076 return self.__class__(self.__name__,
1077 self.__bases__,
Guido van Rossum61f0a022016-11-29 09:46:21 -08001078 _no_slots_copy(self.__dict__),
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001079 tvars=_type_vars(ev_args) if ev_args else None,
1080 args=ev_args,
1081 origin=ev_origin,
1082 extra=self.__extra__,
1083 orig_bases=self.__orig_bases__)
1084
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001085 def __repr__(self):
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001086 if self.__origin__ is None:
1087 return super().__repr__()
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001088 return self._tree_repr(self._subs_tree())
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001089
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001090 def _tree_repr(self, tree):
1091 arg_list = []
1092 for arg in tree[1:]:
1093 if arg == ():
1094 arg_list.append('()')
1095 elif not isinstance(arg, tuple):
1096 arg_list.append(_type_repr(arg))
1097 else:
1098 arg_list.append(arg[0]._tree_repr(arg))
1099 return super().__repr__() + '[%s]' % ', '.join(arg_list)
1100
1101 def _subs_tree(self, tvars=None, args=None):
1102 if self.__origin__ is None:
1103 return self
1104 tree_args = _subs_tree(self, tvars, args)
1105 return (_gorg(self),) + tuple(tree_args)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001106
1107 def __eq__(self, other):
1108 if not isinstance(other, GenericMeta):
1109 return NotImplemented
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001110 if self.__origin__ is None or other.__origin__ is None:
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001111 return self is other
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001112 return self.__tree_hash__ == other.__tree_hash__
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001113
1114 def __hash__(self):
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001115 return self.__tree_hash__
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001116
Guido van Rossum4cefe742016-09-27 15:20:12 -07001117 @_tp_cache
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001118 def __getitem__(self, params):
1119 if not isinstance(params, tuple):
1120 params = (params,)
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001121 if not params and not _gorg(self) is Tuple:
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001122 raise TypeError(
1123 "Parameter list to %s[...] cannot be empty" % _qualname(self))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001124 msg = "Parameters to generic types must be types."
1125 params = tuple(_type_check(p, msg) for p in params)
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001126 if self is Generic:
1127 # Generic can only be subscripted with unique type variables.
1128 if not all(isinstance(p, TypeVar) for p in params):
1129 raise TypeError(
1130 "Parameters to Generic[...] must all be type variables")
Guido van Rossumd70fe632015-08-05 12:11:06 +02001131 if len(set(params)) != len(params):
Guido van Rossum1b669102015-09-04 12:15:54 -07001132 raise TypeError(
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001133 "Parameters to Generic[...] must all be unique")
1134 tvars = params
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001135 args = params
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001136 elif self in (Tuple, Callable):
1137 tvars = _type_vars(params)
1138 args = params
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001139 elif self is _Protocol:
1140 # _Protocol is internal, don't check anything.
1141 tvars = params
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001142 args = params
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001143 elif self.__origin__ in (Generic, _Protocol):
1144 # Can't subscript Generic[...] or _Protocol[...].
1145 raise TypeError("Cannot subscript already-subscripted %s" %
1146 repr(self))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001147 else:
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001148 # Subscripting a regular Generic subclass.
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001149 _check_generic(self, params)
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001150 tvars = _type_vars(params)
1151 args = params
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001152
1153 prepend = (self,) if self.__origin__ is None else ()
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001154 return self.__class__(self.__name__,
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001155 prepend + self.__bases__,
Guido van Rossum61f0a022016-11-29 09:46:21 -08001156 _no_slots_copy(self.__dict__),
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001157 tvars=tvars,
1158 args=args,
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001159 origin=self,
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001160 extra=self.__extra__,
1161 orig_bases=self.__orig_bases__)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001162
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001163 def __subclasscheck__(self, cls):
1164 if self.__origin__ is not None:
1165 if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools']:
1166 raise TypeError("Parameterized generics cannot be used with class "
1167 "or instance checks")
1168 return False
1169 if self is Generic:
1170 raise TypeError("Class %r cannot be used with class "
1171 "or instance checks" % self)
1172 return super().__subclasscheck__(cls)
1173
Guido van Rossum1b669102015-09-04 12:15:54 -07001174 def __instancecheck__(self, instance):
1175 # Since we extend ABC.__subclasscheck__ and
1176 # ABC.__instancecheck__ inlines the cache checking done by the
1177 # latter, we must extend __instancecheck__ too. For simplicity
1178 # we just skip the cache check -- instance checks for generic
1179 # classes are supposed to be rare anyways.
Guido van Rossumb47c9d22016-10-03 08:40:50 -07001180 return issubclass(instance.__class__, self)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001181
Guido van Rossumb7dedc82016-10-29 12:44:29 -07001182 def __copy__(self):
Guido van Rossum61f0a022016-11-29 09:46:21 -08001183 return self.__class__(self.__name__, self.__bases__,
1184 _no_slots_copy(self.__dict__),
Guido van Rossumb7dedc82016-10-29 12:44:29 -07001185 self.__parameters__, self.__args__, self.__origin__,
1186 self.__extra__, self.__orig_bases__)
1187
Ivan Levkivskyiabb3b8a2017-02-24 04:03:28 +01001188 def __setattr__(self, attr, value):
1189 # We consider all the subscripted genrics as proxies for original class
Ivan Levkivskyi365cb5b2017-02-24 18:28:26 +01001190 if (
1191 attr.startswith('__') and attr.endswith('__') or
1192 attr.startswith('_abc_')
1193 ):
Ivan Levkivskyiabb3b8a2017-02-24 04:03:28 +01001194 super(GenericMeta, self).__setattr__(attr, value)
1195 else:
1196 super(GenericMeta, _gorg(self)).__setattr__(attr, value)
1197
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001198
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001199# Prevent checks for Generic to crash when defining Generic.
1200Generic = None
1201
1202
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001203def _generic_new(base_cls, cls, *args, **kwds):
1204 # Assure type is erased on instantiation,
1205 # but attempt to store it in __orig_class__
1206 if cls.__origin__ is None:
1207 return base_cls.__new__(cls)
1208 else:
1209 origin = _gorg(cls)
1210 obj = base_cls.__new__(origin)
1211 try:
1212 obj.__orig_class__ = cls
1213 except AttributeError:
1214 pass
1215 obj.__init__(*args, **kwds)
1216 return obj
1217
1218
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001219class Generic(metaclass=GenericMeta):
1220 """Abstract base class for generic types.
1221
Guido van Rossumb24569a2016-11-20 18:01:29 -08001222 A generic type is typically declared by inheriting from
1223 this class parameterized with one or more type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001224 For example, a generic mapping type might be defined as::
1225
1226 class Mapping(Generic[KT, VT]):
1227 def __getitem__(self, key: KT) -> VT:
1228 ...
1229 # Etc.
1230
1231 This class can then be used as follows::
1232
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001233 def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001234 try:
1235 return mapping[key]
1236 except KeyError:
1237 return default
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001238 """
1239
Guido van Rossumd70fe632015-08-05 12:11:06 +02001240 __slots__ = ()
1241
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001242 def __new__(cls, *args, **kwds):
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001243 if _geqv(cls, Generic):
1244 raise TypeError("Type Generic cannot be instantiated; "
1245 "it can be used only as a base class")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001246 return _generic_new(cls.__next_in_mro__, cls, *args, **kwds)
1247
1248
1249class _TypingEmpty:
Guido van Rossumb24569a2016-11-20 18:01:29 -08001250 """Internal placeholder for () or []. Used by TupleMeta and CallableMeta
1251 to allow empty list/tuple in specific places, without allowing them
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001252 to sneak in where prohibited.
1253 """
1254
1255
1256class _TypingEllipsis:
Guido van Rossumb24569a2016-11-20 18:01:29 -08001257 """Internal placeholder for ... (ellipsis)."""
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001258
1259
1260class TupleMeta(GenericMeta):
Guido van Rossumb24569a2016-11-20 18:01:29 -08001261 """Metaclass for Tuple (internal)."""
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001262
1263 @_tp_cache
1264 def __getitem__(self, parameters):
1265 if self.__origin__ is not None or not _geqv(self, Tuple):
1266 # Normal generic rules apply if this is not the first subscription
1267 # or a subscription of a subclass.
1268 return super().__getitem__(parameters)
1269 if parameters == ():
1270 return super().__getitem__((_TypingEmpty,))
1271 if not isinstance(parameters, tuple):
1272 parameters = (parameters,)
1273 if len(parameters) == 2 and parameters[1] is ...:
1274 msg = "Tuple[t, ...]: t must be a type."
1275 p = _type_check(parameters[0], msg)
1276 return super().__getitem__((p, _TypingEllipsis))
1277 msg = "Tuple[t0, t1, ...]: each t must be a type."
1278 parameters = tuple(_type_check(p, msg) for p in parameters)
1279 return super().__getitem__(parameters)
1280
1281 def __instancecheck__(self, obj):
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001282 if self.__args__ is None:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001283 return isinstance(obj, tuple)
1284 raise TypeError("Parameterized Tuple cannot be used "
1285 "with isinstance().")
1286
1287 def __subclasscheck__(self, cls):
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001288 if self.__args__ is None:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001289 return issubclass(cls, tuple)
1290 raise TypeError("Parameterized Tuple cannot be used "
1291 "with issubclass().")
1292
1293
1294class Tuple(tuple, extra=tuple, metaclass=TupleMeta):
1295 """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
1296
1297 Example: Tuple[T1, T2] is a tuple of two elements corresponding
1298 to type variables T1 and T2. Tuple[int, float, str] is a tuple
1299 of an int, a float and a string.
1300
1301 To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
1302 """
1303
1304 __slots__ = ()
1305
1306 def __new__(cls, *args, **kwds):
1307 if _geqv(cls, Tuple):
1308 raise TypeError("Type Tuple cannot be instantiated; "
1309 "use tuple() instead")
1310 return _generic_new(tuple, cls, *args, **kwds)
1311
1312
1313class CallableMeta(GenericMeta):
Guido van Rossumb24569a2016-11-20 18:01:29 -08001314 """Metaclass for Callable (internal)."""
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001315
1316 def __repr__(self):
1317 if self.__origin__ is None:
1318 return super().__repr__()
1319 return self._tree_repr(self._subs_tree())
1320
1321 def _tree_repr(self, tree):
1322 if _gorg(self) is not Callable:
1323 return super()._tree_repr(tree)
1324 # For actual Callable (not its subclass) we override
1325 # super()._tree_repr() for nice formatting.
1326 arg_list = []
1327 for arg in tree[1:]:
Guido van Rossum991d14f2016-11-09 13:12:51 -08001328 if not isinstance(arg, tuple):
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001329 arg_list.append(_type_repr(arg))
1330 else:
1331 arg_list.append(arg[0]._tree_repr(arg))
Guido van Rossum991d14f2016-11-09 13:12:51 -08001332 if arg_list[0] == '...':
1333 return repr(tree[0]) + '[..., %s]' % arg_list[1]
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001334 return (repr(tree[0]) +
1335 '[[%s], %s]' % (', '.join(arg_list[:-1]), arg_list[-1]))
1336
1337 def __getitem__(self, parameters):
Guido van Rossumb24569a2016-11-20 18:01:29 -08001338 """A thin wrapper around __getitem_inner__ to provide the latter
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001339 with hashable arguments to improve speed.
1340 """
1341
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001342 if self.__origin__ is not None or not _geqv(self, Callable):
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001343 return super().__getitem__(parameters)
1344 if not isinstance(parameters, tuple) or len(parameters) != 2:
1345 raise TypeError("Callable must be used as "
1346 "Callable[[arg, ...], result].")
1347 args, result = parameters
Guido van Rossum991d14f2016-11-09 13:12:51 -08001348 if args is Ellipsis:
1349 parameters = (Ellipsis, result)
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001350 else:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001351 if not isinstance(args, list):
1352 raise TypeError("Callable[args, result]: args must be a list."
1353 " Got %.100r." % (args,))
Guido van Rossum991d14f2016-11-09 13:12:51 -08001354 parameters = (tuple(args), result)
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001355 return self.__getitem_inner__(parameters)
1356
1357 @_tp_cache
1358 def __getitem_inner__(self, parameters):
Guido van Rossum991d14f2016-11-09 13:12:51 -08001359 args, result = parameters
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001360 msg = "Callable[args, result]: result must be a type."
1361 result = _type_check(result, msg)
Guido van Rossum991d14f2016-11-09 13:12:51 -08001362 if args is Ellipsis:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001363 return super().__getitem__((_TypingEllipsis, result))
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001364 msg = "Callable[[arg, ...], result]: each arg must be a type."
1365 args = tuple(_type_check(arg, msg) for arg in args)
1366 parameters = args + (result,)
1367 return super().__getitem__(parameters)
1368
1369
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001370class Callable(extra=collections_abc.Callable, metaclass=CallableMeta):
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001371 """Callable type; Callable[[int], str] is a function of (int) -> str.
1372
1373 The subscription syntax must always be used with exactly two
1374 values: the argument list and the return type. The argument list
Guido van Rossumb24569a2016-11-20 18:01:29 -08001375 must be a list of types or ellipsis; the return type must be a single type.
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001376
1377 There is no syntax to indicate optional or keyword arguments,
1378 such function types are rarely used as callback types.
1379 """
1380
1381 __slots__ = ()
1382
1383 def __new__(cls, *args, **kwds):
1384 if _geqv(cls, Callable):
1385 raise TypeError("Type Callable cannot be instantiated; "
1386 "use a non-abstract subclass instead")
1387 return _generic_new(cls.__next_in_mro__, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001388
1389
Guido van Rossum4cefe742016-09-27 15:20:12 -07001390class _ClassVar(_FinalTypingBase, _root=True):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001391 """Special type construct to mark class variables.
1392
1393 An annotation wrapped in ClassVar indicates that a given
1394 attribute is intended to be used as a class variable and
1395 should not be set on instances of that class. Usage::
1396
1397 class Starship:
1398 stats: ClassVar[Dict[str, int]] = {} # class variable
1399 damage: int = 10 # instance variable
1400
1401 ClassVar accepts only types and cannot be further subscribed.
1402
1403 Note that ClassVar is not a class itself, and should not
1404 be used with isinstance() or issubclass().
1405 """
1406
Guido van Rossum4cefe742016-09-27 15:20:12 -07001407 __slots__ = ('__type__',)
1408
1409 def __init__(self, tp=None, **kwds):
1410 self.__type__ = tp
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001411
1412 def __getitem__(self, item):
1413 cls = type(self)
1414 if self.__type__ is None:
1415 return cls(_type_check(item,
Guido van Rossum4cefe742016-09-27 15:20:12 -07001416 '{} accepts only single type.'.format(cls.__name__[1:])),
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001417 _root=True)
1418 raise TypeError('{} cannot be further subscripted'
1419 .format(cls.__name__[1:]))
1420
1421 def _eval_type(self, globalns, localns):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001422 new_tp = _eval_type(self.__type__, globalns, localns)
1423 if new_tp == self.__type__:
1424 return self
1425 return type(self)(new_tp, _root=True)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001426
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001427 def __repr__(self):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001428 r = super().__repr__()
1429 if self.__type__ is not None:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001430 r += '[{}]'.format(_type_repr(self.__type__))
Guido van Rossum4cefe742016-09-27 15:20:12 -07001431 return r
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001432
1433 def __hash__(self):
1434 return hash((type(self).__name__, self.__type__))
1435
1436 def __eq__(self, other):
1437 if not isinstance(other, _ClassVar):
1438 return NotImplemented
1439 if self.__type__ is not None:
1440 return self.__type__ == other.__type__
1441 return self is other
1442
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001443
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001444ClassVar = _ClassVar(_root=True)
1445
1446
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001447def cast(typ, val):
1448 """Cast a value to a type.
1449
1450 This returns the value unchanged. To the type checker this
1451 signals that the return value has the designated type, but at
1452 runtime we intentionally don't check anything (we want this
1453 to be as fast as possible).
1454 """
1455 return val
1456
1457
1458def _get_defaults(func):
1459 """Internal helper to extract the default arguments, by name."""
Guido van Rossum991d14f2016-11-09 13:12:51 -08001460 try:
1461 code = func.__code__
1462 except AttributeError:
1463 # Some built-in functions don't have __code__, __defaults__, etc.
1464 return {}
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001465 pos_count = code.co_argcount
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001466 arg_names = code.co_varnames
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001467 arg_names = arg_names[:pos_count]
1468 defaults = func.__defaults__ or ()
1469 kwdefaults = func.__kwdefaults__
1470 res = dict(kwdefaults) if kwdefaults else {}
1471 pos_offset = pos_count - len(defaults)
1472 for name, value in zip(arg_names[pos_offset:], defaults):
1473 assert name not in res
1474 res[name] = value
1475 return res
1476
1477
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001478_allowed_types = (types.FunctionType, types.BuiltinFunctionType,
1479 types.MethodType, types.ModuleType,
Ivan Levkivskyif06e0212017-05-02 19:14:07 +02001480 WrapperDescriptorType, MethodWrapperType, MethodDescriptorType)
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001481
1482
Guido van Rossum991d14f2016-11-09 13:12:51 -08001483def get_type_hints(obj, globalns=None, localns=None):
1484 """Return type hints for an object.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001485
Guido van Rossum991d14f2016-11-09 13:12:51 -08001486 This is often the same as obj.__annotations__, but it handles
1487 forward references encoded as string literals, and if necessary
1488 adds Optional[t] if a default value equal to None is set.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001489
Guido van Rossum991d14f2016-11-09 13:12:51 -08001490 The argument may be a module, class, method, or function. The annotations
1491 are returned as a dictionary. For classes, annotations include also
1492 inherited members.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001493
Guido van Rossum991d14f2016-11-09 13:12:51 -08001494 TypeError is raised if the argument is not of a type that can contain
1495 annotations, and an empty dictionary is returned if no annotations are
1496 present.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001497
Guido van Rossum991d14f2016-11-09 13:12:51 -08001498 BEWARE -- the behavior of globalns and localns is counterintuitive
1499 (unless you are familiar with how eval() and exec() work). The
1500 search order is locals first, then globals.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001501
Guido van Rossum991d14f2016-11-09 13:12:51 -08001502 - If no dict arguments are passed, an attempt is made to use the
1503 globals from obj, and these are also used as the locals. If the
1504 object does not appear to have globals, an exception is raised.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001505
Guido van Rossum991d14f2016-11-09 13:12:51 -08001506 - If one dict argument is passed, it is used for both globals and
1507 locals.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001508
Guido van Rossum991d14f2016-11-09 13:12:51 -08001509 - If two dict arguments are passed, they specify globals and
1510 locals, respectively.
1511 """
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001512
Guido van Rossum991d14f2016-11-09 13:12:51 -08001513 if getattr(obj, '__no_type_check__', None):
1514 return {}
1515 if globalns is None:
1516 globalns = getattr(obj, '__globals__', {})
1517 if localns is None:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001518 localns = globalns
Guido van Rossum991d14f2016-11-09 13:12:51 -08001519 elif localns is None:
1520 localns = globalns
1521 # Classes require a special treatment.
1522 if isinstance(obj, type):
1523 hints = {}
1524 for base in reversed(obj.__mro__):
1525 ann = base.__dict__.get('__annotations__', {})
1526 for name, value in ann.items():
1527 if value is None:
1528 value = type(None)
1529 if isinstance(value, str):
1530 value = _ForwardRef(value)
1531 value = _eval_type(value, globalns, localns)
1532 hints[name] = value
1533 return hints
1534 hints = getattr(obj, '__annotations__', None)
1535 if hints is None:
1536 # Return empty annotations for something that _could_ have them.
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001537 if isinstance(obj, _allowed_types):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001538 return {}
Guido van Rossum991d14f2016-11-09 13:12:51 -08001539 else:
1540 raise TypeError('{!r} is not a module, class, method, '
1541 'or function.'.format(obj))
1542 defaults = _get_defaults(obj)
1543 hints = dict(hints)
1544 for name, value in hints.items():
1545 if value is None:
1546 value = type(None)
1547 if isinstance(value, str):
1548 value = _ForwardRef(value)
1549 value = _eval_type(value, globalns, localns)
1550 if name in defaults and defaults[name] is None:
1551 value = Optional[value]
1552 hints[name] = value
1553 return hints
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001554
1555
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001556def no_type_check(arg):
1557 """Decorator to indicate that annotations are not type hints.
1558
1559 The argument must be a class or function; if it is a class, it
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001560 applies recursively to all methods and classes defined in that class
1561 (but not to methods defined in its superclasses or subclasses).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001562
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001563 This mutates the function(s) or class(es) in place.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001564 """
1565 if isinstance(arg, type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001566 arg_attrs = arg.__dict__.copy()
1567 for attr, val in arg.__dict__.items():
1568 if val in arg.__bases__:
1569 arg_attrs.pop(attr)
1570 for obj in arg_attrs.values():
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001571 if isinstance(obj, types.FunctionType):
1572 obj.__no_type_check__ = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001573 if isinstance(obj, type):
1574 no_type_check(obj)
1575 try:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001576 arg.__no_type_check__ = True
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001577 except TypeError: # built-in classes
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001578 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001579 return arg
1580
1581
1582def no_type_check_decorator(decorator):
1583 """Decorator to give another decorator the @no_type_check effect.
1584
1585 This wraps the decorator with something that wraps the decorated
1586 function in @no_type_check.
1587 """
1588
1589 @functools.wraps(decorator)
1590 def wrapped_decorator(*args, **kwds):
1591 func = decorator(*args, **kwds)
1592 func = no_type_check(func)
1593 return func
1594
1595 return wrapped_decorator
1596
1597
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001598def _overload_dummy(*args, **kwds):
1599 """Helper for @overload to raise when called."""
1600 raise NotImplementedError(
1601 "You should not call an overloaded function. "
1602 "A series of @overload-decorated functions "
1603 "outside a stub module should always be followed "
1604 "by an implementation that is not @overload-ed.")
1605
1606
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001607def overload(func):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001608 """Decorator for overloaded functions/methods.
1609
1610 In a stub file, place two or more stub definitions for the same
1611 function in a row, each decorated with @overload. For example:
1612
1613 @overload
1614 def utf8(value: None) -> None: ...
1615 @overload
1616 def utf8(value: bytes) -> bytes: ...
1617 @overload
1618 def utf8(value: str) -> bytes: ...
1619
1620 In a non-stub file (i.e. a regular .py file), do the same but
1621 follow it with an implementation. The implementation should *not*
1622 be decorated with @overload. For example:
1623
1624 @overload
1625 def utf8(value: None) -> None: ...
1626 @overload
1627 def utf8(value: bytes) -> bytes: ...
1628 @overload
1629 def utf8(value: str) -> bytes: ...
1630 def utf8(value):
1631 # implementation goes here
1632 """
1633 return _overload_dummy
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001634
1635
1636class _ProtocolMeta(GenericMeta):
1637 """Internal metaclass for _Protocol.
1638
1639 This exists so _Protocol classes can be generic without deriving
1640 from Generic.
1641 """
1642
Guido van Rossumd70fe632015-08-05 12:11:06 +02001643 def __instancecheck__(self, obj):
Guido van Rossumca4b2522016-11-19 10:32:41 -08001644 if _Protocol not in self.__bases__:
1645 return super().__instancecheck__(obj)
Guido van Rossumd70fe632015-08-05 12:11:06 +02001646 raise TypeError("Protocols cannot be used with isinstance().")
1647
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001648 def __subclasscheck__(self, cls):
1649 if not self._is_protocol:
1650 # No structural checks since this isn't a protocol.
1651 return NotImplemented
1652
1653 if self is _Protocol:
1654 # Every class is a subclass of the empty protocol.
1655 return True
1656
1657 # Find all attributes defined in the protocol.
1658 attrs = self._get_protocol_attrs()
1659
1660 for attr in attrs:
1661 if not any(attr in d.__dict__ for d in cls.__mro__):
1662 return False
1663 return True
1664
1665 def _get_protocol_attrs(self):
1666 # Get all Protocol base classes.
1667 protocol_bases = []
1668 for c in self.__mro__:
1669 if getattr(c, '_is_protocol', False) and c.__name__ != '_Protocol':
1670 protocol_bases.append(c)
1671
1672 # Get attributes included in protocol.
1673 attrs = set()
1674 for base in protocol_bases:
1675 for attr in base.__dict__.keys():
1676 # Include attributes not defined in any non-protocol bases.
1677 for c in self.__mro__:
1678 if (c is not base and attr in c.__dict__ and
1679 not getattr(c, '_is_protocol', False)):
1680 break
1681 else:
1682 if (not attr.startswith('_abc_') and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001683 attr != '__abstractmethods__' and
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001684 attr != '__annotations__' and
1685 attr != '__weakref__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001686 attr != '_is_protocol' and
1687 attr != '__dict__' and
1688 attr != '__args__' and
1689 attr != '__slots__' and
1690 attr != '_get_protocol_attrs' and
1691 attr != '__next_in_mro__' and
1692 attr != '__parameters__' and
1693 attr != '__origin__' and
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001694 attr != '__orig_bases__' and
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001695 attr != '__extra__' and
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001696 attr != '__tree_hash__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001697 attr != '__module__'):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001698 attrs.add(attr)
1699
1700 return attrs
1701
1702
1703class _Protocol(metaclass=_ProtocolMeta):
1704 """Internal base class for protocol classes.
1705
Guido van Rossumb24569a2016-11-20 18:01:29 -08001706 This implements a simple-minded structural issubclass check
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001707 (similar but more general than the one-offs in collections.abc
1708 such as Hashable).
1709 """
1710
Guido van Rossumd70fe632015-08-05 12:11:06 +02001711 __slots__ = ()
1712
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001713 _is_protocol = True
1714
1715
1716# Various ABCs mimicking those in collections.abc.
1717# A few are simply re-exported for completeness.
1718
1719Hashable = collections_abc.Hashable # Not generic.
1720
1721
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001722if hasattr(collections_abc, 'Awaitable'):
1723 class Awaitable(Generic[T_co], extra=collections_abc.Awaitable):
1724 __slots__ = ()
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001725
1726 __all__.append('Awaitable')
1727
1728
1729if hasattr(collections_abc, 'Coroutine'):
1730 class Coroutine(Awaitable[V_co], Generic[T_co, T_contra, V_co],
1731 extra=collections_abc.Coroutine):
1732 __slots__ = ()
1733
1734 __all__.append('Coroutine')
Guido van Rossumf17c2002015-12-03 17:31:24 -08001735
1736
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001737if hasattr(collections_abc, 'AsyncIterable'):
Guido van Rossumf17c2002015-12-03 17:31:24 -08001738
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001739 class AsyncIterable(Generic[T_co], extra=collections_abc.AsyncIterable):
1740 __slots__ = ()
Guido van Rossumf17c2002015-12-03 17:31:24 -08001741
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001742 class AsyncIterator(AsyncIterable[T_co],
1743 extra=collections_abc.AsyncIterator):
1744 __slots__ = ()
1745
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001746 __all__.append('AsyncIterable')
1747 __all__.append('AsyncIterator')
Guido van Rossumf17c2002015-12-03 17:31:24 -08001748
1749
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001750class Iterable(Generic[T_co], extra=collections_abc.Iterable):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001751 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001752
1753
1754class Iterator(Iterable[T_co], extra=collections_abc.Iterator):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001755 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001756
1757
1758class SupportsInt(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001759 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001760
1761 @abstractmethod
1762 def __int__(self) -> int:
1763 pass
1764
1765
1766class SupportsFloat(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001767 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001768
1769 @abstractmethod
1770 def __float__(self) -> float:
1771 pass
1772
1773
1774class SupportsComplex(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001775 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001776
1777 @abstractmethod
1778 def __complex__(self) -> complex:
1779 pass
1780
1781
1782class SupportsBytes(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001783 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001784
1785 @abstractmethod
1786 def __bytes__(self) -> bytes:
1787 pass
1788
1789
Guido van Rossumd70fe632015-08-05 12:11:06 +02001790class SupportsAbs(_Protocol[T_co]):
1791 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001792
1793 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001794 def __abs__(self) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001795 pass
1796
1797
Guido van Rossumd70fe632015-08-05 12:11:06 +02001798class SupportsRound(_Protocol[T_co]):
1799 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001800
1801 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001802 def __round__(self, ndigits: int = 0) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001803 pass
1804
1805
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001806if hasattr(collections_abc, 'Reversible'):
1807 class Reversible(Iterable[T_co], extra=collections_abc.Reversible):
1808 __slots__ = ()
1809else:
1810 class Reversible(_Protocol[T_co]):
1811 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001812
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001813 @abstractmethod
1814 def __reversed__(self) -> 'Iterator[T_co]':
1815 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001816
1817
1818Sized = collections_abc.Sized # Not generic.
1819
1820
1821class Container(Generic[T_co], extra=collections_abc.Container):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001822 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001823
1824
Guido van Rossumefa798d2016-08-23 11:01:50 -07001825if hasattr(collections_abc, 'Collection'):
1826 class Collection(Sized, Iterable[T_co], Container[T_co],
1827 extra=collections_abc.Collection):
1828 __slots__ = ()
1829
1830 __all__.append('Collection')
1831
1832
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001833# Callable was defined earlier.
1834
Guido van Rossumefa798d2016-08-23 11:01:50 -07001835if hasattr(collections_abc, 'Collection'):
1836 class AbstractSet(Collection[T_co],
1837 extra=collections_abc.Set):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001838 __slots__ = ()
Guido van Rossumefa798d2016-08-23 11:01:50 -07001839else:
1840 class AbstractSet(Sized, Iterable[T_co], Container[T_co],
1841 extra=collections_abc.Set):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001842 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001843
1844
1845class MutableSet(AbstractSet[T], extra=collections_abc.MutableSet):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001846 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001847
1848
Guido van Rossumefa798d2016-08-23 11:01:50 -07001849# NOTE: It is only covariant in the value type.
1850if hasattr(collections_abc, 'Collection'):
1851 class Mapping(Collection[KT], Generic[KT, VT_co],
1852 extra=collections_abc.Mapping):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001853 __slots__ = ()
Guido van Rossumefa798d2016-08-23 11:01:50 -07001854else:
1855 class Mapping(Sized, Iterable[KT], Container[KT], Generic[KT, VT_co],
1856 extra=collections_abc.Mapping):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001857 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001858
1859
1860class MutableMapping(Mapping[KT, VT], extra=collections_abc.MutableMapping):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001861 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001862
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001863
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001864if hasattr(collections_abc, 'Reversible'):
Guido van Rossumefa798d2016-08-23 11:01:50 -07001865 if hasattr(collections_abc, 'Collection'):
1866 class Sequence(Reversible[T_co], Collection[T_co],
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001867 extra=collections_abc.Sequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001868 __slots__ = ()
Guido van Rossumefa798d2016-08-23 11:01:50 -07001869 else:
1870 class Sequence(Sized, Reversible[T_co], Container[T_co],
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001871 extra=collections_abc.Sequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001872 __slots__ = ()
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001873else:
1874 class Sequence(Sized, Iterable[T_co], Container[T_co],
1875 extra=collections_abc.Sequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001876 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001877
1878
1879class MutableSequence(Sequence[T], extra=collections_abc.MutableSequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001880 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001881
1882
1883class ByteString(Sequence[int], extra=collections_abc.ByteString):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001884 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001885
1886
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001887class List(list, MutableSequence[T], extra=list):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001888
Guido van Rossum4cefe742016-09-27 15:20:12 -07001889 __slots__ = ()
1890
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001891 def __new__(cls, *args, **kwds):
1892 if _geqv(cls, List):
1893 raise TypeError("Type List cannot be instantiated; "
1894 "use list() instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001895 return _generic_new(list, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001896
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001897
Raymond Hettinger80490522017-01-16 22:42:37 -08001898class Deque(collections.deque, MutableSequence[T], extra=collections.deque):
1899
1900 __slots__ = ()
1901
1902 def __new__(cls, *args, **kwds):
1903 if _geqv(cls, Deque):
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001904 return collections.deque(*args, **kwds)
Raymond Hettinger80490522017-01-16 22:42:37 -08001905 return _generic_new(collections.deque, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001906
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001907
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001908class Set(set, MutableSet[T], extra=set):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001909
Guido van Rossum4cefe742016-09-27 15:20:12 -07001910 __slots__ = ()
1911
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001912 def __new__(cls, *args, **kwds):
1913 if _geqv(cls, Set):
1914 raise TypeError("Type Set cannot be instantiated; "
1915 "use set() instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001916 return _generic_new(set, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001917
1918
Guido van Rossum4cefe742016-09-27 15:20:12 -07001919class FrozenSet(frozenset, AbstractSet[T_co], extra=frozenset):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001920 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001921
1922 def __new__(cls, *args, **kwds):
1923 if _geqv(cls, FrozenSet):
1924 raise TypeError("Type FrozenSet cannot be instantiated; "
1925 "use frozenset() instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001926 return _generic_new(frozenset, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001927
1928
1929class MappingView(Sized, Iterable[T_co], extra=collections_abc.MappingView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001930 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001931
1932
Guido van Rossumd70fe632015-08-05 12:11:06 +02001933class KeysView(MappingView[KT], AbstractSet[KT],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001934 extra=collections_abc.KeysView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001935 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001936
1937
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001938class ItemsView(MappingView[Tuple[KT, VT_co]],
Guido van Rossum0e0563c2016-04-05 14:54:25 -07001939 AbstractSet[Tuple[KT, VT_co]],
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001940 Generic[KT, VT_co],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001941 extra=collections_abc.ItemsView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001942 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001943
1944
1945class ValuesView(MappingView[VT_co], extra=collections_abc.ValuesView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001946 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001947
1948
Brett Cannonf3ad0422016-04-15 10:51:30 -07001949if hasattr(contextlib, 'AbstractContextManager'):
1950 class ContextManager(Generic[T_co], extra=contextlib.AbstractContextManager):
1951 __slots__ = ()
1952 __all__.append('ContextManager')
1953
1954
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001955class Dict(dict, MutableMapping[KT, VT], extra=dict):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001956
Guido van Rossum4cefe742016-09-27 15:20:12 -07001957 __slots__ = ()
1958
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001959 def __new__(cls, *args, **kwds):
1960 if _geqv(cls, Dict):
1961 raise TypeError("Type Dict cannot be instantiated; "
1962 "use dict() instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001963 return _generic_new(dict, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001964
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001965
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001966class DefaultDict(collections.defaultdict, MutableMapping[KT, VT],
1967 extra=collections.defaultdict):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001968
Guido van Rossum4cefe742016-09-27 15:20:12 -07001969 __slots__ = ()
1970
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001971 def __new__(cls, *args, **kwds):
1972 if _geqv(cls, DefaultDict):
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001973 return collections.defaultdict(*args, **kwds)
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001974 return _generic_new(collections.defaultdict, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001975
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001976
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001977class Counter(collections.Counter, Dict[T, int], extra=collections.Counter):
1978
1979 __slots__ = ()
1980
1981 def __new__(cls, *args, **kwds):
1982 if _geqv(cls, Counter):
1983 return collections.Counter(*args, **kwds)
1984 return _generic_new(collections.Counter, cls, *args, **kwds)
1985
1986
1987if hasattr(collections, 'ChainMap'):
1988 # ChainMap only exists in 3.3+
1989 __all__.append('ChainMap')
1990
1991 class ChainMap(collections.ChainMap, MutableMapping[KT, VT],
1992 extra=collections.ChainMap):
1993
1994 __slots__ = ()
1995
1996 def __new__(cls, *args, **kwds):
1997 if _geqv(cls, ChainMap):
1998 return collections.ChainMap(*args, **kwds)
1999 return _generic_new(collections.ChainMap, cls, *args, **kwds)
2000
2001
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002002# Determine what base class to use for Generator.
2003if hasattr(collections_abc, 'Generator'):
2004 # Sufficiently recent versions of 3.5 have a Generator ABC.
2005 _G_base = collections_abc.Generator
2006else:
2007 # Fall back on the exact type.
2008 _G_base = types.GeneratorType
2009
2010
2011class Generator(Iterator[T_co], Generic[T_co, T_contra, V_co],
2012 extra=_G_base):
Guido van Rossumd70fe632015-08-05 12:11:06 +02002013 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002014
2015 def __new__(cls, *args, **kwds):
2016 if _geqv(cls, Generator):
2017 raise TypeError("Type Generator cannot be instantiated; "
2018 "create a subclass instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07002019 return _generic_new(_G_base, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002020
Guido van Rossumd7adfe12017-01-22 17:43:53 -08002021
Guido van Rossume9ed5602017-01-18 13:10:31 -08002022if hasattr(collections_abc, 'AsyncGenerator'):
2023 class AsyncGenerator(AsyncIterator[T_co], Generic[T_co, T_contra],
2024 extra=collections_abc.AsyncGenerator):
2025 __slots__ = ()
2026
2027 __all__.append('AsyncGenerator')
2028
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002029
Guido van Rossumeb9aca32016-05-24 16:38:22 -07002030# Internal type variable used for Type[].
Guido van Rossumefa798d2016-08-23 11:01:50 -07002031CT_co = TypeVar('CT_co', covariant=True, bound=type)
Guido van Rossumeb9aca32016-05-24 16:38:22 -07002032
2033
Guido van Rossumb22c7082016-05-26 09:56:19 -07002034# This is not a real generic class. Don't use outside annotations.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002035class Type(Generic[CT_co], extra=type):
Guido van Rossumb22c7082016-05-26 09:56:19 -07002036 """A special construct usable to annotate class objects.
Guido van Rossumeb9aca32016-05-24 16:38:22 -07002037
2038 For example, suppose we have the following classes::
2039
2040 class User: ... # Abstract base for User classes
2041 class BasicUser(User): ...
2042 class ProUser(User): ...
2043 class TeamUser(User): ...
2044
2045 And a function that takes a class argument that's a subclass of
2046 User and returns an instance of the corresponding class::
2047
2048 U = TypeVar('U', bound=User)
2049 def new_user(user_class: Type[U]) -> U:
2050 user = user_class()
2051 # (Here we could write the user object to a database)
2052 return user
2053
2054 joe = new_user(BasicUser)
2055
2056 At this point the type checker knows that joe has type BasicUser.
2057 """
2058
Guido van Rossum4cefe742016-09-27 15:20:12 -07002059 __slots__ = ()
2060
Guido van Rossumeb9aca32016-05-24 16:38:22 -07002061
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002062def _make_nmtuple(name, types):
Guido van Rossum2f841442016-11-15 09:48:06 -08002063 msg = "NamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a type"
2064 types = [(n, _type_check(t, msg)) for n, t in types]
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002065 nm_tpl = collections.namedtuple(name, [n for n, t in types])
Guido van Rossum83ec3022017-01-17 20:43:28 -08002066 # Prior to PEP 526, only _field_types attribute was assigned.
2067 # Now, both __annotations__ and _field_types are used to maintain compatibility.
2068 nm_tpl.__annotations__ = nm_tpl._field_types = collections.OrderedDict(types)
Guido van Rossum557d1eb2015-11-19 08:16:31 -08002069 try:
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002070 nm_tpl.__module__ = sys._getframe(2).f_globals.get('__name__', '__main__')
Guido van Rossum557d1eb2015-11-19 08:16:31 -08002071 except (AttributeError, ValueError):
2072 pass
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002073 return nm_tpl
2074
2075
Guido van Rossum2f841442016-11-15 09:48:06 -08002076_PY36 = sys.version_info[:2] >= (3, 6)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002077
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01002078# attributes prohibited to set in NamedTuple class syntax
2079_prohibited = ('__new__', '__init__', '__slots__', '__getnewargs__',
2080 '_fields', '_field_defaults', '_field_types',
Ivan Levkivskyif06e0212017-05-02 19:14:07 +02002081 '_make', '_replace', '_asdict', '_source')
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01002082
2083_special = ('__module__', '__name__', '__qualname__', '__annotations__')
2084
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002085
Guido van Rossum2f841442016-11-15 09:48:06 -08002086class NamedTupleMeta(type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002087
Guido van Rossum2f841442016-11-15 09:48:06 -08002088 def __new__(cls, typename, bases, ns):
2089 if ns.get('_root', False):
2090 return super().__new__(cls, typename, bases, ns)
2091 if not _PY36:
2092 raise TypeError("Class syntax for NamedTuple is only supported"
2093 " in Python 3.6+")
2094 types = ns.get('__annotations__', {})
Guido van Rossum3c268be2017-01-18 08:03:50 -08002095 nm_tpl = _make_nmtuple(typename, types.items())
2096 defaults = []
2097 defaults_dict = {}
2098 for field_name in types:
2099 if field_name in ns:
2100 default_value = ns[field_name]
2101 defaults.append(default_value)
2102 defaults_dict[field_name] = default_value
2103 elif defaults:
Guido van Rossumd7adfe12017-01-22 17:43:53 -08002104 raise TypeError("Non-default namedtuple field {field_name} cannot "
2105 "follow default field(s) {default_names}"
Guido van Rossum3c268be2017-01-18 08:03:50 -08002106 .format(field_name=field_name,
2107 default_names=', '.join(defaults_dict.keys())))
2108 nm_tpl.__new__.__defaults__ = tuple(defaults)
2109 nm_tpl._field_defaults = defaults_dict
Guido van Rossum95919c02017-01-22 17:47:20 -08002110 # update from user namespace without overriding special namedtuple attributes
2111 for key in ns:
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01002112 if key in _prohibited:
2113 raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
2114 elif key not in _special and key not in nm_tpl._fields:
Guido van Rossum95919c02017-01-22 17:47:20 -08002115 setattr(nm_tpl, key, ns[key])
Guido van Rossum3c268be2017-01-18 08:03:50 -08002116 return nm_tpl
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002117
Guido van Rossumd7adfe12017-01-22 17:43:53 -08002118
Guido van Rossum2f841442016-11-15 09:48:06 -08002119class NamedTuple(metaclass=NamedTupleMeta):
2120 """Typed version of namedtuple.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002121
Guido van Rossum2f841442016-11-15 09:48:06 -08002122 Usage in Python versions >= 3.6::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002123
Guido van Rossum2f841442016-11-15 09:48:06 -08002124 class Employee(NamedTuple):
2125 name: str
2126 id: int
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002127
Guido van Rossum2f841442016-11-15 09:48:06 -08002128 This is equivalent to::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002129
Guido van Rossum2f841442016-11-15 09:48:06 -08002130 Employee = collections.namedtuple('Employee', ['name', 'id'])
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002131
Guido van Rossum83ec3022017-01-17 20:43:28 -08002132 The resulting class has extra __annotations__ and _field_types
2133 attributes, giving an ordered dict mapping field names to types.
2134 __annotations__ should be preferred, while _field_types
2135 is kept to maintain pre PEP 526 compatibility. (The field names
Guido van Rossum2f841442016-11-15 09:48:06 -08002136 are in the _fields attribute, which is part of the namedtuple
2137 API.) Alternative equivalent keyword syntax is also accepted::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002138
Guido van Rossum2f841442016-11-15 09:48:06 -08002139 Employee = NamedTuple('Employee', name=str, id=int)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002140
Guido van Rossum2f841442016-11-15 09:48:06 -08002141 In Python versions <= 3.5 use::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002142
Guido van Rossum2f841442016-11-15 09:48:06 -08002143 Employee = NamedTuple('Employee', [('name', str), ('id', int)])
2144 """
2145 _root = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002146
Guido van Rossum2f841442016-11-15 09:48:06 -08002147 def __new__(self, typename, fields=None, **kwargs):
2148 if kwargs and not _PY36:
2149 raise TypeError("Keyword syntax for NamedTuple is only supported"
2150 " in Python 3.6+")
2151 if fields is None:
2152 fields = kwargs.items()
2153 elif kwargs:
2154 raise TypeError("Either list of fields or keywords"
2155 " can be provided to NamedTuple, not both")
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002156 return _make_nmtuple(typename, fields)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002157
2158
Guido van Rossum91185fe2016-06-08 11:19:11 -07002159def NewType(name, tp):
2160 """NewType creates simple unique types with almost zero
2161 runtime overhead. NewType(name, tp) is considered a subtype of tp
2162 by static type checkers. At runtime, NewType(name, tp) returns
2163 a dummy function that simply returns its argument. Usage::
2164
2165 UserId = NewType('UserId', int)
2166
2167 def name_by_id(user_id: UserId) -> str:
2168 ...
2169
2170 UserId('user') # Fails type check
2171
2172 name_by_id(42) # Fails type check
2173 name_by_id(UserId(42)) # OK
2174
2175 num = UserId(5) + 1 # type: int
2176 """
2177
2178 def new_type(x):
2179 return x
2180
2181 new_type.__name__ = name
2182 new_type.__supertype__ = tp
2183 return new_type
2184
2185
Guido van Rossum0e0563c2016-04-05 14:54:25 -07002186# Python-version-specific alias (Python 2: unicode; Python 3: str)
2187Text = str
2188
2189
Guido van Rossum91185fe2016-06-08 11:19:11 -07002190# Constant that's True when type checking, but False here.
2191TYPE_CHECKING = False
2192
2193
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002194class IO(Generic[AnyStr]):
2195 """Generic base class for TextIO and BinaryIO.
2196
2197 This is an abstract, generic version of the return of open().
2198
2199 NOTE: This does not distinguish between the different possible
2200 classes (text vs. binary, read vs. write vs. read/write,
2201 append-only, unbuffered). The TextIO and BinaryIO subclasses
2202 below capture the distinctions between text vs. binary, which is
2203 pervasive in the interface; however we currently do not offer a
2204 way to track the other distinctions in the type system.
2205 """
2206
Guido van Rossumd70fe632015-08-05 12:11:06 +02002207 __slots__ = ()
2208
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002209 @abstractproperty
2210 def mode(self) -> str:
2211 pass
2212
2213 @abstractproperty
2214 def name(self) -> str:
2215 pass
2216
2217 @abstractmethod
2218 def close(self) -> None:
2219 pass
2220
2221 @abstractmethod
2222 def closed(self) -> bool:
2223 pass
2224
2225 @abstractmethod
2226 def fileno(self) -> int:
2227 pass
2228
2229 @abstractmethod
2230 def flush(self) -> None:
2231 pass
2232
2233 @abstractmethod
2234 def isatty(self) -> bool:
2235 pass
2236
2237 @abstractmethod
2238 def read(self, n: int = -1) -> AnyStr:
2239 pass
2240
2241 @abstractmethod
2242 def readable(self) -> bool:
2243 pass
2244
2245 @abstractmethod
2246 def readline(self, limit: int = -1) -> AnyStr:
2247 pass
2248
2249 @abstractmethod
2250 def readlines(self, hint: int = -1) -> List[AnyStr]:
2251 pass
2252
2253 @abstractmethod
2254 def seek(self, offset: int, whence: int = 0) -> int:
2255 pass
2256
2257 @abstractmethod
2258 def seekable(self) -> bool:
2259 pass
2260
2261 @abstractmethod
2262 def tell(self) -> int:
2263 pass
2264
2265 @abstractmethod
2266 def truncate(self, size: int = None) -> int:
2267 pass
2268
2269 @abstractmethod
2270 def writable(self) -> bool:
2271 pass
2272
2273 @abstractmethod
2274 def write(self, s: AnyStr) -> int:
2275 pass
2276
2277 @abstractmethod
2278 def writelines(self, lines: List[AnyStr]) -> None:
2279 pass
2280
2281 @abstractmethod
2282 def __enter__(self) -> 'IO[AnyStr]':
2283 pass
2284
2285 @abstractmethod
2286 def __exit__(self, type, value, traceback) -> None:
2287 pass
2288
2289
2290class BinaryIO(IO[bytes]):
2291 """Typed version of the return of open() in binary mode."""
2292
Guido van Rossumd70fe632015-08-05 12:11:06 +02002293 __slots__ = ()
2294
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002295 @abstractmethod
2296 def write(self, s: Union[bytes, bytearray]) -> int:
2297 pass
2298
2299 @abstractmethod
2300 def __enter__(self) -> 'BinaryIO':
2301 pass
2302
2303
2304class TextIO(IO[str]):
2305 """Typed version of the return of open() in text mode."""
2306
Guido van Rossumd70fe632015-08-05 12:11:06 +02002307 __slots__ = ()
2308
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002309 @abstractproperty
2310 def buffer(self) -> BinaryIO:
2311 pass
2312
2313 @abstractproperty
2314 def encoding(self) -> str:
2315 pass
2316
2317 @abstractproperty
Guido van Rossum991d14f2016-11-09 13:12:51 -08002318 def errors(self) -> Optional[str]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002319 pass
2320
2321 @abstractproperty
2322 def line_buffering(self) -> bool:
2323 pass
2324
2325 @abstractproperty
2326 def newlines(self) -> Any:
2327 pass
2328
2329 @abstractmethod
2330 def __enter__(self) -> 'TextIO':
2331 pass
2332
2333
2334class io:
2335 """Wrapper namespace for IO generic classes."""
2336
2337 __all__ = ['IO', 'TextIO', 'BinaryIO']
2338 IO = IO
2339 TextIO = TextIO
2340 BinaryIO = BinaryIO
2341
Guido van Rossumd7adfe12017-01-22 17:43:53 -08002342
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002343io.__name__ = __name__ + '.io'
2344sys.modules[io.__name__] = io
2345
2346
2347Pattern = _TypeAlias('Pattern', AnyStr, type(stdlib_re.compile('')),
2348 lambda p: p.pattern)
2349Match = _TypeAlias('Match', AnyStr, type(stdlib_re.match('', '')),
2350 lambda m: m.re.pattern)
2351
2352
2353class re:
2354 """Wrapper namespace for re type aliases."""
2355
2356 __all__ = ['Pattern', 'Match']
2357 Pattern = Pattern
2358 Match = Match
2359
Guido van Rossumd7adfe12017-01-22 17:43:53 -08002360
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002361re.__name__ = __name__ + '.re'
2362sys.modules[re.__name__] = re