blob: b5564cc29a2d830eb833564d37e332a7e7ee9b49 [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 Levkivskyi29fda8d2017-06-10 21:57:56 +020013if sys.version_info[:2] >= (3, 6):
14 import _collections_abc # Needed for private function _check_methods # noqa
Ivan Levkivskyib692dc82017-02-13 22:50:14 +010015try:
Ivan Levkivskyif06e0212017-05-02 19:14:07 +020016 from types import WrapperDescriptorType, MethodWrapperType, MethodDescriptorType
Ivan Levkivskyib692dc82017-02-13 22:50:14 +010017except ImportError:
Ivan Levkivskyif06e0212017-05-02 19:14:07 +020018 WrapperDescriptorType = type(object.__init__)
Ivan Levkivskyib692dc82017-02-13 22:50:14 +010019 MethodWrapperType = type(object().__str__)
20 MethodDescriptorType = type(str.join)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070021
22
23# Please keep __all__ alphabetized within each category.
24__all__ = [
25 # Super-special typing primitives.
26 'Any',
27 'Callable',
Guido van Rossum0a6976d2016-09-11 15:34:56 -070028 'ClassVar',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070029 'Generic',
30 'Optional',
Guido van Rossumeb9aca32016-05-24 16:38:22 -070031 'Tuple',
32 'Type',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070033 'TypeVar',
34 'Union',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070035
36 # ABCs (from collections.abc).
37 'AbstractSet', # collections.abc.Set.
Guido van Rossum83ec3022017-01-17 20:43:28 -080038 'GenericMeta', # subclass of abc.ABCMeta and a metaclass
39 # for 'Generic' and ABCs below.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070040 'ByteString',
41 'Container',
Ivan Levkivskyi29fda8d2017-06-10 21:57:56 +020042 'ContextManager',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070043 'Hashable',
44 'ItemsView',
45 'Iterable',
46 'Iterator',
47 'KeysView',
48 'Mapping',
49 'MappingView',
50 'MutableMapping',
51 'MutableSequence',
52 'MutableSet',
53 'Sequence',
54 'Sized',
55 'ValuesView',
Guido van Rossum62fe1bb2016-10-29 16:05:26 -070056 # The following are added depending on presence
57 # of their non-generic counterparts in stdlib:
58 # Awaitable,
59 # AsyncIterator,
60 # AsyncIterable,
61 # Coroutine,
62 # Collection,
Guido van Rossume9ed5602017-01-18 13:10:31 -080063 # AsyncGenerator,
Ivan Levkivskyi29fda8d2017-06-10 21:57:56 +020064 # AsyncContextManager
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070065
66 # Structural checks, a.k.a. protocols.
67 'Reversible',
68 'SupportsAbs',
Ivan Levkivskyif06e0212017-05-02 19:14:07 +020069 'SupportsBytes',
70 'SupportsComplex',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070071 'SupportsFloat',
72 'SupportsInt',
73 'SupportsRound',
74
75 # Concrete collection types.
Ivan Levkivskyib692dc82017-02-13 22:50:14 +010076 'Counter',
Raymond Hettinger80490522017-01-16 22:42:37 -080077 'Deque',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070078 'Dict',
Guido van Rossumbd5b9a02016-04-05 08:28:52 -070079 'DefaultDict',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070080 'List',
81 'Set',
Guido van Rossumefa798d2016-08-23 11:01:50 -070082 'FrozenSet',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070083 'NamedTuple', # Not really a type.
84 'Generator',
85
86 # One-off things.
87 'AnyStr',
88 'cast',
89 'get_type_hints',
Guido van Rossum91185fe2016-06-08 11:19:11 -070090 'NewType',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070091 'no_type_check',
92 'no_type_check_decorator',
93 'overload',
Guido van Rossum0e0563c2016-04-05 14:54:25 -070094 'Text',
Guido van Rossum91185fe2016-06-08 11:19:11 -070095 'TYPE_CHECKING',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070096]
97
Guido van Rossumbd5b9a02016-04-05 08:28:52 -070098# The pseudo-submodules 're' and 'io' are part of the public
99# namespace, but excluded from __all__ because they might stomp on
100# legitimate imports of those modules.
101
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700102
103def _qualname(x):
104 if sys.version_info[:2] >= (3, 3):
105 return x.__qualname__
106 else:
107 # Fall back to just name.
108 return x.__name__
109
110
Guido van Rossum4cefe742016-09-27 15:20:12 -0700111def _trim_name(nm):
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800112 whitelist = ('_TypeAlias', '_ForwardRef', '_TypingBase', '_FinalTypingBase')
113 if nm.startswith('_') and nm not in whitelist:
Guido van Rossum4cefe742016-09-27 15:20:12 -0700114 nm = nm[1:]
115 return nm
116
117
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700118class TypingMeta(type):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800119 """Metaclass for most types defined in typing module
120 (not a part of public API).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700121
122 This overrides __new__() to require an extra keyword parameter
123 '_root', which serves as a guard against naive subclassing of the
124 typing classes. Any legitimate class defined using a metaclass
Guido van Rossumb24569a2016-11-20 18:01:29 -0800125 derived from TypingMeta must pass _root=True.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700126
Guido van Rossumb24569a2016-11-20 18:01:29 -0800127 This also defines a dummy constructor (all the work for most typing
128 constructs is done in __new__) and a nicer repr().
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700129 """
130
131 _is_protocol = False
132
133 def __new__(cls, name, bases, namespace, *, _root=False):
134 if not _root:
135 raise TypeError("Cannot subclass %s" %
136 (', '.join(map(_type_repr, bases)) or '()'))
137 return super().__new__(cls, name, bases, namespace)
138
139 def __init__(self, *args, **kwds):
140 pass
141
142 def _eval_type(self, globalns, localns):
143 """Override this in subclasses to interpret forward references.
144
Guido van Rossumb24569a2016-11-20 18:01:29 -0800145 For example, List['C'] is internally stored as
146 List[_ForwardRef('C')], which should evaluate to List[C],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700147 where C is an object found in globalns or localns (searching
148 localns first, of course).
149 """
150 return self
151
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700152 def _get_type_vars(self, tvars):
153 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700154
155 def __repr__(self):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700156 qname = _trim_name(_qualname(self))
157 return '%s.%s' % (self.__module__, qname)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700158
159
Guido van Rossum4cefe742016-09-27 15:20:12 -0700160class _TypingBase(metaclass=TypingMeta, _root=True):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800161 """Internal indicator of special typing constructs."""
Guido van Rossum4cefe742016-09-27 15:20:12 -0700162
Guido van Rossum83ec3022017-01-17 20:43:28 -0800163 __slots__ = ('__weakref__',)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700164
Guido van Rossum4cefe742016-09-27 15:20:12 -0700165 def __init__(self, *args, **kwds):
166 pass
167
168 def __new__(cls, *args, **kwds):
169 """Constructor.
170
171 This only exists to give a better error message in case
172 someone tries to subclass a special typing object (not a good idea).
173 """
174 if (len(args) == 3 and
175 isinstance(args[0], str) and
176 isinstance(args[1], tuple)):
177 # Close enough.
178 raise TypeError("Cannot subclass %r" % cls)
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700179 return super().__new__(cls)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700180
181 # Things that are not classes also need these.
182 def _eval_type(self, globalns, localns):
183 return self
184
185 def _get_type_vars(self, tvars):
186 pass
187
188 def __repr__(self):
189 cls = type(self)
190 qname = _trim_name(_qualname(cls))
191 return '%s.%s' % (cls.__module__, qname)
192
193 def __call__(self, *args, **kwds):
194 raise TypeError("Cannot instantiate %r" % type(self))
195
196
197class _FinalTypingBase(_TypingBase, _root=True):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800198 """Internal mix-in class to prevent instantiation.
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700199
200 Prevents instantiation unless _root=True is given in class call.
Guido van Rossumb24569a2016-11-20 18:01:29 -0800201 It is used to create pseudo-singleton instances Any, Union, Optional, etc.
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700202 """
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700203
Guido van Rossumd70fe632015-08-05 12:11:06 +0200204 __slots__ = ()
205
Guido van Rossum4cefe742016-09-27 15:20:12 -0700206 def __new__(cls, *args, _root=False, **kwds):
207 self = super().__new__(cls, *args, **kwds)
208 if _root is True:
209 return self
210 raise TypeError("Cannot instantiate %r" % cls)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700211
Guido van Rossumb7dedc82016-10-29 12:44:29 -0700212 def __reduce__(self):
213 return _trim_name(type(self).__name__)
214
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700215
Guido van Rossum4cefe742016-09-27 15:20:12 -0700216class _ForwardRef(_TypingBase, _root=True):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800217 """Internal wrapper to hold a forward reference."""
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700218
Guido van Rossum4cefe742016-09-27 15:20:12 -0700219 __slots__ = ('__forward_arg__', '__forward_code__',
Guido van Rossumc7b92952016-11-10 08:24:06 -0800220 '__forward_evaluated__', '__forward_value__')
Guido van Rossum4cefe742016-09-27 15:20:12 -0700221
222 def __init__(self, arg):
223 super().__init__(arg)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700224 if not isinstance(arg, str):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800225 raise TypeError('Forward reference must be a string -- got %r' % (arg,))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700226 try:
227 code = compile(arg, '<string>', 'eval')
228 except SyntaxError:
Guido van Rossumb24569a2016-11-20 18:01:29 -0800229 raise SyntaxError('Forward reference must be an expression -- got %r' %
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700230 (arg,))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700231 self.__forward_arg__ = arg
232 self.__forward_code__ = code
233 self.__forward_evaluated__ = False
234 self.__forward_value__ = None
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700235
236 def _eval_type(self, globalns, localns):
Guido van Rossumdad17902016-11-10 08:29:18 -0800237 if not self.__forward_evaluated__ or localns is not globalns:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700238 if globalns is None and localns is None:
239 globalns = localns = {}
240 elif globalns is None:
241 globalns = localns
242 elif localns is None:
243 localns = globalns
244 self.__forward_value__ = _type_check(
245 eval(self.__forward_code__, globalns, localns),
246 "Forward references must evaluate to types.")
247 self.__forward_evaluated__ = True
248 return self.__forward_value__
249
Guido van Rossum4cefe742016-09-27 15:20:12 -0700250 def __eq__(self, other):
251 if not isinstance(other, _ForwardRef):
252 return NotImplemented
253 return (self.__forward_arg__ == other.__forward_arg__ and
Guido van Rossumc7b92952016-11-10 08:24:06 -0800254 self.__forward_value__ == other.__forward_value__)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700255
256 def __hash__(self):
Guido van Rossumc7b92952016-11-10 08:24:06 -0800257 return hash((self.__forward_arg__, self.__forward_value__))
Guido van Rossum4cefe742016-09-27 15:20:12 -0700258
Guido van Rossumd70fe632015-08-05 12:11:06 +0200259 def __instancecheck__(self, obj):
260 raise TypeError("Forward references cannot be used with isinstance().")
261
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700262 def __subclasscheck__(self, cls):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700263 raise TypeError("Forward references cannot be used with issubclass().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700264
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700265 def __repr__(self):
266 return '_ForwardRef(%r)' % (self.__forward_arg__,)
267
268
Guido van Rossum4cefe742016-09-27 15:20:12 -0700269class _TypeAlias(_TypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700270 """Internal helper class for defining generic variants of concrete types.
271
Guido van Rossum4cefe742016-09-27 15:20:12 -0700272 Note that this is not a type; let's call it a pseudo-type. It cannot
273 be used in instance and subclass checks in parameterized form, i.e.
274 ``isinstance(42, Match[str])`` raises ``TypeError`` instead of returning
275 ``False``.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700276 """
277
Guido van Rossumd70fe632015-08-05 12:11:06 +0200278 __slots__ = ('name', 'type_var', 'impl_type', 'type_checker')
279
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700280 def __init__(self, name, type_var, impl_type, type_checker):
281 """Initializer.
282
283 Args:
284 name: The name, e.g. 'Pattern'.
285 type_var: The type parameter, e.g. AnyStr, or the
286 specific type, e.g. str.
287 impl_type: The implementation type.
288 type_checker: Function that takes an impl_type instance.
289 and returns a value that should be a type_var instance.
290 """
291 assert isinstance(name, str), repr(name)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700292 assert isinstance(impl_type, type), repr(impl_type)
293 assert not isinstance(impl_type, TypingMeta), repr(impl_type)
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700294 assert isinstance(type_var, (type, _TypingBase)), repr(type_var)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700295 self.name = name
296 self.type_var = type_var
297 self.impl_type = impl_type
298 self.type_checker = type_checker
299
300 def __repr__(self):
301 return "%s[%s]" % (self.name, _type_repr(self.type_var))
302
303 def __getitem__(self, parameter):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700304 if not isinstance(self.type_var, TypeVar):
305 raise TypeError("%s cannot be further parameterized." % self)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700306 if self.type_var.__constraints__ and isinstance(parameter, type):
307 if not issubclass(parameter, self.type_var.__constraints__):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700308 raise TypeError("%s is not a valid substitution for %s." %
309 (parameter, self.type_var))
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700310 if isinstance(parameter, TypeVar) and parameter is not self.type_var:
311 raise TypeError("%s cannot be re-parameterized." % self)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700312 return self.__class__(self.name, parameter,
313 self.impl_type, self.type_checker)
314
Guido van Rossum4cefe742016-09-27 15:20:12 -0700315 def __eq__(self, other):
316 if not isinstance(other, _TypeAlias):
317 return NotImplemented
318 return self.name == other.name and self.type_var == other.type_var
319
320 def __hash__(self):
321 return hash((self.name, self.type_var))
322
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700323 def __instancecheck__(self, obj):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700324 if not isinstance(self.type_var, TypeVar):
325 raise TypeError("Parameterized type aliases cannot be used "
326 "with isinstance().")
327 return isinstance(obj, self.impl_type)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700328
329 def __subclasscheck__(self, cls):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700330 if not isinstance(self.type_var, TypeVar):
331 raise TypeError("Parameterized type aliases cannot be used "
332 "with issubclass().")
333 return issubclass(cls, self.impl_type)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700334
335
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700336def _get_type_vars(types, tvars):
337 for t in types:
Guido van Rossum4cefe742016-09-27 15:20:12 -0700338 if isinstance(t, TypingMeta) or isinstance(t, _TypingBase):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700339 t._get_type_vars(tvars)
340
341
342def _type_vars(types):
343 tvars = []
344 _get_type_vars(types, tvars)
345 return tuple(tvars)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700346
347
348def _eval_type(t, globalns, localns):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700349 if isinstance(t, TypingMeta) or isinstance(t, _TypingBase):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700350 return t._eval_type(globalns, localns)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700351 return t
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700352
353
354def _type_check(arg, msg):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800355 """Check that the argument is a type, and return it (internal helper).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700356
357 As a special case, accept None and return type(None) instead.
358 Also, _TypeAlias instances (e.g. Match, Pattern) are acceptable.
359
360 The msg argument is a human-readable error message, e.g.
361
362 "Union[arg, ...]: arg should be a type."
363
364 We append the repr() of the actual value (truncated to 100 chars).
365 """
366 if arg is None:
367 return type(None)
368 if isinstance(arg, str):
369 arg = _ForwardRef(arg)
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800370 if (
371 isinstance(arg, _TypingBase) and type(arg).__name__ == '_ClassVar' or
372 not isinstance(arg, (type, _TypingBase)) and not callable(arg)
373 ):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700374 raise TypeError(msg + " Got %.100r." % (arg,))
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700375 # Bare Union etc. are not valid as type arguments
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800376 if (
377 type(arg).__name__ in ('_Union', '_Optional') and
378 not getattr(arg, '__origin__', None) or
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +0200379 isinstance(arg, TypingMeta) and arg._gorg in (Generic, _Protocol)
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800380 ):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700381 raise TypeError("Plain %s is not valid as type argument" % arg)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700382 return arg
383
384
385def _type_repr(obj):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800386 """Return the repr() of an object, special-casing types (internal helper).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700387
388 If obj is a type, we return a shorter version than the default
389 type.__repr__, based on the module and qualified name, which is
390 typically enough to uniquely identify a type. For everything
391 else, we fall back on repr(obj).
392 """
393 if isinstance(obj, type) and not isinstance(obj, TypingMeta):
394 if obj.__module__ == 'builtins':
395 return _qualname(obj)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700396 return '%s.%s' % (obj.__module__, _qualname(obj))
397 if obj is ...:
398 return('...')
399 if isinstance(obj, types.FunctionType):
400 return obj.__name__
401 return repr(obj)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700402
403
Guido van Rossum4cefe742016-09-27 15:20:12 -0700404class _Any(_FinalTypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700405 """Special type indicating an unconstrained type.
406
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700407 - Any is compatible with every type.
408 - Any assumed to have all methods.
409 - All values assumed to be instances of Any.
410
411 Note that all the above statements are true from the point of view of
412 static type checkers. At runtime, Any should not be used with instance
413 or class checks.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700414 """
415
Guido van Rossumd70fe632015-08-05 12:11:06 +0200416 __slots__ = ()
417
Guido van Rossum4cefe742016-09-27 15:20:12 -0700418 def __instancecheck__(self, obj):
419 raise TypeError("Any cannot be used with isinstance().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700420
Guido van Rossum4cefe742016-09-27 15:20:12 -0700421 def __subclasscheck__(self, cls):
422 raise TypeError("Any cannot be used with issubclass().")
423
424
425Any = _Any(_root=True)
426
427
Ivan Levkivskyif06e0212017-05-02 19:14:07 +0200428class _NoReturn(_FinalTypingBase, _root=True):
429 """Special type indicating functions that never return.
430 Example::
431
432 from typing import NoReturn
433
434 def stop() -> NoReturn:
435 raise Exception('no way')
436
437 This type is invalid in other positions, e.g., ``List[NoReturn]``
438 will fail in static type checkers.
439 """
440
441 __slots__ = ()
442
443 def __instancecheck__(self, obj):
444 raise TypeError("NoReturn cannot be used with isinstance().")
445
446 def __subclasscheck__(self, cls):
447 raise TypeError("NoReturn cannot be used with issubclass().")
448
449
450NoReturn = _NoReturn(_root=True)
451
452
Guido van Rossum4cefe742016-09-27 15:20:12 -0700453class TypeVar(_TypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700454 """Type variable.
455
456 Usage::
457
458 T = TypeVar('T') # Can be anything
459 A = TypeVar('A', str, bytes) # Must be str or bytes
460
461 Type variables exist primarily for the benefit of static type
462 checkers. They serve as the parameters for generic types as well
463 as for generic function definitions. See class Generic for more
464 information on generic types. Generic functions work as follows:
465
Guido van Rossumb24569a2016-11-20 18:01:29 -0800466 def repeat(x: T, n: int) -> List[T]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700467 '''Return a list containing n references to x.'''
468 return [x]*n
469
470 def longest(x: A, y: A) -> A:
471 '''Return the longest of two strings.'''
472 return x if len(x) >= len(y) else y
473
474 The latter example's signature is essentially the overloading
475 of (str, str) -> str and (bytes, bytes) -> bytes. Also note
476 that if the arguments are instances of some subclass of str,
477 the return type is still plain str.
478
Guido van Rossumb24569a2016-11-20 18:01:29 -0800479 At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700480
Guido van Rossumefa798d2016-08-23 11:01:50 -0700481 Type variables defined with covariant=True or contravariant=True
482 can be used do declare covariant or contravariant generic types.
483 See PEP 484 for more details. By default generic types are invariant
484 in all type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700485
486 Type variables can be introspected. e.g.:
487
488 T.__name__ == 'T'
489 T.__constraints__ == ()
490 T.__covariant__ == False
491 T.__contravariant__ = False
492 A.__constraints__ == (str, bytes)
493 """
494
Guido van Rossum4cefe742016-09-27 15:20:12 -0700495 __slots__ = ('__name__', '__bound__', '__constraints__',
496 '__covariant__', '__contravariant__')
497
498 def __init__(self, name, *constraints, bound=None,
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800499 covariant=False, contravariant=False):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700500 super().__init__(name, *constraints, bound=bound,
501 covariant=covariant, contravariant=contravariant)
502 self.__name__ = name
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700503 if covariant and contravariant:
Guido van Rossumefa798d2016-08-23 11:01:50 -0700504 raise ValueError("Bivariant types are not supported.")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700505 self.__covariant__ = bool(covariant)
506 self.__contravariant__ = bool(contravariant)
507 if constraints and bound is not None:
508 raise TypeError("Constraints cannot be combined with bound=...")
509 if constraints and len(constraints) == 1:
510 raise TypeError("A single constraint is not allowed")
511 msg = "TypeVar(name, constraint, ...): constraints must be types."
512 self.__constraints__ = tuple(_type_check(t, msg) for t in constraints)
513 if bound:
514 self.__bound__ = _type_check(bound, "Bound must be a type.")
515 else:
516 self.__bound__ = None
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700517
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700518 def _get_type_vars(self, tvars):
519 if self not in tvars:
520 tvars.append(self)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700521
522 def __repr__(self):
523 if self.__covariant__:
524 prefix = '+'
525 elif self.__contravariant__:
526 prefix = '-'
527 else:
528 prefix = '~'
529 return prefix + self.__name__
530
531 def __instancecheck__(self, instance):
532 raise TypeError("Type variables cannot be used with isinstance().")
533
534 def __subclasscheck__(self, cls):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700535 raise TypeError("Type variables cannot be used with issubclass().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700536
537
538# Some unconstrained type variables. These are used by the container types.
Guido van Rossumeb9aca32016-05-24 16:38:22 -0700539# (These are not for export.)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700540T = TypeVar('T') # Any type.
541KT = TypeVar('KT') # Key type.
542VT = TypeVar('VT') # Value type.
543T_co = TypeVar('T_co', covariant=True) # Any type covariant containers.
544V_co = TypeVar('V_co', covariant=True) # Any type covariant containers.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700545VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
546T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
547
548# A useful type variable with constraints. This represents string types.
Guido van Rossumeb9aca32016-05-24 16:38:22 -0700549# (This one *is* for export!)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700550AnyStr = TypeVar('AnyStr', bytes, str)
551
552
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700553def _replace_arg(arg, tvars, args):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800554 """An internal helper function: replace arg if it is a type variable
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700555 found in tvars with corresponding substitution from args or
556 with corresponding substitution sub-tree if arg is a generic type.
557 """
558
559 if tvars is None:
560 tvars = []
Guido van Rossum83ec3022017-01-17 20:43:28 -0800561 if hasattr(arg, '_subs_tree') and isinstance(arg, (GenericMeta, _TypingBase)):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700562 return arg._subs_tree(tvars, args)
563 if isinstance(arg, TypeVar):
564 for i, tvar in enumerate(tvars):
565 if arg == tvar:
566 return args[i]
567 return arg
568
569
Guido van Rossum83ec3022017-01-17 20:43:28 -0800570# Special typing constructs Union, Optional, Generic, Callable and Tuple
571# use three special attributes for internal bookkeeping of generic types:
572# * __parameters__ is a tuple of unique free type parameters of a generic
573# type, for example, Dict[T, T].__parameters__ == (T,);
574# * __origin__ keeps a reference to a type that was subscripted,
575# e.g., Union[T, int].__origin__ == Union;
576# * __args__ is a tuple of all arguments used in subscripting,
577# e.g., Dict[T, int].__args__ == (T, int).
578
579
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700580def _subs_tree(cls, tvars=None, args=None):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800581 """An internal helper function: calculate substitution tree
582 for generic cls after replacing its type parameters with
583 substitutions in tvars -> args (if any).
584 Repeat the same following __origin__'s.
585
586 Return a list of arguments with all possible substitutions
587 performed. Arguments that are generic classes themselves are represented
588 as tuples (so that no new classes are created by this function).
589 For example: _subs_tree(List[Tuple[int, T]][str]) == [(Tuple, int, str)]
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700590 """
591
592 if cls.__origin__ is None:
593 return cls
594 # Make of chain of origins (i.e. cls -> cls.__origin__)
595 current = cls.__origin__
596 orig_chain = []
597 while current.__origin__ is not None:
598 orig_chain.append(current)
599 current = current.__origin__
600 # Replace type variables in __args__ if asked ...
601 tree_args = []
602 for arg in cls.__args__:
603 tree_args.append(_replace_arg(arg, tvars, args))
604 # ... then continue replacing down the origin chain.
605 for ocls in orig_chain:
606 new_tree_args = []
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800607 for arg in ocls.__args__:
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700608 new_tree_args.append(_replace_arg(arg, ocls.__parameters__, tree_args))
609 tree_args = new_tree_args
610 return tree_args
611
612
613def _remove_dups_flatten(parameters):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800614 """An internal helper for Union creation and substitution: flatten Union's
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700615 among parameters, then remove duplicates and strict subclasses.
616 """
617
618 # Flatten out Union[Union[...], ...].
619 params = []
620 for p in parameters:
621 if isinstance(p, _Union) and p.__origin__ is Union:
622 params.extend(p.__args__)
623 elif isinstance(p, tuple) and len(p) > 0 and p[0] is Union:
624 params.extend(p[1:])
625 else:
626 params.append(p)
627 # Weed out strict duplicates, preserving the first of each occurrence.
628 all_params = set(params)
629 if len(all_params) < len(params):
630 new_params = []
631 for t in params:
632 if t in all_params:
633 new_params.append(t)
634 all_params.remove(t)
635 params = new_params
636 assert not all_params, all_params
637 # Weed out subclasses.
638 # E.g. Union[int, Employee, Manager] == Union[int, Employee].
639 # If object is present it will be sole survivor among proper classes.
640 # Never discard type variables.
641 # (In particular, Union[str, AnyStr] != AnyStr.)
642 all_params = set(params)
643 for t1 in params:
644 if not isinstance(t1, type):
645 continue
646 if any(isinstance(t2, type) and issubclass(t1, t2)
647 for t2 in all_params - {t1}
648 if not (isinstance(t2, GenericMeta) and
649 t2.__origin__ is not None)):
650 all_params.remove(t1)
651 return tuple(t for t in params if t in all_params)
652
653
654def _check_generic(cls, parameters):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800655 # Check correct count for parameters of a generic cls (internal helper).
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700656 if not cls.__parameters__:
657 raise TypeError("%s is not a generic class" % repr(cls))
658 alen = len(parameters)
659 elen = len(cls.__parameters__)
660 if alen != elen:
661 raise TypeError("Too %s parameters for %s; actual %s, expected %s" %
662 ("many" if alen > elen else "few", repr(cls), alen, elen))
663
664
Guido van Rossum9b107562016-11-09 13:23:04 -0800665_cleanups = []
666
667
Guido van Rossum4cefe742016-09-27 15:20:12 -0700668def _tp_cache(func):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800669 """Internal wrapper caching __getitem__ of generic types with a fallback to
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700670 original function for non-hashable arguments.
671 """
672
Guido van Rossum4cefe742016-09-27 15:20:12 -0700673 cached = functools.lru_cache()(func)
Guido van Rossum9b107562016-11-09 13:23:04 -0800674 _cleanups.append(cached.cache_clear)
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800675
Guido van Rossum4cefe742016-09-27 15:20:12 -0700676 @functools.wraps(func)
677 def inner(*args, **kwds):
678 try:
679 return cached(*args, **kwds)
680 except TypeError:
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700681 pass # All real errors (not unhashable args) are raised below.
Guido van Rossum4cefe742016-09-27 15:20:12 -0700682 return func(*args, **kwds)
683 return inner
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700684
685
Guido van Rossum4cefe742016-09-27 15:20:12 -0700686class _Union(_FinalTypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700687 """Union type; Union[X, Y] means either X or Y.
688
689 To define a union, use e.g. Union[int, str]. Details:
690
691 - The arguments must be types and there must be at least one.
692
693 - None as an argument is a special case and is replaced by
694 type(None).
695
696 - Unions of unions are flattened, e.g.::
697
698 Union[Union[int, str], float] == Union[int, str, float]
699
700 - Unions of a single argument vanish, e.g.::
701
702 Union[int] == int # The constructor actually returns int
703
704 - Redundant arguments are skipped, e.g.::
705
706 Union[int, str, int] == Union[int, str]
707
708 - When comparing unions, the argument order is ignored, e.g.::
709
710 Union[int, str] == Union[str, int]
711
712 - When two arguments have a subclass relationship, the least
713 derived argument is kept, e.g.::
714
715 class Employee: pass
716 class Manager(Employee): pass
717 Union[int, Employee, Manager] == Union[int, Employee]
718 Union[Manager, int, Employee] == Union[int, Employee]
719 Union[Employee, Manager] == Employee
720
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700721 - Similar for object::
722
723 Union[int, object] == object
724
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700725 - You cannot subclass or instantiate a union.
726
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700727 - You can use Optional[X] as a shorthand for Union[X, None].
728 """
729
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700730 __slots__ = ('__parameters__', '__args__', '__origin__', '__tree_hash__')
Guido van Rossum4cefe742016-09-27 15:20:12 -0700731
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700732 def __new__(cls, parameters=None, origin=None, *args, _root=False):
733 self = super().__new__(cls, parameters, origin, *args, _root=_root)
734 if origin is None:
735 self.__parameters__ = None
736 self.__args__ = None
737 self.__origin__ = None
738 self.__tree_hash__ = hash(frozenset(('Union',)))
Guido van Rossum4cefe742016-09-27 15:20:12 -0700739 return self
740 if not isinstance(parameters, tuple):
741 raise TypeError("Expected parameters=<tuple>")
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700742 if origin is Union:
743 parameters = _remove_dups_flatten(parameters)
744 # It's not a union if there's only one type left.
745 if len(parameters) == 1:
746 return parameters[0]
747 self.__parameters__ = _type_vars(parameters)
748 self.__args__ = parameters
749 self.__origin__ = origin
750 # Pre-calculate the __hash__ on instantiation.
751 # This improves speed for complex substitutions.
752 subs_tree = self._subs_tree()
753 if isinstance(subs_tree, tuple):
754 self.__tree_hash__ = hash(frozenset(subs_tree))
755 else:
756 self.__tree_hash__ = hash(subs_tree)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700757 return self
758
759 def _eval_type(self, globalns, localns):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700760 if self.__args__ is None:
Guido van Rossum4cefe742016-09-27 15:20:12 -0700761 return self
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700762 ev_args = tuple(_eval_type(t, globalns, localns) for t in self.__args__)
763 ev_origin = _eval_type(self.__origin__, globalns, localns)
764 if ev_args == self.__args__ and ev_origin == self.__origin__:
765 # Everything is already evaluated.
766 return self
767 return self.__class__(ev_args, ev_origin, _root=True)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700768
769 def _get_type_vars(self, tvars):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700770 if self.__origin__ and self.__parameters__:
771 _get_type_vars(self.__parameters__, tvars)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700772
773 def __repr__(self):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700774 if self.__origin__ is None:
775 return super().__repr__()
776 tree = self._subs_tree()
777 if not isinstance(tree, tuple):
778 return repr(tree)
779 return tree[0]._tree_repr(tree)
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700780
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700781 def _tree_repr(self, tree):
782 arg_list = []
783 for arg in tree[1:]:
784 if not isinstance(arg, tuple):
785 arg_list.append(_type_repr(arg))
786 else:
787 arg_list.append(arg[0]._tree_repr(arg))
788 return super().__repr__() + '[%s]' % ', '.join(arg_list)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700789
790 @_tp_cache
791 def __getitem__(self, parameters):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700792 if parameters == ():
793 raise TypeError("Cannot take a Union of no types.")
794 if not isinstance(parameters, tuple):
795 parameters = (parameters,)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700796 if self.__origin__ is None:
797 msg = "Union[arg, ...]: each arg must be a type."
798 else:
799 msg = "Parameters to generic types must be types."
800 parameters = tuple(_type_check(p, msg) for p in parameters)
801 if self is not Union:
802 _check_generic(self, parameters)
803 return self.__class__(parameters, origin=self, _root=True)
804
805 def _subs_tree(self, tvars=None, args=None):
806 if self is Union:
807 return Union # Nothing to substitute
808 tree_args = _subs_tree(self, tvars, args)
809 tree_args = _remove_dups_flatten(tree_args)
810 if len(tree_args) == 1:
811 return tree_args[0] # Union of a single type is that type
812 return (Union,) + tree_args
Guido van Rossum4cefe742016-09-27 15:20:12 -0700813
814 def __eq__(self, other):
Guido van Rossum83ec3022017-01-17 20:43:28 -0800815 if isinstance(other, _Union):
816 return self.__tree_hash__ == other.__tree_hash__
817 elif self is not Union:
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700818 return self._subs_tree() == other
Guido van Rossum83ec3022017-01-17 20:43:28 -0800819 else:
820 return self is other
Guido van Rossum4cefe742016-09-27 15:20:12 -0700821
822 def __hash__(self):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700823 return self.__tree_hash__
Guido van Rossum4cefe742016-09-27 15:20:12 -0700824
825 def __instancecheck__(self, obj):
826 raise TypeError("Unions cannot be used with isinstance().")
827
828 def __subclasscheck__(self, cls):
829 raise TypeError("Unions cannot be used with issubclass().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700830
831
Guido van Rossum4cefe742016-09-27 15:20:12 -0700832Union = _Union(_root=True)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700833
834
Guido van Rossum4cefe742016-09-27 15:20:12 -0700835class _Optional(_FinalTypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700836 """Optional type.
837
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700838 Optional[X] is equivalent to Union[X, None].
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700839 """
840
Guido van Rossumd70fe632015-08-05 12:11:06 +0200841 __slots__ = ()
842
Guido van Rossum4cefe742016-09-27 15:20:12 -0700843 @_tp_cache
844 def __getitem__(self, arg):
845 arg = _type_check(arg, "Optional[t] requires a single type.")
846 return Union[arg, type(None)]
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700847
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700848
Guido van Rossum4cefe742016-09-27 15:20:12 -0700849Optional = _Optional(_root=True)
850
851
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700852def _next_in_mro(cls):
853 """Helper for Generic.__new__.
854
855 Returns the class after the last occurrence of Generic or
856 Generic[...] in cls.__mro__.
857 """
858 next_in_mro = object
859 # Look for the last occurrence of Generic or Generic[...].
860 for i, c in enumerate(cls.__mro__[:-1]):
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +0200861 if isinstance(c, GenericMeta) and c._gorg is Generic:
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800862 next_in_mro = cls.__mro__[i + 1]
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700863 return next_in_mro
864
865
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700866def _make_subclasshook(cls):
867 """Construct a __subclasshook__ callable that incorporates
868 the associated __extra__ class in subclass checks performed
869 against cls.
870 """
871 if isinstance(cls.__extra__, abc.ABCMeta):
872 # The logic mirrors that of ABCMeta.__subclasscheck__.
873 # Registered classes need not be checked here because
874 # cls and its extra share the same _abc_registry.
875 def __extrahook__(subclass):
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700876 res = cls.__extra__.__subclasshook__(subclass)
877 if res is not NotImplemented:
878 return res
879 if cls.__extra__ in subclass.__mro__:
880 return True
881 for scls in cls.__extra__.__subclasses__():
882 if isinstance(scls, GenericMeta):
883 continue
884 if issubclass(subclass, scls):
885 return True
886 return NotImplemented
887 else:
888 # For non-ABC extras we'll just call issubclass().
889 def __extrahook__(subclass):
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700890 if cls.__extra__ and issubclass(subclass, cls.__extra__):
891 return True
892 return NotImplemented
893 return __extrahook__
894
895
Guido van Rossum61f0a022016-11-29 09:46:21 -0800896def _no_slots_copy(dct):
897 """Internal helper: copy class __dict__ and clean slots class variables.
898 (They will be re-created if necessary by normal class machinery.)
899 """
900 dict_copy = dict(dct)
901 if '__slots__' in dict_copy:
902 for slot in dict_copy['__slots__']:
903 dict_copy.pop(slot, None)
904 return dict_copy
905
906
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700907class GenericMeta(TypingMeta, abc.ABCMeta):
Guido van Rossum83ec3022017-01-17 20:43:28 -0800908 """Metaclass for generic types.
909
910 This is a metaclass for typing.Generic and generic ABCs defined in
911 typing module. User defined subclasses of GenericMeta can override
912 __new__ and invoke super().__new__. Note that GenericMeta.__new__
913 has strict rules on what is allowed in its bases argument:
914 * plain Generic is disallowed in bases;
915 * Generic[...] should appear in bases at most once;
916 * if Generic[...] is present, then it should list all type variables
917 that appear in other bases.
918 In addition, type of all generic bases is erased, e.g., C[int] is
919 stripped to plain C.
920 """
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700921
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700922 def __new__(cls, name, bases, namespace,
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700923 tvars=None, args=None, origin=None, extra=None, orig_bases=None):
Guido van Rossum83ec3022017-01-17 20:43:28 -0800924 """Create a new generic class. GenericMeta.__new__ accepts
925 keyword arguments that are used for internal bookkeeping, therefore
926 an override should pass unused keyword arguments to super().
927 """
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700928 if tvars is not None:
929 # Called from __getitem__() below.
930 assert origin is not None
931 assert all(isinstance(t, TypeVar) for t in tvars), tvars
932 else:
933 # Called from class statement.
934 assert tvars is None, tvars
935 assert args is None, args
936 assert origin is None, origin
937
938 # Get the full set of tvars from the bases.
939 tvars = _type_vars(bases)
940 # Look for Generic[T1, ..., Tn].
941 # If found, tvars must be a subset of it.
942 # If not found, tvars is it.
943 # Also check for and reject plain Generic,
944 # and reject multiple Generic[...].
945 gvars = None
946 for base in bases:
947 if base is Generic:
948 raise TypeError("Cannot inherit from plain Generic")
949 if (isinstance(base, GenericMeta) and
950 base.__origin__ is Generic):
951 if gvars is not None:
952 raise TypeError(
953 "Cannot inherit from Generic[...] multiple types.")
954 gvars = base.__parameters__
955 if gvars is None:
956 gvars = tvars
957 else:
958 tvarset = set(tvars)
959 gvarset = set(gvars)
960 if not tvarset <= gvarset:
961 raise TypeError(
962 "Some type variables (%s) "
963 "are not listed in Generic[%s]" %
964 (", ".join(str(t) for t in tvars if t not in gvarset),
965 ", ".join(str(g) for g in gvars)))
966 tvars = gvars
967
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700968 initial_bases = bases
969 if extra is not None and type(extra) is abc.ABCMeta and extra not in bases:
970 bases = (extra,) + bases
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +0200971 bases = tuple(b._gorg if isinstance(b, GenericMeta) else b for b in bases)
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700972
973 # remove bare Generic from bases if there are other generic bases
974 if any(isinstance(b, GenericMeta) and b is not Generic for b in bases):
975 bases = tuple(b for b in bases if b is not Generic)
Ivan Levkivskyi29bc1932017-12-05 03:43:58 +0100976 namespace.update({'__origin__': origin, '__extra__': extra,
977 '_gorg': None if not origin else origin._gorg})
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700978 self = super().__new__(cls, name, bases, namespace, _root=True)
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +0200979 super(GenericMeta, self).__setattr__('_gorg',
980 self if not origin else origin._gorg)
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700981 self.__parameters__ = tvars
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700982 # Be prepared that GenericMeta will be subclassed by TupleMeta
983 # and CallableMeta, those two allow ..., (), or [] in __args___.
984 self.__args__ = tuple(... if a is _TypingEllipsis else
985 () if a is _TypingEmpty else
986 a for a in args) if args else None
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700987 # Speed hack (https://github.com/python/typing/issues/196).
988 self.__next_in_mro__ = _next_in_mro(self)
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700989 # Preserve base classes on subclassing (__bases__ are type erased now).
990 if orig_bases is None:
991 self.__orig_bases__ = initial_bases
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700992
993 # This allows unparameterized generic collections to be used
994 # with issubclass() and isinstance() in the same way as their
995 # collections.abc counterparts (e.g., isinstance([], Iterable)).
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800996 if (
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800997 '__subclasshook__' not in namespace and extra or
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100998 # allow overriding
999 getattr(self.__subclasshook__, '__name__', '') == '__extrahook__'
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001000 ):
Guido van Rossume2592672016-10-08 20:27:22 -07001001 self.__subclasshook__ = _make_subclasshook(self)
Guido van Rossumb47c9d22016-10-03 08:40:50 -07001002 if isinstance(extra, abc.ABCMeta):
1003 self._abc_registry = extra._abc_registry
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001004 self._abc_cache = extra._abc_cache
1005 elif origin is not None:
1006 self._abc_registry = origin._abc_registry
1007 self._abc_cache = origin._abc_cache
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001008
1009 if origin and hasattr(origin, '__qualname__'): # Fix for Python 3.2.
1010 self.__qualname__ = origin.__qualname__
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001011 self.__tree_hash__ = (hash(self._subs_tree()) if origin else
1012 super(GenericMeta, self).__hash__())
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001013 return self
1014
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001015 # _abc_negative_cache and _abc_negative_cache_version
1016 # realised as descriptors, since GenClass[t1, t2, ...] always
1017 # share subclass info with GenClass.
1018 # This is an important memory optimization.
1019 @property
1020 def _abc_negative_cache(self):
1021 if isinstance(self.__extra__, abc.ABCMeta):
1022 return self.__extra__._abc_negative_cache
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001023 return self._gorg._abc_generic_negative_cache
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001024
1025 @_abc_negative_cache.setter
1026 def _abc_negative_cache(self, value):
1027 if self.__origin__ is None:
1028 if isinstance(self.__extra__, abc.ABCMeta):
1029 self.__extra__._abc_negative_cache = value
1030 else:
1031 self._abc_generic_negative_cache = value
1032
1033 @property
1034 def _abc_negative_cache_version(self):
1035 if isinstance(self.__extra__, abc.ABCMeta):
1036 return self.__extra__._abc_negative_cache_version
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001037 return self._gorg._abc_generic_negative_cache_version
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001038
1039 @_abc_negative_cache_version.setter
1040 def _abc_negative_cache_version(self, value):
1041 if self.__origin__ is None:
1042 if isinstance(self.__extra__, abc.ABCMeta):
1043 self.__extra__._abc_negative_cache_version = value
1044 else:
1045 self._abc_generic_negative_cache_version = value
1046
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001047 def _get_type_vars(self, tvars):
1048 if self.__origin__ and self.__parameters__:
1049 _get_type_vars(self.__parameters__, tvars)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001050
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001051 def _eval_type(self, globalns, localns):
1052 ev_origin = (self.__origin__._eval_type(globalns, localns)
1053 if self.__origin__ else None)
1054 ev_args = tuple(_eval_type(a, globalns, localns) for a
1055 in self.__args__) if self.__args__ else None
1056 if ev_origin == self.__origin__ and ev_args == self.__args__:
1057 return self
1058 return self.__class__(self.__name__,
1059 self.__bases__,
Guido van Rossum61f0a022016-11-29 09:46:21 -08001060 _no_slots_copy(self.__dict__),
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001061 tvars=_type_vars(ev_args) if ev_args else None,
1062 args=ev_args,
1063 origin=ev_origin,
1064 extra=self.__extra__,
1065 orig_bases=self.__orig_bases__)
1066
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001067 def __repr__(self):
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001068 if self.__origin__ is None:
1069 return super().__repr__()
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001070 return self._tree_repr(self._subs_tree())
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001071
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001072 def _tree_repr(self, tree):
1073 arg_list = []
1074 for arg in tree[1:]:
1075 if arg == ():
1076 arg_list.append('()')
1077 elif not isinstance(arg, tuple):
1078 arg_list.append(_type_repr(arg))
1079 else:
1080 arg_list.append(arg[0]._tree_repr(arg))
1081 return super().__repr__() + '[%s]' % ', '.join(arg_list)
1082
1083 def _subs_tree(self, tvars=None, args=None):
1084 if self.__origin__ is None:
1085 return self
1086 tree_args = _subs_tree(self, tvars, args)
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001087 return (self._gorg,) + tuple(tree_args)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001088
1089 def __eq__(self, other):
1090 if not isinstance(other, GenericMeta):
1091 return NotImplemented
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001092 if self.__origin__ is None or other.__origin__ is None:
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001093 return self is other
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001094 return self.__tree_hash__ == other.__tree_hash__
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001095
1096 def __hash__(self):
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001097 return self.__tree_hash__
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001098
Guido van Rossum4cefe742016-09-27 15:20:12 -07001099 @_tp_cache
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001100 def __getitem__(self, params):
1101 if not isinstance(params, tuple):
1102 params = (params,)
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001103 if not params and self._gorg is not Tuple:
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001104 raise TypeError(
1105 "Parameter list to %s[...] cannot be empty" % _qualname(self))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001106 msg = "Parameters to generic types must be types."
1107 params = tuple(_type_check(p, msg) for p in params)
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001108 if self is Generic:
1109 # Generic can only be subscripted with unique type variables.
1110 if not all(isinstance(p, TypeVar) for p in params):
1111 raise TypeError(
1112 "Parameters to Generic[...] must all be type variables")
Guido van Rossumd70fe632015-08-05 12:11:06 +02001113 if len(set(params)) != len(params):
Guido van Rossum1b669102015-09-04 12:15:54 -07001114 raise TypeError(
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001115 "Parameters to Generic[...] must all be unique")
1116 tvars = params
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001117 args = params
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001118 elif self in (Tuple, Callable):
1119 tvars = _type_vars(params)
1120 args = params
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001121 elif self is _Protocol:
1122 # _Protocol is internal, don't check anything.
1123 tvars = params
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001124 args = params
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001125 elif self.__origin__ in (Generic, _Protocol):
1126 # Can't subscript Generic[...] or _Protocol[...].
1127 raise TypeError("Cannot subscript already-subscripted %s" %
1128 repr(self))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001129 else:
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001130 # Subscripting a regular Generic subclass.
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001131 _check_generic(self, params)
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001132 tvars = _type_vars(params)
1133 args = params
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001134
1135 prepend = (self,) if self.__origin__ is None else ()
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001136 return self.__class__(self.__name__,
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001137 prepend + self.__bases__,
Guido van Rossum61f0a022016-11-29 09:46:21 -08001138 _no_slots_copy(self.__dict__),
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001139 tvars=tvars,
1140 args=args,
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001141 origin=self,
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001142 extra=self.__extra__,
1143 orig_bases=self.__orig_bases__)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001144
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001145 def __subclasscheck__(self, cls):
1146 if self.__origin__ is not None:
1147 if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools']:
1148 raise TypeError("Parameterized generics cannot be used with class "
1149 "or instance checks")
1150 return False
1151 if self is Generic:
1152 raise TypeError("Class %r cannot be used with class "
1153 "or instance checks" % self)
1154 return super().__subclasscheck__(cls)
1155
Guido van Rossum1b669102015-09-04 12:15:54 -07001156 def __instancecheck__(self, instance):
1157 # Since we extend ABC.__subclasscheck__ and
1158 # ABC.__instancecheck__ inlines the cache checking done by the
1159 # latter, we must extend __instancecheck__ too. For simplicity
1160 # we just skip the cache check -- instance checks for generic
1161 # classes are supposed to be rare anyways.
Guido van Rossumb47c9d22016-10-03 08:40:50 -07001162 return issubclass(instance.__class__, self)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001163
Ivan Levkivskyiabb3b8a2017-02-24 04:03:28 +01001164 def __setattr__(self, attr, value):
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001165 # We consider all the subscripted generics as proxies for original class
Ivan Levkivskyi365cb5b2017-02-24 18:28:26 +01001166 if (
1167 attr.startswith('__') and attr.endswith('__') or
Ivan Levkivskyi29bc1932017-12-05 03:43:58 +01001168 attr.startswith('_abc_') or
1169 self._gorg is None # The class is not fully created, see #typing/506
Ivan Levkivskyi365cb5b2017-02-24 18:28:26 +01001170 ):
Ivan Levkivskyiabb3b8a2017-02-24 04:03:28 +01001171 super(GenericMeta, self).__setattr__(attr, value)
1172 else:
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001173 super(GenericMeta, self._gorg).__setattr__(attr, value)
Ivan Levkivskyiabb3b8a2017-02-24 04:03:28 +01001174
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001175
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001176# Prevent checks for Generic to crash when defining Generic.
1177Generic = None
1178
1179
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001180def _generic_new(base_cls, cls, *args, **kwds):
1181 # Assure type is erased on instantiation,
1182 # but attempt to store it in __orig_class__
1183 if cls.__origin__ is None:
1184 return base_cls.__new__(cls)
1185 else:
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001186 origin = cls._gorg
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001187 obj = base_cls.__new__(origin)
1188 try:
1189 obj.__orig_class__ = cls
1190 except AttributeError:
1191 pass
1192 obj.__init__(*args, **kwds)
1193 return obj
1194
1195
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001196class Generic(metaclass=GenericMeta):
1197 """Abstract base class for generic types.
1198
Guido van Rossumb24569a2016-11-20 18:01:29 -08001199 A generic type is typically declared by inheriting from
1200 this class parameterized with one or more type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001201 For example, a generic mapping type might be defined as::
1202
1203 class Mapping(Generic[KT, VT]):
1204 def __getitem__(self, key: KT) -> VT:
1205 ...
1206 # Etc.
1207
1208 This class can then be used as follows::
1209
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001210 def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001211 try:
1212 return mapping[key]
1213 except KeyError:
1214 return default
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001215 """
1216
Guido van Rossumd70fe632015-08-05 12:11:06 +02001217 __slots__ = ()
1218
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001219 def __new__(cls, *args, **kwds):
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001220 if cls._gorg is Generic:
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001221 raise TypeError("Type Generic cannot be instantiated; "
1222 "it can be used only as a base class")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001223 return _generic_new(cls.__next_in_mro__, cls, *args, **kwds)
1224
1225
1226class _TypingEmpty:
Guido van Rossumb24569a2016-11-20 18:01:29 -08001227 """Internal placeholder for () or []. Used by TupleMeta and CallableMeta
1228 to allow empty list/tuple in specific places, without allowing them
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001229 to sneak in where prohibited.
1230 """
1231
1232
1233class _TypingEllipsis:
Guido van Rossumb24569a2016-11-20 18:01:29 -08001234 """Internal placeholder for ... (ellipsis)."""
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001235
1236
1237class TupleMeta(GenericMeta):
Guido van Rossumb24569a2016-11-20 18:01:29 -08001238 """Metaclass for Tuple (internal)."""
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001239
1240 @_tp_cache
1241 def __getitem__(self, parameters):
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001242 if self.__origin__ is not None or self._gorg is not Tuple:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001243 # Normal generic rules apply if this is not the first subscription
1244 # or a subscription of a subclass.
1245 return super().__getitem__(parameters)
1246 if parameters == ():
1247 return super().__getitem__((_TypingEmpty,))
1248 if not isinstance(parameters, tuple):
1249 parameters = (parameters,)
1250 if len(parameters) == 2 and parameters[1] is ...:
1251 msg = "Tuple[t, ...]: t must be a type."
1252 p = _type_check(parameters[0], msg)
1253 return super().__getitem__((p, _TypingEllipsis))
1254 msg = "Tuple[t0, t1, ...]: each t must be a type."
1255 parameters = tuple(_type_check(p, msg) for p in parameters)
1256 return super().__getitem__(parameters)
1257
1258 def __instancecheck__(self, obj):
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001259 if self.__args__ is None:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001260 return isinstance(obj, tuple)
1261 raise TypeError("Parameterized Tuple cannot be used "
1262 "with isinstance().")
1263
1264 def __subclasscheck__(self, cls):
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001265 if self.__args__ is None:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001266 return issubclass(cls, tuple)
1267 raise TypeError("Parameterized Tuple cannot be used "
1268 "with issubclass().")
1269
1270
1271class Tuple(tuple, extra=tuple, metaclass=TupleMeta):
1272 """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
1273
1274 Example: Tuple[T1, T2] is a tuple of two elements corresponding
1275 to type variables T1 and T2. Tuple[int, float, str] is a tuple
1276 of an int, a float and a string.
1277
1278 To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
1279 """
1280
1281 __slots__ = ()
1282
1283 def __new__(cls, *args, **kwds):
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001284 if cls._gorg is Tuple:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001285 raise TypeError("Type Tuple cannot be instantiated; "
1286 "use tuple() instead")
1287 return _generic_new(tuple, cls, *args, **kwds)
1288
1289
1290class CallableMeta(GenericMeta):
Guido van Rossumb24569a2016-11-20 18:01:29 -08001291 """Metaclass for Callable (internal)."""
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001292
1293 def __repr__(self):
1294 if self.__origin__ is None:
1295 return super().__repr__()
1296 return self._tree_repr(self._subs_tree())
1297
1298 def _tree_repr(self, tree):
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001299 if self._gorg is not Callable:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001300 return super()._tree_repr(tree)
1301 # For actual Callable (not its subclass) we override
1302 # super()._tree_repr() for nice formatting.
1303 arg_list = []
1304 for arg in tree[1:]:
Guido van Rossum991d14f2016-11-09 13:12:51 -08001305 if not isinstance(arg, tuple):
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001306 arg_list.append(_type_repr(arg))
1307 else:
1308 arg_list.append(arg[0]._tree_repr(arg))
Guido van Rossum991d14f2016-11-09 13:12:51 -08001309 if arg_list[0] == '...':
1310 return repr(tree[0]) + '[..., %s]' % arg_list[1]
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001311 return (repr(tree[0]) +
1312 '[[%s], %s]' % (', '.join(arg_list[:-1]), arg_list[-1]))
1313
1314 def __getitem__(self, parameters):
Guido van Rossumb24569a2016-11-20 18:01:29 -08001315 """A thin wrapper around __getitem_inner__ to provide the latter
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001316 with hashable arguments to improve speed.
1317 """
1318
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001319 if self.__origin__ is not None or self._gorg is not Callable:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001320 return super().__getitem__(parameters)
1321 if not isinstance(parameters, tuple) or len(parameters) != 2:
1322 raise TypeError("Callable must be used as "
1323 "Callable[[arg, ...], result].")
1324 args, result = parameters
Guido van Rossum991d14f2016-11-09 13:12:51 -08001325 if args is Ellipsis:
1326 parameters = (Ellipsis, result)
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001327 else:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001328 if not isinstance(args, list):
1329 raise TypeError("Callable[args, result]: args must be a list."
1330 " Got %.100r." % (args,))
Guido van Rossum991d14f2016-11-09 13:12:51 -08001331 parameters = (tuple(args), result)
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001332 return self.__getitem_inner__(parameters)
1333
1334 @_tp_cache
1335 def __getitem_inner__(self, parameters):
Guido van Rossum991d14f2016-11-09 13:12:51 -08001336 args, result = parameters
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001337 msg = "Callable[args, result]: result must be a type."
1338 result = _type_check(result, msg)
Guido van Rossum991d14f2016-11-09 13:12:51 -08001339 if args is Ellipsis:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001340 return super().__getitem__((_TypingEllipsis, result))
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001341 msg = "Callable[[arg, ...], result]: each arg must be a type."
1342 args = tuple(_type_check(arg, msg) for arg in args)
1343 parameters = args + (result,)
1344 return super().__getitem__(parameters)
1345
1346
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001347class Callable(extra=collections_abc.Callable, metaclass=CallableMeta):
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001348 """Callable type; Callable[[int], str] is a function of (int) -> str.
1349
1350 The subscription syntax must always be used with exactly two
1351 values: the argument list and the return type. The argument list
Guido van Rossumb24569a2016-11-20 18:01:29 -08001352 must be a list of types or ellipsis; the return type must be a single type.
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001353
1354 There is no syntax to indicate optional or keyword arguments,
1355 such function types are rarely used as callback types.
1356 """
1357
1358 __slots__ = ()
1359
1360 def __new__(cls, *args, **kwds):
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001361 if cls._gorg is Callable:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001362 raise TypeError("Type Callable cannot be instantiated; "
1363 "use a non-abstract subclass instead")
1364 return _generic_new(cls.__next_in_mro__, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001365
1366
Guido van Rossum4cefe742016-09-27 15:20:12 -07001367class _ClassVar(_FinalTypingBase, _root=True):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001368 """Special type construct to mark class variables.
1369
1370 An annotation wrapped in ClassVar indicates that a given
1371 attribute is intended to be used as a class variable and
1372 should not be set on instances of that class. Usage::
1373
1374 class Starship:
1375 stats: ClassVar[Dict[str, int]] = {} # class variable
1376 damage: int = 10 # instance variable
1377
1378 ClassVar accepts only types and cannot be further subscribed.
1379
1380 Note that ClassVar is not a class itself, and should not
1381 be used with isinstance() or issubclass().
1382 """
1383
Guido van Rossum4cefe742016-09-27 15:20:12 -07001384 __slots__ = ('__type__',)
1385
1386 def __init__(self, tp=None, **kwds):
1387 self.__type__ = tp
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001388
1389 def __getitem__(self, item):
1390 cls = type(self)
1391 if self.__type__ is None:
1392 return cls(_type_check(item,
Guido van Rossum4cefe742016-09-27 15:20:12 -07001393 '{} accepts only single type.'.format(cls.__name__[1:])),
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001394 _root=True)
1395 raise TypeError('{} cannot be further subscripted'
1396 .format(cls.__name__[1:]))
1397
1398 def _eval_type(self, globalns, localns):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001399 new_tp = _eval_type(self.__type__, globalns, localns)
1400 if new_tp == self.__type__:
1401 return self
1402 return type(self)(new_tp, _root=True)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001403
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001404 def __repr__(self):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001405 r = super().__repr__()
1406 if self.__type__ is not None:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001407 r += '[{}]'.format(_type_repr(self.__type__))
Guido van Rossum4cefe742016-09-27 15:20:12 -07001408 return r
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001409
1410 def __hash__(self):
1411 return hash((type(self).__name__, self.__type__))
1412
1413 def __eq__(self, other):
1414 if not isinstance(other, _ClassVar):
1415 return NotImplemented
1416 if self.__type__ is not None:
1417 return self.__type__ == other.__type__
1418 return self is other
1419
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001420
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001421ClassVar = _ClassVar(_root=True)
1422
1423
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001424def cast(typ, val):
1425 """Cast a value to a type.
1426
1427 This returns the value unchanged. To the type checker this
1428 signals that the return value has the designated type, but at
1429 runtime we intentionally don't check anything (we want this
1430 to be as fast as possible).
1431 """
1432 return val
1433
1434
1435def _get_defaults(func):
1436 """Internal helper to extract the default arguments, by name."""
Guido van Rossum991d14f2016-11-09 13:12:51 -08001437 try:
1438 code = func.__code__
1439 except AttributeError:
1440 # Some built-in functions don't have __code__, __defaults__, etc.
1441 return {}
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001442 pos_count = code.co_argcount
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001443 arg_names = code.co_varnames
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001444 arg_names = arg_names[:pos_count]
1445 defaults = func.__defaults__ or ()
1446 kwdefaults = func.__kwdefaults__
1447 res = dict(kwdefaults) if kwdefaults else {}
1448 pos_offset = pos_count - len(defaults)
1449 for name, value in zip(arg_names[pos_offset:], defaults):
1450 assert name not in res
1451 res[name] = value
1452 return res
1453
1454
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001455_allowed_types = (types.FunctionType, types.BuiltinFunctionType,
1456 types.MethodType, types.ModuleType,
Ivan Levkivskyif06e0212017-05-02 19:14:07 +02001457 WrapperDescriptorType, MethodWrapperType, MethodDescriptorType)
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001458
1459
Guido van Rossum991d14f2016-11-09 13:12:51 -08001460def get_type_hints(obj, globalns=None, localns=None):
1461 """Return type hints for an object.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001462
Guido van Rossum991d14f2016-11-09 13:12:51 -08001463 This is often the same as obj.__annotations__, but it handles
1464 forward references encoded as string literals, and if necessary
1465 adds Optional[t] if a default value equal to None is set.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001466
Guido van Rossum991d14f2016-11-09 13:12:51 -08001467 The argument may be a module, class, method, or function. The annotations
1468 are returned as a dictionary. For classes, annotations include also
1469 inherited members.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001470
Guido van Rossum991d14f2016-11-09 13:12:51 -08001471 TypeError is raised if the argument is not of a type that can contain
1472 annotations, and an empty dictionary is returned if no annotations are
1473 present.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001474
Guido van Rossum991d14f2016-11-09 13:12:51 -08001475 BEWARE -- the behavior of globalns and localns is counterintuitive
1476 (unless you are familiar with how eval() and exec() work). The
1477 search order is locals first, then globals.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001478
Guido van Rossum991d14f2016-11-09 13:12:51 -08001479 - If no dict arguments are passed, an attempt is made to use the
Łukasz Langaf350a262017-09-14 14:33:00 -04001480 globals from obj (or the respective module's globals for classes),
1481 and these are also used as the locals. If the object does not appear
1482 to have globals, an empty dictionary is used.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001483
Guido van Rossum991d14f2016-11-09 13:12:51 -08001484 - If one dict argument is passed, it is used for both globals and
1485 locals.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001486
Guido van Rossum991d14f2016-11-09 13:12:51 -08001487 - If two dict arguments are passed, they specify globals and
1488 locals, respectively.
1489 """
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001490
Guido van Rossum991d14f2016-11-09 13:12:51 -08001491 if getattr(obj, '__no_type_check__', None):
1492 return {}
Guido van Rossum991d14f2016-11-09 13:12:51 -08001493 # Classes require a special treatment.
1494 if isinstance(obj, type):
1495 hints = {}
1496 for base in reversed(obj.__mro__):
Łukasz Langaf350a262017-09-14 14:33:00 -04001497 if globalns is None:
1498 base_globals = sys.modules[base.__module__].__dict__
1499 else:
1500 base_globals = globalns
Guido van Rossum991d14f2016-11-09 13:12:51 -08001501 ann = base.__dict__.get('__annotations__', {})
1502 for name, value in ann.items():
1503 if value is None:
1504 value = type(None)
1505 if isinstance(value, str):
1506 value = _ForwardRef(value)
Łukasz Langaf350a262017-09-14 14:33:00 -04001507 value = _eval_type(value, base_globals, localns)
Guido van Rossum991d14f2016-11-09 13:12:51 -08001508 hints[name] = value
1509 return hints
Łukasz Langaf350a262017-09-14 14:33:00 -04001510
1511 if globalns is None:
1512 if isinstance(obj, types.ModuleType):
1513 globalns = obj.__dict__
1514 else:
1515 globalns = getattr(obj, '__globals__', {})
1516 if localns is None:
1517 localns = globalns
1518 elif localns is None:
1519 localns = globalns
Guido van Rossum991d14f2016-11-09 13:12:51 -08001520 hints = getattr(obj, '__annotations__', None)
1521 if hints is None:
1522 # Return empty annotations for something that _could_ have them.
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001523 if isinstance(obj, _allowed_types):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001524 return {}
Guido van Rossum991d14f2016-11-09 13:12:51 -08001525 else:
1526 raise TypeError('{!r} is not a module, class, method, '
1527 'or function.'.format(obj))
1528 defaults = _get_defaults(obj)
1529 hints = dict(hints)
1530 for name, value in hints.items():
1531 if value is None:
1532 value = type(None)
1533 if isinstance(value, str):
1534 value = _ForwardRef(value)
1535 value = _eval_type(value, globalns, localns)
1536 if name in defaults and defaults[name] is None:
1537 value = Optional[value]
1538 hints[name] = value
1539 return hints
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001540
1541
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001542def no_type_check(arg):
1543 """Decorator to indicate that annotations are not type hints.
1544
1545 The argument must be a class or function; if it is a class, it
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001546 applies recursively to all methods and classes defined in that class
1547 (but not to methods defined in its superclasses or subclasses).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001548
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001549 This mutates the function(s) or class(es) in place.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001550 """
1551 if isinstance(arg, type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001552 arg_attrs = arg.__dict__.copy()
1553 for attr, val in arg.__dict__.items():
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001554 if val in arg.__bases__ + (arg,):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001555 arg_attrs.pop(attr)
1556 for obj in arg_attrs.values():
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001557 if isinstance(obj, types.FunctionType):
1558 obj.__no_type_check__ = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001559 if isinstance(obj, type):
1560 no_type_check(obj)
1561 try:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001562 arg.__no_type_check__ = True
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001563 except TypeError: # built-in classes
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001564 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001565 return arg
1566
1567
1568def no_type_check_decorator(decorator):
1569 """Decorator to give another decorator the @no_type_check effect.
1570
1571 This wraps the decorator with something that wraps the decorated
1572 function in @no_type_check.
1573 """
1574
1575 @functools.wraps(decorator)
1576 def wrapped_decorator(*args, **kwds):
1577 func = decorator(*args, **kwds)
1578 func = no_type_check(func)
1579 return func
1580
1581 return wrapped_decorator
1582
1583
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001584def _overload_dummy(*args, **kwds):
1585 """Helper for @overload to raise when called."""
1586 raise NotImplementedError(
1587 "You should not call an overloaded function. "
1588 "A series of @overload-decorated functions "
1589 "outside a stub module should always be followed "
1590 "by an implementation that is not @overload-ed.")
1591
1592
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001593def overload(func):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001594 """Decorator for overloaded functions/methods.
1595
1596 In a stub file, place two or more stub definitions for the same
1597 function in a row, each decorated with @overload. For example:
1598
1599 @overload
1600 def utf8(value: None) -> None: ...
1601 @overload
1602 def utf8(value: bytes) -> bytes: ...
1603 @overload
1604 def utf8(value: str) -> bytes: ...
1605
1606 In a non-stub file (i.e. a regular .py file), do the same but
1607 follow it with an implementation. The implementation should *not*
1608 be decorated with @overload. For example:
1609
1610 @overload
1611 def utf8(value: None) -> None: ...
1612 @overload
1613 def utf8(value: bytes) -> bytes: ...
1614 @overload
1615 def utf8(value: str) -> bytes: ...
1616 def utf8(value):
1617 # implementation goes here
1618 """
1619 return _overload_dummy
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001620
1621
1622class _ProtocolMeta(GenericMeta):
1623 """Internal metaclass for _Protocol.
1624
1625 This exists so _Protocol classes can be generic without deriving
1626 from Generic.
1627 """
1628
Guido van Rossumd70fe632015-08-05 12:11:06 +02001629 def __instancecheck__(self, obj):
Guido van Rossumca4b2522016-11-19 10:32:41 -08001630 if _Protocol not in self.__bases__:
1631 return super().__instancecheck__(obj)
Guido van Rossumd70fe632015-08-05 12:11:06 +02001632 raise TypeError("Protocols cannot be used with isinstance().")
1633
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001634 def __subclasscheck__(self, cls):
1635 if not self._is_protocol:
1636 # No structural checks since this isn't a protocol.
1637 return NotImplemented
1638
1639 if self is _Protocol:
1640 # Every class is a subclass of the empty protocol.
1641 return True
1642
1643 # Find all attributes defined in the protocol.
1644 attrs = self._get_protocol_attrs()
1645
1646 for attr in attrs:
1647 if not any(attr in d.__dict__ for d in cls.__mro__):
1648 return False
1649 return True
1650
1651 def _get_protocol_attrs(self):
1652 # Get all Protocol base classes.
1653 protocol_bases = []
1654 for c in self.__mro__:
1655 if getattr(c, '_is_protocol', False) and c.__name__ != '_Protocol':
1656 protocol_bases.append(c)
1657
1658 # Get attributes included in protocol.
1659 attrs = set()
1660 for base in protocol_bases:
1661 for attr in base.__dict__.keys():
1662 # Include attributes not defined in any non-protocol bases.
1663 for c in self.__mro__:
1664 if (c is not base and attr in c.__dict__ and
1665 not getattr(c, '_is_protocol', False)):
1666 break
1667 else:
1668 if (not attr.startswith('_abc_') and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001669 attr != '__abstractmethods__' and
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001670 attr != '__annotations__' and
1671 attr != '__weakref__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001672 attr != '_is_protocol' and
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001673 attr != '_gorg' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001674 attr != '__dict__' and
1675 attr != '__args__' and
1676 attr != '__slots__' and
1677 attr != '_get_protocol_attrs' and
1678 attr != '__next_in_mro__' and
1679 attr != '__parameters__' and
1680 attr != '__origin__' and
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001681 attr != '__orig_bases__' and
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001682 attr != '__extra__' and
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001683 attr != '__tree_hash__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001684 attr != '__module__'):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001685 attrs.add(attr)
1686
1687 return attrs
1688
1689
1690class _Protocol(metaclass=_ProtocolMeta):
1691 """Internal base class for protocol classes.
1692
Guido van Rossumb24569a2016-11-20 18:01:29 -08001693 This implements a simple-minded structural issubclass check
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001694 (similar but more general than the one-offs in collections.abc
1695 such as Hashable).
1696 """
1697
Guido van Rossumd70fe632015-08-05 12:11:06 +02001698 __slots__ = ()
1699
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001700 _is_protocol = True
1701
1702
1703# Various ABCs mimicking those in collections.abc.
1704# A few are simply re-exported for completeness.
1705
1706Hashable = collections_abc.Hashable # Not generic.
1707
1708
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001709if hasattr(collections_abc, 'Awaitable'):
1710 class Awaitable(Generic[T_co], extra=collections_abc.Awaitable):
1711 __slots__ = ()
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001712
1713 __all__.append('Awaitable')
1714
1715
1716if hasattr(collections_abc, 'Coroutine'):
1717 class Coroutine(Awaitable[V_co], Generic[T_co, T_contra, V_co],
1718 extra=collections_abc.Coroutine):
1719 __slots__ = ()
1720
1721 __all__.append('Coroutine')
Guido van Rossumf17c2002015-12-03 17:31:24 -08001722
1723
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001724if hasattr(collections_abc, 'AsyncIterable'):
Guido van Rossumf17c2002015-12-03 17:31:24 -08001725
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001726 class AsyncIterable(Generic[T_co], extra=collections_abc.AsyncIterable):
1727 __slots__ = ()
Guido van Rossumf17c2002015-12-03 17:31:24 -08001728
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001729 class AsyncIterator(AsyncIterable[T_co],
1730 extra=collections_abc.AsyncIterator):
1731 __slots__ = ()
1732
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001733 __all__.append('AsyncIterable')
1734 __all__.append('AsyncIterator')
Guido van Rossumf17c2002015-12-03 17:31:24 -08001735
1736
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001737class Iterable(Generic[T_co], extra=collections_abc.Iterable):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001738 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001739
1740
1741class Iterator(Iterable[T_co], extra=collections_abc.Iterator):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001742 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001743
1744
1745class SupportsInt(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001746 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001747
1748 @abstractmethod
1749 def __int__(self) -> int:
1750 pass
1751
1752
1753class SupportsFloat(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001754 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001755
1756 @abstractmethod
1757 def __float__(self) -> float:
1758 pass
1759
1760
1761class SupportsComplex(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001762 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001763
1764 @abstractmethod
1765 def __complex__(self) -> complex:
1766 pass
1767
1768
1769class SupportsBytes(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001770 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001771
1772 @abstractmethod
1773 def __bytes__(self) -> bytes:
1774 pass
1775
1776
Guido van Rossumd70fe632015-08-05 12:11:06 +02001777class SupportsAbs(_Protocol[T_co]):
1778 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001779
1780 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001781 def __abs__(self) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001782 pass
1783
1784
Guido van Rossumd70fe632015-08-05 12:11:06 +02001785class SupportsRound(_Protocol[T_co]):
1786 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001787
1788 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001789 def __round__(self, ndigits: int = 0) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001790 pass
1791
1792
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001793if hasattr(collections_abc, 'Reversible'):
1794 class Reversible(Iterable[T_co], extra=collections_abc.Reversible):
1795 __slots__ = ()
1796else:
1797 class Reversible(_Protocol[T_co]):
1798 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001799
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001800 @abstractmethod
1801 def __reversed__(self) -> 'Iterator[T_co]':
1802 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001803
1804
1805Sized = collections_abc.Sized # Not generic.
1806
1807
1808class Container(Generic[T_co], extra=collections_abc.Container):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001809 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001810
1811
Guido van Rossumefa798d2016-08-23 11:01:50 -07001812if hasattr(collections_abc, 'Collection'):
1813 class Collection(Sized, Iterable[T_co], Container[T_co],
1814 extra=collections_abc.Collection):
1815 __slots__ = ()
1816
1817 __all__.append('Collection')
1818
1819
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001820# Callable was defined earlier.
1821
Guido van Rossumefa798d2016-08-23 11:01:50 -07001822if hasattr(collections_abc, 'Collection'):
1823 class AbstractSet(Collection[T_co],
1824 extra=collections_abc.Set):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001825 __slots__ = ()
Guido van Rossumefa798d2016-08-23 11:01:50 -07001826else:
1827 class AbstractSet(Sized, Iterable[T_co], Container[T_co],
1828 extra=collections_abc.Set):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001829 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001830
1831
1832class MutableSet(AbstractSet[T], extra=collections_abc.MutableSet):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001833 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001834
1835
Guido van Rossumefa798d2016-08-23 11:01:50 -07001836# NOTE: It is only covariant in the value type.
1837if hasattr(collections_abc, 'Collection'):
1838 class Mapping(Collection[KT], Generic[KT, VT_co],
1839 extra=collections_abc.Mapping):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001840 __slots__ = ()
Guido van Rossumefa798d2016-08-23 11:01:50 -07001841else:
1842 class Mapping(Sized, Iterable[KT], Container[KT], Generic[KT, VT_co],
1843 extra=collections_abc.Mapping):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001844 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001845
1846
1847class MutableMapping(Mapping[KT, VT], extra=collections_abc.MutableMapping):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001848 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001849
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001850
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001851if hasattr(collections_abc, 'Reversible'):
Guido van Rossumefa798d2016-08-23 11:01:50 -07001852 if hasattr(collections_abc, 'Collection'):
1853 class Sequence(Reversible[T_co], Collection[T_co],
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001854 extra=collections_abc.Sequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001855 __slots__ = ()
Guido van Rossumefa798d2016-08-23 11:01:50 -07001856 else:
1857 class Sequence(Sized, Reversible[T_co], Container[T_co],
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001858 extra=collections_abc.Sequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001859 __slots__ = ()
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001860else:
1861 class Sequence(Sized, Iterable[T_co], Container[T_co],
1862 extra=collections_abc.Sequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001863 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001864
1865
1866class MutableSequence(Sequence[T], extra=collections_abc.MutableSequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001867 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001868
1869
1870class ByteString(Sequence[int], extra=collections_abc.ByteString):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001871 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001872
1873
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001874class List(list, MutableSequence[T], extra=list):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001875
Guido van Rossum4cefe742016-09-27 15:20:12 -07001876 __slots__ = ()
1877
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001878 def __new__(cls, *args, **kwds):
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001879 if cls._gorg is List:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001880 raise TypeError("Type List cannot be instantiated; "
1881 "use list() instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001882 return _generic_new(list, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001883
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001884
Raymond Hettinger80490522017-01-16 22:42:37 -08001885class Deque(collections.deque, MutableSequence[T], extra=collections.deque):
1886
1887 __slots__ = ()
1888
1889 def __new__(cls, *args, **kwds):
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001890 if cls._gorg is Deque:
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001891 return collections.deque(*args, **kwds)
Raymond Hettinger80490522017-01-16 22:42:37 -08001892 return _generic_new(collections.deque, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001893
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001894
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001895class Set(set, MutableSet[T], extra=set):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001896
Guido van Rossum4cefe742016-09-27 15:20:12 -07001897 __slots__ = ()
1898
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001899 def __new__(cls, *args, **kwds):
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001900 if cls._gorg is Set:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001901 raise TypeError("Type Set cannot be instantiated; "
1902 "use set() instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001903 return _generic_new(set, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001904
1905
Guido van Rossum4cefe742016-09-27 15:20:12 -07001906class FrozenSet(frozenset, AbstractSet[T_co], extra=frozenset):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001907 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001908
1909 def __new__(cls, *args, **kwds):
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001910 if cls._gorg is FrozenSet:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001911 raise TypeError("Type FrozenSet cannot be instantiated; "
1912 "use frozenset() instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001913 return _generic_new(frozenset, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001914
1915
1916class MappingView(Sized, Iterable[T_co], extra=collections_abc.MappingView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001917 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001918
1919
Guido van Rossumd70fe632015-08-05 12:11:06 +02001920class KeysView(MappingView[KT], AbstractSet[KT],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001921 extra=collections_abc.KeysView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001922 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001923
1924
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001925class ItemsView(MappingView[Tuple[KT, VT_co]],
Guido van Rossum0e0563c2016-04-05 14:54:25 -07001926 AbstractSet[Tuple[KT, VT_co]],
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001927 Generic[KT, VT_co],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001928 extra=collections_abc.ItemsView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001929 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001930
1931
1932class ValuesView(MappingView[VT_co], extra=collections_abc.ValuesView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001933 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001934
1935
Brett Cannonf3ad0422016-04-15 10:51:30 -07001936if hasattr(contextlib, 'AbstractContextManager'):
1937 class ContextManager(Generic[T_co], extra=contextlib.AbstractContextManager):
1938 __slots__ = ()
Ivan Levkivskyi29fda8d2017-06-10 21:57:56 +02001939else:
1940 class ContextManager(Generic[T_co]):
1941 __slots__ = ()
1942
1943 def __enter__(self):
1944 return self
1945
1946 @abc.abstractmethod
1947 def __exit__(self, exc_type, exc_value, traceback):
1948 return None
1949
1950 @classmethod
1951 def __subclasshook__(cls, C):
1952 if cls is ContextManager:
1953 # In Python 3.6+, it is possible to set a method to None to
1954 # explicitly indicate that the class does not implement an ABC
1955 # (https://bugs.python.org/issue25958), but we do not support
1956 # that pattern here because this fallback class is only used
1957 # in Python 3.5 and earlier.
1958 if (any("__enter__" in B.__dict__ for B in C.__mro__) and
1959 any("__exit__" in B.__dict__ for B in C.__mro__)):
1960 return True
1961 return NotImplemented
1962
1963
1964if hasattr(contextlib, 'AbstractAsyncContextManager'):
1965 class AsyncContextManager(Generic[T_co],
1966 extra=contextlib.AbstractAsyncContextManager):
1967 __slots__ = ()
1968
1969 __all__.append('AsyncContextManager')
1970elif sys.version_info[:2] >= (3, 5):
1971 exec("""
1972class AsyncContextManager(Generic[T_co]):
1973 __slots__ = ()
1974
1975 async def __aenter__(self):
1976 return self
1977
1978 @abc.abstractmethod
1979 async def __aexit__(self, exc_type, exc_value, traceback):
1980 return None
1981
1982 @classmethod
1983 def __subclasshook__(cls, C):
1984 if cls is AsyncContextManager:
1985 if sys.version_info[:2] >= (3, 6):
1986 return _collections_abc._check_methods(C, "__aenter__", "__aexit__")
1987 if (any("__aenter__" in B.__dict__ for B in C.__mro__) and
1988 any("__aexit__" in B.__dict__ for B in C.__mro__)):
1989 return True
1990 return NotImplemented
1991
1992__all__.append('AsyncContextManager')
1993""")
Brett Cannonf3ad0422016-04-15 10:51:30 -07001994
1995
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001996class Dict(dict, MutableMapping[KT, VT], extra=dict):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001997
Guido van Rossum4cefe742016-09-27 15:20:12 -07001998 __slots__ = ()
1999
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002000 def __new__(cls, *args, **kwds):
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02002001 if cls._gorg is Dict:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002002 raise TypeError("Type Dict cannot be instantiated; "
2003 "use dict() instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07002004 return _generic_new(dict, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002005
Guido van Rossumd7adfe12017-01-22 17:43:53 -08002006
Guido van Rossum1cea70f2016-05-18 08:35:00 -07002007class DefaultDict(collections.defaultdict, MutableMapping[KT, VT],
2008 extra=collections.defaultdict):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07002009
Guido van Rossum4cefe742016-09-27 15:20:12 -07002010 __slots__ = ()
2011
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07002012 def __new__(cls, *args, **kwds):
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02002013 if cls._gorg is DefaultDict:
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01002014 return collections.defaultdict(*args, **kwds)
Guido van Rossum5fc25a82016-10-29 08:54:56 -07002015 return _generic_new(collections.defaultdict, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002016
Guido van Rossumd7adfe12017-01-22 17:43:53 -08002017
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01002018class Counter(collections.Counter, Dict[T, int], extra=collections.Counter):
2019
2020 __slots__ = ()
2021
2022 def __new__(cls, *args, **kwds):
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02002023 if cls._gorg is Counter:
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01002024 return collections.Counter(*args, **kwds)
2025 return _generic_new(collections.Counter, cls, *args, **kwds)
2026
2027
2028if hasattr(collections, 'ChainMap'):
2029 # ChainMap only exists in 3.3+
2030 __all__.append('ChainMap')
2031
2032 class ChainMap(collections.ChainMap, MutableMapping[KT, VT],
2033 extra=collections.ChainMap):
2034
2035 __slots__ = ()
2036
2037 def __new__(cls, *args, **kwds):
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02002038 if cls._gorg is ChainMap:
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01002039 return collections.ChainMap(*args, **kwds)
2040 return _generic_new(collections.ChainMap, cls, *args, **kwds)
2041
2042
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002043# Determine what base class to use for Generator.
2044if hasattr(collections_abc, 'Generator'):
2045 # Sufficiently recent versions of 3.5 have a Generator ABC.
2046 _G_base = collections_abc.Generator
2047else:
2048 # Fall back on the exact type.
2049 _G_base = types.GeneratorType
2050
2051
2052class Generator(Iterator[T_co], Generic[T_co, T_contra, V_co],
2053 extra=_G_base):
Guido van Rossumd70fe632015-08-05 12:11:06 +02002054 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002055
2056 def __new__(cls, *args, **kwds):
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02002057 if cls._gorg is Generator:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002058 raise TypeError("Type Generator cannot be instantiated; "
2059 "create a subclass instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07002060 return _generic_new(_G_base, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002061
Guido van Rossumd7adfe12017-01-22 17:43:53 -08002062
Guido van Rossume9ed5602017-01-18 13:10:31 -08002063if hasattr(collections_abc, 'AsyncGenerator'):
2064 class AsyncGenerator(AsyncIterator[T_co], Generic[T_co, T_contra],
2065 extra=collections_abc.AsyncGenerator):
2066 __slots__ = ()
2067
2068 __all__.append('AsyncGenerator')
2069
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002070
Guido van Rossumeb9aca32016-05-24 16:38:22 -07002071# Internal type variable used for Type[].
Guido van Rossumefa798d2016-08-23 11:01:50 -07002072CT_co = TypeVar('CT_co', covariant=True, bound=type)
Guido van Rossumeb9aca32016-05-24 16:38:22 -07002073
2074
Guido van Rossumb22c7082016-05-26 09:56:19 -07002075# This is not a real generic class. Don't use outside annotations.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002076class Type(Generic[CT_co], extra=type):
Guido van Rossumb22c7082016-05-26 09:56:19 -07002077 """A special construct usable to annotate class objects.
Guido van Rossumeb9aca32016-05-24 16:38:22 -07002078
2079 For example, suppose we have the following classes::
2080
2081 class User: ... # Abstract base for User classes
2082 class BasicUser(User): ...
2083 class ProUser(User): ...
2084 class TeamUser(User): ...
2085
2086 And a function that takes a class argument that's a subclass of
2087 User and returns an instance of the corresponding class::
2088
2089 U = TypeVar('U', bound=User)
2090 def new_user(user_class: Type[U]) -> U:
2091 user = user_class()
2092 # (Here we could write the user object to a database)
2093 return user
2094
2095 joe = new_user(BasicUser)
2096
2097 At this point the type checker knows that joe has type BasicUser.
2098 """
2099
Guido van Rossum4cefe742016-09-27 15:20:12 -07002100 __slots__ = ()
2101
Guido van Rossumeb9aca32016-05-24 16:38:22 -07002102
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002103def _make_nmtuple(name, types):
Guido van Rossum2f841442016-11-15 09:48:06 -08002104 msg = "NamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a type"
2105 types = [(n, _type_check(t, msg)) for n, t in types]
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002106 nm_tpl = collections.namedtuple(name, [n for n, t in types])
Guido van Rossum83ec3022017-01-17 20:43:28 -08002107 # Prior to PEP 526, only _field_types attribute was assigned.
2108 # Now, both __annotations__ and _field_types are used to maintain compatibility.
2109 nm_tpl.__annotations__ = nm_tpl._field_types = collections.OrderedDict(types)
Guido van Rossum557d1eb2015-11-19 08:16:31 -08002110 try:
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002111 nm_tpl.__module__ = sys._getframe(2).f_globals.get('__name__', '__main__')
Guido van Rossum557d1eb2015-11-19 08:16:31 -08002112 except (AttributeError, ValueError):
2113 pass
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002114 return nm_tpl
2115
2116
Guido van Rossum2f841442016-11-15 09:48:06 -08002117_PY36 = sys.version_info[:2] >= (3, 6)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002118
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01002119# attributes prohibited to set in NamedTuple class syntax
2120_prohibited = ('__new__', '__init__', '__slots__', '__getnewargs__',
2121 '_fields', '_field_defaults', '_field_types',
Ivan Levkivskyif06e0212017-05-02 19:14:07 +02002122 '_make', '_replace', '_asdict', '_source')
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01002123
2124_special = ('__module__', '__name__', '__qualname__', '__annotations__')
2125
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002126
Guido van Rossum2f841442016-11-15 09:48:06 -08002127class NamedTupleMeta(type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002128
Guido van Rossum2f841442016-11-15 09:48:06 -08002129 def __new__(cls, typename, bases, ns):
2130 if ns.get('_root', False):
2131 return super().__new__(cls, typename, bases, ns)
2132 if not _PY36:
2133 raise TypeError("Class syntax for NamedTuple is only supported"
2134 " in Python 3.6+")
2135 types = ns.get('__annotations__', {})
Guido van Rossum3c268be2017-01-18 08:03:50 -08002136 nm_tpl = _make_nmtuple(typename, types.items())
2137 defaults = []
2138 defaults_dict = {}
2139 for field_name in types:
2140 if field_name in ns:
2141 default_value = ns[field_name]
2142 defaults.append(default_value)
2143 defaults_dict[field_name] = default_value
2144 elif defaults:
Guido van Rossumd7adfe12017-01-22 17:43:53 -08002145 raise TypeError("Non-default namedtuple field {field_name} cannot "
2146 "follow default field(s) {default_names}"
Guido van Rossum3c268be2017-01-18 08:03:50 -08002147 .format(field_name=field_name,
2148 default_names=', '.join(defaults_dict.keys())))
2149 nm_tpl.__new__.__defaults__ = tuple(defaults)
2150 nm_tpl._field_defaults = defaults_dict
Guido van Rossum95919c02017-01-22 17:47:20 -08002151 # update from user namespace without overriding special namedtuple attributes
2152 for key in ns:
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01002153 if key in _prohibited:
2154 raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
2155 elif key not in _special and key not in nm_tpl._fields:
Guido van Rossum95919c02017-01-22 17:47:20 -08002156 setattr(nm_tpl, key, ns[key])
Guido van Rossum3c268be2017-01-18 08:03:50 -08002157 return nm_tpl
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002158
Guido van Rossumd7adfe12017-01-22 17:43:53 -08002159
Guido van Rossum2f841442016-11-15 09:48:06 -08002160class NamedTuple(metaclass=NamedTupleMeta):
2161 """Typed version of namedtuple.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002162
Guido van Rossum2f841442016-11-15 09:48:06 -08002163 Usage in Python versions >= 3.6::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002164
Guido van Rossum2f841442016-11-15 09:48:06 -08002165 class Employee(NamedTuple):
2166 name: str
2167 id: int
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002168
Guido van Rossum2f841442016-11-15 09:48:06 -08002169 This is equivalent to::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002170
Guido van Rossum2f841442016-11-15 09:48:06 -08002171 Employee = collections.namedtuple('Employee', ['name', 'id'])
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002172
Guido van Rossum83ec3022017-01-17 20:43:28 -08002173 The resulting class has extra __annotations__ and _field_types
2174 attributes, giving an ordered dict mapping field names to types.
2175 __annotations__ should be preferred, while _field_types
2176 is kept to maintain pre PEP 526 compatibility. (The field names
Guido van Rossum2f841442016-11-15 09:48:06 -08002177 are in the _fields attribute, which is part of the namedtuple
2178 API.) Alternative equivalent keyword syntax is also accepted::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002179
Guido van Rossum2f841442016-11-15 09:48:06 -08002180 Employee = NamedTuple('Employee', name=str, id=int)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002181
Guido van Rossum2f841442016-11-15 09:48:06 -08002182 In Python versions <= 3.5 use::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002183
Guido van Rossum2f841442016-11-15 09:48:06 -08002184 Employee = NamedTuple('Employee', [('name', str), ('id', int)])
2185 """
2186 _root = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002187
Guido van Rossum2f841442016-11-15 09:48:06 -08002188 def __new__(self, typename, fields=None, **kwargs):
2189 if kwargs and not _PY36:
2190 raise TypeError("Keyword syntax for NamedTuple is only supported"
2191 " in Python 3.6+")
2192 if fields is None:
2193 fields = kwargs.items()
2194 elif kwargs:
2195 raise TypeError("Either list of fields or keywords"
2196 " can be provided to NamedTuple, not both")
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002197 return _make_nmtuple(typename, fields)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002198
2199
Guido van Rossum91185fe2016-06-08 11:19:11 -07002200def NewType(name, tp):
2201 """NewType creates simple unique types with almost zero
2202 runtime overhead. NewType(name, tp) is considered a subtype of tp
2203 by static type checkers. At runtime, NewType(name, tp) returns
2204 a dummy function that simply returns its argument. Usage::
2205
2206 UserId = NewType('UserId', int)
2207
2208 def name_by_id(user_id: UserId) -> str:
2209 ...
2210
2211 UserId('user') # Fails type check
2212
2213 name_by_id(42) # Fails type check
2214 name_by_id(UserId(42)) # OK
2215
2216 num = UserId(5) + 1 # type: int
2217 """
2218
2219 def new_type(x):
2220 return x
2221
2222 new_type.__name__ = name
2223 new_type.__supertype__ = tp
2224 return new_type
2225
2226
Guido van Rossum0e0563c2016-04-05 14:54:25 -07002227# Python-version-specific alias (Python 2: unicode; Python 3: str)
2228Text = str
2229
2230
Guido van Rossum91185fe2016-06-08 11:19:11 -07002231# Constant that's True when type checking, but False here.
2232TYPE_CHECKING = False
2233
2234
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002235class IO(Generic[AnyStr]):
2236 """Generic base class for TextIO and BinaryIO.
2237
2238 This is an abstract, generic version of the return of open().
2239
2240 NOTE: This does not distinguish between the different possible
2241 classes (text vs. binary, read vs. write vs. read/write,
2242 append-only, unbuffered). The TextIO and BinaryIO subclasses
2243 below capture the distinctions between text vs. binary, which is
2244 pervasive in the interface; however we currently do not offer a
2245 way to track the other distinctions in the type system.
2246 """
2247
Guido van Rossumd70fe632015-08-05 12:11:06 +02002248 __slots__ = ()
2249
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002250 @abstractproperty
2251 def mode(self) -> str:
2252 pass
2253
2254 @abstractproperty
2255 def name(self) -> str:
2256 pass
2257
2258 @abstractmethod
2259 def close(self) -> None:
2260 pass
2261
2262 @abstractmethod
2263 def closed(self) -> bool:
2264 pass
2265
2266 @abstractmethod
2267 def fileno(self) -> int:
2268 pass
2269
2270 @abstractmethod
2271 def flush(self) -> None:
2272 pass
2273
2274 @abstractmethod
2275 def isatty(self) -> bool:
2276 pass
2277
2278 @abstractmethod
2279 def read(self, n: int = -1) -> AnyStr:
2280 pass
2281
2282 @abstractmethod
2283 def readable(self) -> bool:
2284 pass
2285
2286 @abstractmethod
2287 def readline(self, limit: int = -1) -> AnyStr:
2288 pass
2289
2290 @abstractmethod
2291 def readlines(self, hint: int = -1) -> List[AnyStr]:
2292 pass
2293
2294 @abstractmethod
2295 def seek(self, offset: int, whence: int = 0) -> int:
2296 pass
2297
2298 @abstractmethod
2299 def seekable(self) -> bool:
2300 pass
2301
2302 @abstractmethod
2303 def tell(self) -> int:
2304 pass
2305
2306 @abstractmethod
2307 def truncate(self, size: int = None) -> int:
2308 pass
2309
2310 @abstractmethod
2311 def writable(self) -> bool:
2312 pass
2313
2314 @abstractmethod
2315 def write(self, s: AnyStr) -> int:
2316 pass
2317
2318 @abstractmethod
2319 def writelines(self, lines: List[AnyStr]) -> None:
2320 pass
2321
2322 @abstractmethod
2323 def __enter__(self) -> 'IO[AnyStr]':
2324 pass
2325
2326 @abstractmethod
2327 def __exit__(self, type, value, traceback) -> None:
2328 pass
2329
2330
2331class BinaryIO(IO[bytes]):
2332 """Typed version of the return of open() in binary mode."""
2333
Guido van Rossumd70fe632015-08-05 12:11:06 +02002334 __slots__ = ()
2335
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002336 @abstractmethod
2337 def write(self, s: Union[bytes, bytearray]) -> int:
2338 pass
2339
2340 @abstractmethod
2341 def __enter__(self) -> 'BinaryIO':
2342 pass
2343
2344
2345class TextIO(IO[str]):
2346 """Typed version of the return of open() in text mode."""
2347
Guido van Rossumd70fe632015-08-05 12:11:06 +02002348 __slots__ = ()
2349
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002350 @abstractproperty
2351 def buffer(self) -> BinaryIO:
2352 pass
2353
2354 @abstractproperty
2355 def encoding(self) -> str:
2356 pass
2357
2358 @abstractproperty
Guido van Rossum991d14f2016-11-09 13:12:51 -08002359 def errors(self) -> Optional[str]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002360 pass
2361
2362 @abstractproperty
2363 def line_buffering(self) -> bool:
2364 pass
2365
2366 @abstractproperty
2367 def newlines(self) -> Any:
2368 pass
2369
2370 @abstractmethod
2371 def __enter__(self) -> 'TextIO':
2372 pass
2373
2374
2375class io:
2376 """Wrapper namespace for IO generic classes."""
2377
2378 __all__ = ['IO', 'TextIO', 'BinaryIO']
2379 IO = IO
2380 TextIO = TextIO
2381 BinaryIO = BinaryIO
2382
Guido van Rossumd7adfe12017-01-22 17:43:53 -08002383
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002384io.__name__ = __name__ + '.io'
2385sys.modules[io.__name__] = io
2386
2387
2388Pattern = _TypeAlias('Pattern', AnyStr, type(stdlib_re.compile('')),
2389 lambda p: p.pattern)
2390Match = _TypeAlias('Match', AnyStr, type(stdlib_re.match('', '')),
2391 lambda m: m.re.pattern)
2392
2393
2394class re:
2395 """Wrapper namespace for re type aliases."""
2396
2397 __all__ = ['Pattern', 'Match']
2398 Pattern = Pattern
2399 Match = Match
2400
Guido van Rossumd7adfe12017-01-22 17:43:53 -08002401
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002402re.__name__ = __name__ + '.re'
2403sys.modules[re.__name__] = re