blob: efe358faf20988b0e2e3a315b7447b14d81c7109 [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.
Mariatta0230e642017-02-14 06:11:12 -080013try:
14 from types import SlotWrapperType, MethodWrapperType, MethodDescriptorType
15except ImportError:
16 SlotWrapperType = type(object.__init__)
17 MethodWrapperType = type(object().__str__)
18 MethodDescriptorType = type(str.join)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070019
20
21# Please keep __all__ alphabetized within each category.
22__all__ = [
23 # Super-special typing primitives.
24 'Any',
25 'Callable',
Guido van Rossum0a6976d2016-09-11 15:34:56 -070026 'ClassVar',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070027 'Generic',
28 'Optional',
Guido van Rossumeb9aca32016-05-24 16:38:22 -070029 'Tuple',
30 'Type',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070031 'TypeVar',
32 'Union',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070033
34 # ABCs (from collections.abc).
35 'AbstractSet', # collections.abc.Set.
Guido van Rossum83ec3022017-01-17 20:43:28 -080036 'GenericMeta', # subclass of abc.ABCMeta and a metaclass
37 # for 'Generic' and ABCs below.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070038 'ByteString',
39 'Container',
40 'Hashable',
41 'ItemsView',
42 'Iterable',
43 'Iterator',
44 'KeysView',
45 'Mapping',
46 'MappingView',
47 'MutableMapping',
48 'MutableSequence',
49 'MutableSet',
50 'Sequence',
51 'Sized',
52 'ValuesView',
Guido van Rossum62fe1bb2016-10-29 16:05:26 -070053 # The following are added depending on presence
54 # of their non-generic counterparts in stdlib:
55 # Awaitable,
56 # AsyncIterator,
57 # AsyncIterable,
58 # Coroutine,
59 # Collection,
Guido van Rossume9ed5602017-01-18 13:10:31 -080060 # ContextManager,
61 # AsyncGenerator,
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070062
63 # Structural checks, a.k.a. protocols.
64 'Reversible',
65 'SupportsAbs',
66 'SupportsFloat',
67 'SupportsInt',
68 'SupportsRound',
69
70 # Concrete collection types.
Mariatta0230e642017-02-14 06:11:12 -080071 'Counter',
Raymond Hettinger80490522017-01-16 22:42:37 -080072 'Deque',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070073 'Dict',
Guido van Rossumbd5b9a02016-04-05 08:28:52 -070074 'DefaultDict',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070075 'List',
76 'Set',
Guido van Rossumefa798d2016-08-23 11:01:50 -070077 'FrozenSet',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070078 'NamedTuple', # Not really a type.
79 'Generator',
80
81 # One-off things.
82 'AnyStr',
83 'cast',
84 'get_type_hints',
Guido van Rossum91185fe2016-06-08 11:19:11 -070085 'NewType',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070086 'no_type_check',
87 'no_type_check_decorator',
88 'overload',
Guido van Rossum0e0563c2016-04-05 14:54:25 -070089 'Text',
Guido van Rossum91185fe2016-06-08 11:19:11 -070090 'TYPE_CHECKING',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070091]
92
Guido van Rossumbd5b9a02016-04-05 08:28:52 -070093# The pseudo-submodules 're' and 'io' are part of the public
94# namespace, but excluded from __all__ because they might stomp on
95# legitimate imports of those modules.
96
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070097
98def _qualname(x):
99 if sys.version_info[:2] >= (3, 3):
100 return x.__qualname__
101 else:
102 # Fall back to just name.
103 return x.__name__
104
105
Guido van Rossum4cefe742016-09-27 15:20:12 -0700106def _trim_name(nm):
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800107 whitelist = ('_TypeAlias', '_ForwardRef', '_TypingBase', '_FinalTypingBase')
108 if nm.startswith('_') and nm not in whitelist:
Guido van Rossum4cefe742016-09-27 15:20:12 -0700109 nm = nm[1:]
110 return nm
111
112
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700113class TypingMeta(type):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800114 """Metaclass for most types defined in typing module
115 (not a part of public API).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700116
117 This overrides __new__() to require an extra keyword parameter
118 '_root', which serves as a guard against naive subclassing of the
119 typing classes. Any legitimate class defined using a metaclass
Guido van Rossumb24569a2016-11-20 18:01:29 -0800120 derived from TypingMeta must pass _root=True.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700121
Guido van Rossumb24569a2016-11-20 18:01:29 -0800122 This also defines a dummy constructor (all the work for most typing
123 constructs is done in __new__) and a nicer repr().
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700124 """
125
126 _is_protocol = False
127
128 def __new__(cls, name, bases, namespace, *, _root=False):
129 if not _root:
130 raise TypeError("Cannot subclass %s" %
131 (', '.join(map(_type_repr, bases)) or '()'))
132 return super().__new__(cls, name, bases, namespace)
133
134 def __init__(self, *args, **kwds):
135 pass
136
137 def _eval_type(self, globalns, localns):
138 """Override this in subclasses to interpret forward references.
139
Guido van Rossumb24569a2016-11-20 18:01:29 -0800140 For example, List['C'] is internally stored as
141 List[_ForwardRef('C')], which should evaluate to List[C],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700142 where C is an object found in globalns or localns (searching
143 localns first, of course).
144 """
145 return self
146
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700147 def _get_type_vars(self, tvars):
148 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700149
150 def __repr__(self):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700151 qname = _trim_name(_qualname(self))
152 return '%s.%s' % (self.__module__, qname)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700153
154
Guido van Rossum4cefe742016-09-27 15:20:12 -0700155class _TypingBase(metaclass=TypingMeta, _root=True):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800156 """Internal indicator of special typing constructs."""
Guido van Rossum4cefe742016-09-27 15:20:12 -0700157
Guido van Rossum83ec3022017-01-17 20:43:28 -0800158 __slots__ = ('__weakref__',)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700159
Guido van Rossum4cefe742016-09-27 15:20:12 -0700160 def __init__(self, *args, **kwds):
161 pass
162
163 def __new__(cls, *args, **kwds):
164 """Constructor.
165
166 This only exists to give a better error message in case
167 someone tries to subclass a special typing object (not a good idea).
168 """
169 if (len(args) == 3 and
170 isinstance(args[0], str) and
171 isinstance(args[1], tuple)):
172 # Close enough.
173 raise TypeError("Cannot subclass %r" % cls)
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700174 return super().__new__(cls)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700175
176 # Things that are not classes also need these.
177 def _eval_type(self, globalns, localns):
178 return self
179
180 def _get_type_vars(self, tvars):
181 pass
182
183 def __repr__(self):
184 cls = type(self)
185 qname = _trim_name(_qualname(cls))
186 return '%s.%s' % (cls.__module__, qname)
187
188 def __call__(self, *args, **kwds):
189 raise TypeError("Cannot instantiate %r" % type(self))
190
191
192class _FinalTypingBase(_TypingBase, _root=True):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800193 """Internal mix-in class to prevent instantiation.
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700194
195 Prevents instantiation unless _root=True is given in class call.
Guido van Rossumb24569a2016-11-20 18:01:29 -0800196 It is used to create pseudo-singleton instances Any, Union, Optional, etc.
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700197 """
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700198
Guido van Rossumd70fe632015-08-05 12:11:06 +0200199 __slots__ = ()
200
Guido van Rossum4cefe742016-09-27 15:20:12 -0700201 def __new__(cls, *args, _root=False, **kwds):
202 self = super().__new__(cls, *args, **kwds)
203 if _root is True:
204 return self
205 raise TypeError("Cannot instantiate %r" % cls)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700206
Guido van Rossumb7dedc82016-10-29 12:44:29 -0700207 def __reduce__(self):
208 return _trim_name(type(self).__name__)
209
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700210
Guido van Rossum4cefe742016-09-27 15:20:12 -0700211class _ForwardRef(_TypingBase, _root=True):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800212 """Internal wrapper to hold a forward reference."""
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700213
Guido van Rossum4cefe742016-09-27 15:20:12 -0700214 __slots__ = ('__forward_arg__', '__forward_code__',
Guido van Rossumc7b92952016-11-10 08:24:06 -0800215 '__forward_evaluated__', '__forward_value__')
Guido van Rossum4cefe742016-09-27 15:20:12 -0700216
217 def __init__(self, arg):
218 super().__init__(arg)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700219 if not isinstance(arg, str):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800220 raise TypeError('Forward reference must be a string -- got %r' % (arg,))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700221 try:
222 code = compile(arg, '<string>', 'eval')
223 except SyntaxError:
Guido van Rossumb24569a2016-11-20 18:01:29 -0800224 raise SyntaxError('Forward reference must be an expression -- got %r' %
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700225 (arg,))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700226 self.__forward_arg__ = arg
227 self.__forward_code__ = code
228 self.__forward_evaluated__ = False
229 self.__forward_value__ = None
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700230
231 def _eval_type(self, globalns, localns):
Guido van Rossumdad17902016-11-10 08:29:18 -0800232 if not self.__forward_evaluated__ or localns is not globalns:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700233 if globalns is None and localns is None:
234 globalns = localns = {}
235 elif globalns is None:
236 globalns = localns
237 elif localns is None:
238 localns = globalns
239 self.__forward_value__ = _type_check(
240 eval(self.__forward_code__, globalns, localns),
241 "Forward references must evaluate to types.")
242 self.__forward_evaluated__ = True
243 return self.__forward_value__
244
Guido van Rossum4cefe742016-09-27 15:20:12 -0700245 def __eq__(self, other):
246 if not isinstance(other, _ForwardRef):
247 return NotImplemented
248 return (self.__forward_arg__ == other.__forward_arg__ and
Guido van Rossumc7b92952016-11-10 08:24:06 -0800249 self.__forward_value__ == other.__forward_value__)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700250
251 def __hash__(self):
Guido van Rossumc7b92952016-11-10 08:24:06 -0800252 return hash((self.__forward_arg__, self.__forward_value__))
Guido van Rossum4cefe742016-09-27 15:20:12 -0700253
Guido van Rossumd70fe632015-08-05 12:11:06 +0200254 def __instancecheck__(self, obj):
255 raise TypeError("Forward references cannot be used with isinstance().")
256
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700257 def __subclasscheck__(self, cls):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700258 raise TypeError("Forward references cannot be used with issubclass().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700259
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700260 def __repr__(self):
261 return '_ForwardRef(%r)' % (self.__forward_arg__,)
262
263
Guido van Rossum4cefe742016-09-27 15:20:12 -0700264class _TypeAlias(_TypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700265 """Internal helper class for defining generic variants of concrete types.
266
Guido van Rossum4cefe742016-09-27 15:20:12 -0700267 Note that this is not a type; let's call it a pseudo-type. It cannot
268 be used in instance and subclass checks in parameterized form, i.e.
269 ``isinstance(42, Match[str])`` raises ``TypeError`` instead of returning
270 ``False``.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700271 """
272
Guido van Rossumd70fe632015-08-05 12:11:06 +0200273 __slots__ = ('name', 'type_var', 'impl_type', 'type_checker')
274
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700275 def __init__(self, name, type_var, impl_type, type_checker):
276 """Initializer.
277
278 Args:
279 name: The name, e.g. 'Pattern'.
280 type_var: The type parameter, e.g. AnyStr, or the
281 specific type, e.g. str.
282 impl_type: The implementation type.
283 type_checker: Function that takes an impl_type instance.
284 and returns a value that should be a type_var instance.
285 """
286 assert isinstance(name, str), repr(name)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700287 assert isinstance(impl_type, type), repr(impl_type)
288 assert not isinstance(impl_type, TypingMeta), repr(impl_type)
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700289 assert isinstance(type_var, (type, _TypingBase)), repr(type_var)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700290 self.name = name
291 self.type_var = type_var
292 self.impl_type = impl_type
293 self.type_checker = type_checker
294
295 def __repr__(self):
296 return "%s[%s]" % (self.name, _type_repr(self.type_var))
297
298 def __getitem__(self, parameter):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700299 if not isinstance(self.type_var, TypeVar):
300 raise TypeError("%s cannot be further parameterized." % self)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700301 if self.type_var.__constraints__ and isinstance(parameter, type):
302 if not issubclass(parameter, self.type_var.__constraints__):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700303 raise TypeError("%s is not a valid substitution for %s." %
304 (parameter, self.type_var))
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700305 if isinstance(parameter, TypeVar) and parameter is not self.type_var:
306 raise TypeError("%s cannot be re-parameterized." % self)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700307 return self.__class__(self.name, parameter,
308 self.impl_type, self.type_checker)
309
Guido van Rossum4cefe742016-09-27 15:20:12 -0700310 def __eq__(self, other):
311 if not isinstance(other, _TypeAlias):
312 return NotImplemented
313 return self.name == other.name and self.type_var == other.type_var
314
315 def __hash__(self):
316 return hash((self.name, self.type_var))
317
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700318 def __instancecheck__(self, obj):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700319 if not isinstance(self.type_var, TypeVar):
320 raise TypeError("Parameterized type aliases cannot be used "
321 "with isinstance().")
322 return isinstance(obj, self.impl_type)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700323
324 def __subclasscheck__(self, cls):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700325 if not isinstance(self.type_var, TypeVar):
326 raise TypeError("Parameterized type aliases cannot be used "
327 "with issubclass().")
328 return issubclass(cls, self.impl_type)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700329
330
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700331def _get_type_vars(types, tvars):
332 for t in types:
Guido van Rossum4cefe742016-09-27 15:20:12 -0700333 if isinstance(t, TypingMeta) or isinstance(t, _TypingBase):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700334 t._get_type_vars(tvars)
335
336
337def _type_vars(types):
338 tvars = []
339 _get_type_vars(types, tvars)
340 return tuple(tvars)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700341
342
343def _eval_type(t, globalns, localns):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700344 if isinstance(t, TypingMeta) or isinstance(t, _TypingBase):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700345 return t._eval_type(globalns, localns)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700346 return t
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700347
348
349def _type_check(arg, msg):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800350 """Check that the argument is a type, and return it (internal helper).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700351
352 As a special case, accept None and return type(None) instead.
353 Also, _TypeAlias instances (e.g. Match, Pattern) are acceptable.
354
355 The msg argument is a human-readable error message, e.g.
356
357 "Union[arg, ...]: arg should be a type."
358
359 We append the repr() of the actual value (truncated to 100 chars).
360 """
361 if arg is None:
362 return type(None)
363 if isinstance(arg, str):
364 arg = _ForwardRef(arg)
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800365 if (
366 isinstance(arg, _TypingBase) and type(arg).__name__ == '_ClassVar' or
367 not isinstance(arg, (type, _TypingBase)) and not callable(arg)
368 ):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700369 raise TypeError(msg + " Got %.100r." % (arg,))
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700370 # Bare Union etc. are not valid as type arguments
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800371 if (
372 type(arg).__name__ in ('_Union', '_Optional') and
373 not getattr(arg, '__origin__', None) or
374 isinstance(arg, TypingMeta) and _gorg(arg) in (Generic, _Protocol)
375 ):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700376 raise TypeError("Plain %s is not valid as type argument" % arg)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700377 return arg
378
379
380def _type_repr(obj):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800381 """Return the repr() of an object, special-casing types (internal helper).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700382
383 If obj is a type, we return a shorter version than the default
384 type.__repr__, based on the module and qualified name, which is
385 typically enough to uniquely identify a type. For everything
386 else, we fall back on repr(obj).
387 """
388 if isinstance(obj, type) and not isinstance(obj, TypingMeta):
389 if obj.__module__ == 'builtins':
390 return _qualname(obj)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700391 return '%s.%s' % (obj.__module__, _qualname(obj))
392 if obj is ...:
393 return('...')
394 if isinstance(obj, types.FunctionType):
395 return obj.__name__
396 return repr(obj)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700397
398
Guido van Rossum4cefe742016-09-27 15:20:12 -0700399class _Any(_FinalTypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700400 """Special type indicating an unconstrained type.
401
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700402 - Any is compatible with every type.
403 - Any assumed to have all methods.
404 - All values assumed to be instances of Any.
405
406 Note that all the above statements are true from the point of view of
407 static type checkers. At runtime, Any should not be used with instance
408 or class checks.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700409 """
410
Guido van Rossumd70fe632015-08-05 12:11:06 +0200411 __slots__ = ()
412
Guido van Rossum4cefe742016-09-27 15:20:12 -0700413 def __instancecheck__(self, obj):
414 raise TypeError("Any cannot be used with isinstance().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700415
Guido van Rossum4cefe742016-09-27 15:20:12 -0700416 def __subclasscheck__(self, cls):
417 raise TypeError("Any cannot be used with issubclass().")
418
419
420Any = _Any(_root=True)
421
422
423class TypeVar(_TypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700424 """Type variable.
425
426 Usage::
427
428 T = TypeVar('T') # Can be anything
429 A = TypeVar('A', str, bytes) # Must be str or bytes
430
431 Type variables exist primarily for the benefit of static type
432 checkers. They serve as the parameters for generic types as well
433 as for generic function definitions. See class Generic for more
434 information on generic types. Generic functions work as follows:
435
Guido van Rossumb24569a2016-11-20 18:01:29 -0800436 def repeat(x: T, n: int) -> List[T]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700437 '''Return a list containing n references to x.'''
438 return [x]*n
439
440 def longest(x: A, y: A) -> A:
441 '''Return the longest of two strings.'''
442 return x if len(x) >= len(y) else y
443
444 The latter example's signature is essentially the overloading
445 of (str, str) -> str and (bytes, bytes) -> bytes. Also note
446 that if the arguments are instances of some subclass of str,
447 the return type is still plain str.
448
Guido van Rossumb24569a2016-11-20 18:01:29 -0800449 At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700450
Guido van Rossumefa798d2016-08-23 11:01:50 -0700451 Type variables defined with covariant=True or contravariant=True
452 can be used do declare covariant or contravariant generic types.
453 See PEP 484 for more details. By default generic types are invariant
454 in all type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700455
456 Type variables can be introspected. e.g.:
457
458 T.__name__ == 'T'
459 T.__constraints__ == ()
460 T.__covariant__ == False
461 T.__contravariant__ = False
462 A.__constraints__ == (str, bytes)
463 """
464
Guido van Rossum4cefe742016-09-27 15:20:12 -0700465 __slots__ = ('__name__', '__bound__', '__constraints__',
466 '__covariant__', '__contravariant__')
467
468 def __init__(self, name, *constraints, bound=None,
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800469 covariant=False, contravariant=False):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700470 super().__init__(name, *constraints, bound=bound,
471 covariant=covariant, contravariant=contravariant)
472 self.__name__ = name
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700473 if covariant and contravariant:
Guido van Rossumefa798d2016-08-23 11:01:50 -0700474 raise ValueError("Bivariant types are not supported.")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700475 self.__covariant__ = bool(covariant)
476 self.__contravariant__ = bool(contravariant)
477 if constraints and bound is not None:
478 raise TypeError("Constraints cannot be combined with bound=...")
479 if constraints and len(constraints) == 1:
480 raise TypeError("A single constraint is not allowed")
481 msg = "TypeVar(name, constraint, ...): constraints must be types."
482 self.__constraints__ = tuple(_type_check(t, msg) for t in constraints)
483 if bound:
484 self.__bound__ = _type_check(bound, "Bound must be a type.")
485 else:
486 self.__bound__ = None
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700487
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700488 def _get_type_vars(self, tvars):
489 if self not in tvars:
490 tvars.append(self)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700491
492 def __repr__(self):
493 if self.__covariant__:
494 prefix = '+'
495 elif self.__contravariant__:
496 prefix = '-'
497 else:
498 prefix = '~'
499 return prefix + self.__name__
500
501 def __instancecheck__(self, instance):
502 raise TypeError("Type variables cannot be used with isinstance().")
503
504 def __subclasscheck__(self, cls):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700505 raise TypeError("Type variables cannot be used with issubclass().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700506
507
508# Some unconstrained type variables. These are used by the container types.
Guido van Rossumeb9aca32016-05-24 16:38:22 -0700509# (These are not for export.)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700510T = TypeVar('T') # Any type.
511KT = TypeVar('KT') # Key type.
512VT = TypeVar('VT') # Value type.
513T_co = TypeVar('T_co', covariant=True) # Any type covariant containers.
514V_co = TypeVar('V_co', covariant=True) # Any type covariant containers.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700515VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
516T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
517
518# A useful type variable with constraints. This represents string types.
Guido van Rossumeb9aca32016-05-24 16:38:22 -0700519# (This one *is* for export!)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700520AnyStr = TypeVar('AnyStr', bytes, str)
521
522
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700523def _replace_arg(arg, tvars, args):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800524 """An internal helper function: replace arg if it is a type variable
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700525 found in tvars with corresponding substitution from args or
526 with corresponding substitution sub-tree if arg is a generic type.
527 """
528
529 if tvars is None:
530 tvars = []
Guido van Rossum83ec3022017-01-17 20:43:28 -0800531 if hasattr(arg, '_subs_tree') and isinstance(arg, (GenericMeta, _TypingBase)):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700532 return arg._subs_tree(tvars, args)
533 if isinstance(arg, TypeVar):
534 for i, tvar in enumerate(tvars):
535 if arg == tvar:
536 return args[i]
537 return arg
538
539
Guido van Rossum83ec3022017-01-17 20:43:28 -0800540# Special typing constructs Union, Optional, Generic, Callable and Tuple
541# use three special attributes for internal bookkeeping of generic types:
542# * __parameters__ is a tuple of unique free type parameters of a generic
543# type, for example, Dict[T, T].__parameters__ == (T,);
544# * __origin__ keeps a reference to a type that was subscripted,
545# e.g., Union[T, int].__origin__ == Union;
546# * __args__ is a tuple of all arguments used in subscripting,
547# e.g., Dict[T, int].__args__ == (T, int).
548
549
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700550def _subs_tree(cls, tvars=None, args=None):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800551 """An internal helper function: calculate substitution tree
552 for generic cls after replacing its type parameters with
553 substitutions in tvars -> args (if any).
554 Repeat the same following __origin__'s.
555
556 Return a list of arguments with all possible substitutions
557 performed. Arguments that are generic classes themselves are represented
558 as tuples (so that no new classes are created by this function).
559 For example: _subs_tree(List[Tuple[int, T]][str]) == [(Tuple, int, str)]
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700560 """
561
562 if cls.__origin__ is None:
563 return cls
564 # Make of chain of origins (i.e. cls -> cls.__origin__)
565 current = cls.__origin__
566 orig_chain = []
567 while current.__origin__ is not None:
568 orig_chain.append(current)
569 current = current.__origin__
570 # Replace type variables in __args__ if asked ...
571 tree_args = []
572 for arg in cls.__args__:
573 tree_args.append(_replace_arg(arg, tvars, args))
574 # ... then continue replacing down the origin chain.
575 for ocls in orig_chain:
576 new_tree_args = []
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800577 for arg in ocls.__args__:
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700578 new_tree_args.append(_replace_arg(arg, ocls.__parameters__, tree_args))
579 tree_args = new_tree_args
580 return tree_args
581
582
583def _remove_dups_flatten(parameters):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800584 """An internal helper for Union creation and substitution: flatten Union's
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700585 among parameters, then remove duplicates and strict subclasses.
586 """
587
588 # Flatten out Union[Union[...], ...].
589 params = []
590 for p in parameters:
591 if isinstance(p, _Union) and p.__origin__ is Union:
592 params.extend(p.__args__)
593 elif isinstance(p, tuple) and len(p) > 0 and p[0] is Union:
594 params.extend(p[1:])
595 else:
596 params.append(p)
597 # Weed out strict duplicates, preserving the first of each occurrence.
598 all_params = set(params)
599 if len(all_params) < len(params):
600 new_params = []
601 for t in params:
602 if t in all_params:
603 new_params.append(t)
604 all_params.remove(t)
605 params = new_params
606 assert not all_params, all_params
607 # Weed out subclasses.
608 # E.g. Union[int, Employee, Manager] == Union[int, Employee].
609 # If object is present it will be sole survivor among proper classes.
610 # Never discard type variables.
611 # (In particular, Union[str, AnyStr] != AnyStr.)
612 all_params = set(params)
613 for t1 in params:
614 if not isinstance(t1, type):
615 continue
616 if any(isinstance(t2, type) and issubclass(t1, t2)
617 for t2 in all_params - {t1}
618 if not (isinstance(t2, GenericMeta) and
619 t2.__origin__ is not None)):
620 all_params.remove(t1)
621 return tuple(t for t in params if t in all_params)
622
623
624def _check_generic(cls, parameters):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800625 # Check correct count for parameters of a generic cls (internal helper).
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700626 if not cls.__parameters__:
627 raise TypeError("%s is not a generic class" % repr(cls))
628 alen = len(parameters)
629 elen = len(cls.__parameters__)
630 if alen != elen:
631 raise TypeError("Too %s parameters for %s; actual %s, expected %s" %
632 ("many" if alen > elen else "few", repr(cls), alen, elen))
633
634
Guido van Rossum9b107562016-11-09 13:23:04 -0800635_cleanups = []
636
637
Guido van Rossum4cefe742016-09-27 15:20:12 -0700638def _tp_cache(func):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800639 """Internal wrapper caching __getitem__ of generic types with a fallback to
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700640 original function for non-hashable arguments.
641 """
642
Guido van Rossum4cefe742016-09-27 15:20:12 -0700643 cached = functools.lru_cache()(func)
Guido van Rossum9b107562016-11-09 13:23:04 -0800644 _cleanups.append(cached.cache_clear)
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800645
Guido van Rossum4cefe742016-09-27 15:20:12 -0700646 @functools.wraps(func)
647 def inner(*args, **kwds):
648 try:
649 return cached(*args, **kwds)
650 except TypeError:
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700651 pass # All real errors (not unhashable args) are raised below.
Guido van Rossum4cefe742016-09-27 15:20:12 -0700652 return func(*args, **kwds)
653 return inner
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700654
655
Guido van Rossum4cefe742016-09-27 15:20:12 -0700656class _Union(_FinalTypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700657 """Union type; Union[X, Y] means either X or Y.
658
659 To define a union, use e.g. Union[int, str]. Details:
660
661 - The arguments must be types and there must be at least one.
662
663 - None as an argument is a special case and is replaced by
664 type(None).
665
666 - Unions of unions are flattened, e.g.::
667
668 Union[Union[int, str], float] == Union[int, str, float]
669
670 - Unions of a single argument vanish, e.g.::
671
672 Union[int] == int # The constructor actually returns int
673
674 - Redundant arguments are skipped, e.g.::
675
676 Union[int, str, int] == Union[int, str]
677
678 - When comparing unions, the argument order is ignored, e.g.::
679
680 Union[int, str] == Union[str, int]
681
682 - When two arguments have a subclass relationship, the least
683 derived argument is kept, e.g.::
684
685 class Employee: pass
686 class Manager(Employee): pass
687 Union[int, Employee, Manager] == Union[int, Employee]
688 Union[Manager, int, Employee] == Union[int, Employee]
689 Union[Employee, Manager] == Employee
690
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700691 - Similar for object::
692
693 Union[int, object] == object
694
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700695 - You cannot subclass or instantiate a union.
696
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700697 - You can use Optional[X] as a shorthand for Union[X, None].
698 """
699
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700700 __slots__ = ('__parameters__', '__args__', '__origin__', '__tree_hash__')
Guido van Rossum4cefe742016-09-27 15:20:12 -0700701
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700702 def __new__(cls, parameters=None, origin=None, *args, _root=False):
703 self = super().__new__(cls, parameters, origin, *args, _root=_root)
704 if origin is None:
705 self.__parameters__ = None
706 self.__args__ = None
707 self.__origin__ = None
708 self.__tree_hash__ = hash(frozenset(('Union',)))
Guido van Rossum4cefe742016-09-27 15:20:12 -0700709 return self
710 if not isinstance(parameters, tuple):
711 raise TypeError("Expected parameters=<tuple>")
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700712 if origin is Union:
713 parameters = _remove_dups_flatten(parameters)
714 # It's not a union if there's only one type left.
715 if len(parameters) == 1:
716 return parameters[0]
717 self.__parameters__ = _type_vars(parameters)
718 self.__args__ = parameters
719 self.__origin__ = origin
720 # Pre-calculate the __hash__ on instantiation.
721 # This improves speed for complex substitutions.
722 subs_tree = self._subs_tree()
723 if isinstance(subs_tree, tuple):
724 self.__tree_hash__ = hash(frozenset(subs_tree))
725 else:
726 self.__tree_hash__ = hash(subs_tree)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700727 return self
728
729 def _eval_type(self, globalns, localns):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700730 if self.__args__ is None:
Guido van Rossum4cefe742016-09-27 15:20:12 -0700731 return self
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700732 ev_args = tuple(_eval_type(t, globalns, localns) for t in self.__args__)
733 ev_origin = _eval_type(self.__origin__, globalns, localns)
734 if ev_args == self.__args__ and ev_origin == self.__origin__:
735 # Everything is already evaluated.
736 return self
737 return self.__class__(ev_args, ev_origin, _root=True)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700738
739 def _get_type_vars(self, tvars):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700740 if self.__origin__ and self.__parameters__:
741 _get_type_vars(self.__parameters__, tvars)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700742
743 def __repr__(self):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700744 if self.__origin__ is None:
745 return super().__repr__()
746 tree = self._subs_tree()
747 if not isinstance(tree, tuple):
748 return repr(tree)
749 return tree[0]._tree_repr(tree)
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700750
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700751 def _tree_repr(self, tree):
752 arg_list = []
753 for arg in tree[1:]:
754 if not isinstance(arg, tuple):
755 arg_list.append(_type_repr(arg))
756 else:
757 arg_list.append(arg[0]._tree_repr(arg))
758 return super().__repr__() + '[%s]' % ', '.join(arg_list)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700759
760 @_tp_cache
761 def __getitem__(self, parameters):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700762 if parameters == ():
763 raise TypeError("Cannot take a Union of no types.")
764 if not isinstance(parameters, tuple):
765 parameters = (parameters,)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700766 if self.__origin__ is None:
767 msg = "Union[arg, ...]: each arg must be a type."
768 else:
769 msg = "Parameters to generic types must be types."
770 parameters = tuple(_type_check(p, msg) for p in parameters)
771 if self is not Union:
772 _check_generic(self, parameters)
773 return self.__class__(parameters, origin=self, _root=True)
774
775 def _subs_tree(self, tvars=None, args=None):
776 if self is Union:
777 return Union # Nothing to substitute
778 tree_args = _subs_tree(self, tvars, args)
779 tree_args = _remove_dups_flatten(tree_args)
780 if len(tree_args) == 1:
781 return tree_args[0] # Union of a single type is that type
782 return (Union,) + tree_args
Guido van Rossum4cefe742016-09-27 15:20:12 -0700783
784 def __eq__(self, other):
Guido van Rossum83ec3022017-01-17 20:43:28 -0800785 if isinstance(other, _Union):
786 return self.__tree_hash__ == other.__tree_hash__
787 elif self is not Union:
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700788 return self._subs_tree() == other
Guido van Rossum83ec3022017-01-17 20:43:28 -0800789 else:
790 return self is other
Guido van Rossum4cefe742016-09-27 15:20:12 -0700791
792 def __hash__(self):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700793 return self.__tree_hash__
Guido van Rossum4cefe742016-09-27 15:20:12 -0700794
795 def __instancecheck__(self, obj):
796 raise TypeError("Unions cannot be used with isinstance().")
797
798 def __subclasscheck__(self, cls):
799 raise TypeError("Unions cannot be used with issubclass().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700800
801
Guido van Rossum4cefe742016-09-27 15:20:12 -0700802Union = _Union(_root=True)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700803
804
Guido van Rossum4cefe742016-09-27 15:20:12 -0700805class _Optional(_FinalTypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700806 """Optional type.
807
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700808 Optional[X] is equivalent to Union[X, None].
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700809 """
810
Guido van Rossumd70fe632015-08-05 12:11:06 +0200811 __slots__ = ()
812
Guido van Rossum4cefe742016-09-27 15:20:12 -0700813 @_tp_cache
814 def __getitem__(self, arg):
815 arg = _type_check(arg, "Optional[t] requires a single type.")
816 return Union[arg, type(None)]
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700817
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700818
Guido van Rossum4cefe742016-09-27 15:20:12 -0700819Optional = _Optional(_root=True)
820
821
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700822def _gorg(a):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800823 """Return the farthest origin of a generic class (internal helper)."""
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700824 assert isinstance(a, GenericMeta)
825 while a.__origin__ is not None:
826 a = a.__origin__
827 return a
828
829
830def _geqv(a, b):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800831 """Return whether two generic classes are equivalent (internal helper).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700832
833 The intention is to consider generic class X and any of its
Guido van Rossumb24569a2016-11-20 18:01:29 -0800834 parameterized forms (X[T], X[int], etc.) as equivalent.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700835
836 However, X is not equivalent to a subclass of X.
837
838 The relation is reflexive, symmetric and transitive.
839 """
840 assert isinstance(a, GenericMeta) and isinstance(b, GenericMeta)
841 # Reduce each to its origin.
842 return _gorg(a) is _gorg(b)
843
844
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700845def _next_in_mro(cls):
846 """Helper for Generic.__new__.
847
848 Returns the class after the last occurrence of Generic or
849 Generic[...] in cls.__mro__.
850 """
851 next_in_mro = object
852 # Look for the last occurrence of Generic or Generic[...].
853 for i, c in enumerate(cls.__mro__[:-1]):
854 if isinstance(c, GenericMeta) and _gorg(c) is Generic:
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800855 next_in_mro = cls.__mro__[i + 1]
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700856 return next_in_mro
857
858
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700859def _make_subclasshook(cls):
860 """Construct a __subclasshook__ callable that incorporates
861 the associated __extra__ class in subclass checks performed
862 against cls.
863 """
864 if isinstance(cls.__extra__, abc.ABCMeta):
865 # The logic mirrors that of ABCMeta.__subclasscheck__.
866 # Registered classes need not be checked here because
867 # cls and its extra share the same _abc_registry.
868 def __extrahook__(subclass):
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700869 res = cls.__extra__.__subclasshook__(subclass)
870 if res is not NotImplemented:
871 return res
872 if cls.__extra__ in subclass.__mro__:
873 return True
874 for scls in cls.__extra__.__subclasses__():
875 if isinstance(scls, GenericMeta):
876 continue
877 if issubclass(subclass, scls):
878 return True
879 return NotImplemented
880 else:
881 # For non-ABC extras we'll just call issubclass().
882 def __extrahook__(subclass):
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700883 if cls.__extra__ and issubclass(subclass, cls.__extra__):
884 return True
885 return NotImplemented
886 return __extrahook__
887
888
Guido van Rossum61f0a022016-11-29 09:46:21 -0800889def _no_slots_copy(dct):
890 """Internal helper: copy class __dict__ and clean slots class variables.
891 (They will be re-created if necessary by normal class machinery.)
892 """
893 dict_copy = dict(dct)
894 if '__slots__' in dict_copy:
895 for slot in dict_copy['__slots__']:
896 dict_copy.pop(slot, None)
897 return dict_copy
898
899
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700900class GenericMeta(TypingMeta, abc.ABCMeta):
Guido van Rossum83ec3022017-01-17 20:43:28 -0800901 """Metaclass for generic types.
902
903 This is a metaclass for typing.Generic and generic ABCs defined in
904 typing module. User defined subclasses of GenericMeta can override
905 __new__ and invoke super().__new__. Note that GenericMeta.__new__
906 has strict rules on what is allowed in its bases argument:
907 * plain Generic is disallowed in bases;
908 * Generic[...] should appear in bases at most once;
909 * if Generic[...] is present, then it should list all type variables
910 that appear in other bases.
911 In addition, type of all generic bases is erased, e.g., C[int] is
912 stripped to plain C.
913 """
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700914
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700915 def __new__(cls, name, bases, namespace,
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700916 tvars=None, args=None, origin=None, extra=None, orig_bases=None):
Guido van Rossum83ec3022017-01-17 20:43:28 -0800917 """Create a new generic class. GenericMeta.__new__ accepts
918 keyword arguments that are used for internal bookkeeping, therefore
919 an override should pass unused keyword arguments to super().
920 """
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700921 if tvars is not None:
922 # Called from __getitem__() below.
923 assert origin is not None
924 assert all(isinstance(t, TypeVar) for t in tvars), tvars
925 else:
926 # Called from class statement.
927 assert tvars is None, tvars
928 assert args is None, args
929 assert origin is None, origin
930
931 # Get the full set of tvars from the bases.
932 tvars = _type_vars(bases)
933 # Look for Generic[T1, ..., Tn].
934 # If found, tvars must be a subset of it.
935 # If not found, tvars is it.
936 # Also check for and reject plain Generic,
937 # and reject multiple Generic[...].
938 gvars = None
939 for base in bases:
940 if base is Generic:
941 raise TypeError("Cannot inherit from plain Generic")
942 if (isinstance(base, GenericMeta) and
943 base.__origin__ is Generic):
944 if gvars is not None:
945 raise TypeError(
946 "Cannot inherit from Generic[...] multiple types.")
947 gvars = base.__parameters__
948 if gvars is None:
949 gvars = tvars
950 else:
951 tvarset = set(tvars)
952 gvarset = set(gvars)
953 if not tvarset <= gvarset:
954 raise TypeError(
955 "Some type variables (%s) "
956 "are not listed in Generic[%s]" %
957 (", ".join(str(t) for t in tvars if t not in gvarset),
958 ", ".join(str(g) for g in gvars)))
959 tvars = gvars
960
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700961 initial_bases = bases
962 if extra is not None and type(extra) is abc.ABCMeta and extra not in bases:
963 bases = (extra,) + bases
964 bases = tuple(_gorg(b) if isinstance(b, GenericMeta) else b for b in bases)
965
966 # remove bare Generic from bases if there are other generic bases
967 if any(isinstance(b, GenericMeta) and b is not Generic for b in bases):
968 bases = tuple(b for b in bases if b is not Generic)
Mariatta0230e642017-02-14 06:11:12 -0800969 namespace.update({'__origin__': origin, '__extra__': extra})
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700970 self = super().__new__(cls, name, bases, namespace, _root=True)
971
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700972 self.__parameters__ = tvars
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700973 # Be prepared that GenericMeta will be subclassed by TupleMeta
974 # and CallableMeta, those two allow ..., (), or [] in __args___.
975 self.__args__ = tuple(... if a is _TypingEllipsis else
976 () if a is _TypingEmpty else
977 a for a in args) if args else None
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700978 # Speed hack (https://github.com/python/typing/issues/196).
979 self.__next_in_mro__ = _next_in_mro(self)
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700980 # Preserve base classes on subclassing (__bases__ are type erased now).
981 if orig_bases is None:
982 self.__orig_bases__ = initial_bases
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700983
984 # This allows unparameterized generic collections to be used
985 # with issubclass() and isinstance() in the same way as their
986 # collections.abc counterparts (e.g., isinstance([], Iterable)).
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800987 if (
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800988 '__subclasshook__' not in namespace and extra or
Mariatta0230e642017-02-14 06:11:12 -0800989 # allow overriding
990 getattr(self.__subclasshook__, '__name__', '') == '__extrahook__'
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800991 ):
Guido van Rossume2592672016-10-08 20:27:22 -0700992 self.__subclasshook__ = _make_subclasshook(self)
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700993 if isinstance(extra, abc.ABCMeta):
994 self._abc_registry = extra._abc_registry
Mariatta0230e642017-02-14 06:11:12 -0800995 self._abc_cache = extra._abc_cache
996 elif origin is not None:
997 self._abc_registry = origin._abc_registry
998 self._abc_cache = origin._abc_cache
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700999
1000 if origin and hasattr(origin, '__qualname__'): # Fix for Python 3.2.
1001 self.__qualname__ = origin.__qualname__
Mariatta0230e642017-02-14 06:11:12 -08001002 self.__tree_hash__ = (hash(self._subs_tree()) if origin else
1003 super(GenericMeta, self).__hash__())
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001004 return self
1005
Mariatta0230e642017-02-14 06:11:12 -08001006 # _abc_negative_cache and _abc_negative_cache_version
1007 # realised as descriptors, since GenClass[t1, t2, ...] always
1008 # share subclass info with GenClass.
1009 # This is an important memory optimization.
1010 @property
1011 def _abc_negative_cache(self):
1012 if isinstance(self.__extra__, abc.ABCMeta):
1013 return self.__extra__._abc_negative_cache
1014 return _gorg(self)._abc_generic_negative_cache
1015
1016 @_abc_negative_cache.setter
1017 def _abc_negative_cache(self, value):
1018 if self.__origin__ is None:
1019 if isinstance(self.__extra__, abc.ABCMeta):
1020 self.__extra__._abc_negative_cache = value
1021 else:
1022 self._abc_generic_negative_cache = value
1023
1024 @property
1025 def _abc_negative_cache_version(self):
1026 if isinstance(self.__extra__, abc.ABCMeta):
1027 return self.__extra__._abc_negative_cache_version
1028 return _gorg(self)._abc_generic_negative_cache_version
1029
1030 @_abc_negative_cache_version.setter
1031 def _abc_negative_cache_version(self, value):
1032 if self.__origin__ is None:
1033 if isinstance(self.__extra__, abc.ABCMeta):
1034 self.__extra__._abc_negative_cache_version = value
1035 else:
1036 self._abc_generic_negative_cache_version = value
1037
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001038 def _get_type_vars(self, tvars):
1039 if self.__origin__ and self.__parameters__:
1040 _get_type_vars(self.__parameters__, tvars)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001041
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001042 def _eval_type(self, globalns, localns):
1043 ev_origin = (self.__origin__._eval_type(globalns, localns)
1044 if self.__origin__ else None)
1045 ev_args = tuple(_eval_type(a, globalns, localns) for a
1046 in self.__args__) if self.__args__ else None
1047 if ev_origin == self.__origin__ and ev_args == self.__args__:
1048 return self
1049 return self.__class__(self.__name__,
1050 self.__bases__,
Guido van Rossum61f0a022016-11-29 09:46:21 -08001051 _no_slots_copy(self.__dict__),
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001052 tvars=_type_vars(ev_args) if ev_args else None,
1053 args=ev_args,
1054 origin=ev_origin,
1055 extra=self.__extra__,
1056 orig_bases=self.__orig_bases__)
1057
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001058 def __repr__(self):
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001059 if self.__origin__ is None:
1060 return super().__repr__()
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001061 return self._tree_repr(self._subs_tree())
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001062
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001063 def _tree_repr(self, tree):
1064 arg_list = []
1065 for arg in tree[1:]:
1066 if arg == ():
1067 arg_list.append('()')
1068 elif not isinstance(arg, tuple):
1069 arg_list.append(_type_repr(arg))
1070 else:
1071 arg_list.append(arg[0]._tree_repr(arg))
1072 return super().__repr__() + '[%s]' % ', '.join(arg_list)
1073
1074 def _subs_tree(self, tvars=None, args=None):
1075 if self.__origin__ is None:
1076 return self
1077 tree_args = _subs_tree(self, tvars, args)
1078 return (_gorg(self),) + tuple(tree_args)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001079
1080 def __eq__(self, other):
1081 if not isinstance(other, GenericMeta):
1082 return NotImplemented
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001083 if self.__origin__ is None or other.__origin__ is None:
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001084 return self is other
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001085 return self.__tree_hash__ == other.__tree_hash__
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001086
1087 def __hash__(self):
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001088 return self.__tree_hash__
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001089
Guido van Rossum4cefe742016-09-27 15:20:12 -07001090 @_tp_cache
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001091 def __getitem__(self, params):
1092 if not isinstance(params, tuple):
1093 params = (params,)
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001094 if not params and not _gorg(self) is Tuple:
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001095 raise TypeError(
1096 "Parameter list to %s[...] cannot be empty" % _qualname(self))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001097 msg = "Parameters to generic types must be types."
1098 params = tuple(_type_check(p, msg) for p in params)
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001099 if self is Generic:
1100 # Generic can only be subscripted with unique type variables.
1101 if not all(isinstance(p, TypeVar) for p in params):
1102 raise TypeError(
1103 "Parameters to Generic[...] must all be type variables")
Guido van Rossumd70fe632015-08-05 12:11:06 +02001104 if len(set(params)) != len(params):
Guido van Rossum1b669102015-09-04 12:15:54 -07001105 raise TypeError(
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001106 "Parameters to Generic[...] must all be unique")
1107 tvars = params
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001108 args = params
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001109 elif self in (Tuple, Callable):
1110 tvars = _type_vars(params)
1111 args = params
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001112 elif self is _Protocol:
1113 # _Protocol is internal, don't check anything.
1114 tvars = params
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001115 args = params
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001116 elif self.__origin__ in (Generic, _Protocol):
1117 # Can't subscript Generic[...] or _Protocol[...].
1118 raise TypeError("Cannot subscript already-subscripted %s" %
1119 repr(self))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001120 else:
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001121 # Subscripting a regular Generic subclass.
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001122 _check_generic(self, params)
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001123 tvars = _type_vars(params)
1124 args = params
Mariatta0230e642017-02-14 06:11:12 -08001125
1126 prepend = (self,) if self.__origin__ is None else ()
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001127 return self.__class__(self.__name__,
Mariatta0230e642017-02-14 06:11:12 -08001128 prepend + self.__bases__,
Guido van Rossum61f0a022016-11-29 09:46:21 -08001129 _no_slots_copy(self.__dict__),
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001130 tvars=tvars,
1131 args=args,
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001132 origin=self,
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001133 extra=self.__extra__,
1134 orig_bases=self.__orig_bases__)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001135
Mariatta0230e642017-02-14 06:11:12 -08001136 def __subclasscheck__(self, cls):
1137 if self.__origin__ is not None:
1138 if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools']:
1139 raise TypeError("Parameterized generics cannot be used with class "
1140 "or instance checks")
1141 return False
1142 if self is Generic:
1143 raise TypeError("Class %r cannot be used with class "
1144 "or instance checks" % self)
1145 return super().__subclasscheck__(cls)
1146
Guido van Rossum1b669102015-09-04 12:15:54 -07001147 def __instancecheck__(self, instance):
1148 # Since we extend ABC.__subclasscheck__ and
1149 # ABC.__instancecheck__ inlines the cache checking done by the
1150 # latter, we must extend __instancecheck__ too. For simplicity
1151 # we just skip the cache check -- instance checks for generic
1152 # classes are supposed to be rare anyways.
Guido van Rossumb47c9d22016-10-03 08:40:50 -07001153 return issubclass(instance.__class__, self)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001154
Guido van Rossumb7dedc82016-10-29 12:44:29 -07001155 def __copy__(self):
Guido van Rossum61f0a022016-11-29 09:46:21 -08001156 return self.__class__(self.__name__, self.__bases__,
1157 _no_slots_copy(self.__dict__),
Guido van Rossumb7dedc82016-10-29 12:44:29 -07001158 self.__parameters__, self.__args__, self.__origin__,
1159 self.__extra__, self.__orig_bases__)
1160
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001161
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001162# Prevent checks for Generic to crash when defining Generic.
1163Generic = None
1164
1165
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001166def _generic_new(base_cls, cls, *args, **kwds):
1167 # Assure type is erased on instantiation,
1168 # but attempt to store it in __orig_class__
1169 if cls.__origin__ is None:
1170 return base_cls.__new__(cls)
1171 else:
1172 origin = _gorg(cls)
1173 obj = base_cls.__new__(origin)
1174 try:
1175 obj.__orig_class__ = cls
1176 except AttributeError:
1177 pass
1178 obj.__init__(*args, **kwds)
1179 return obj
1180
1181
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001182class Generic(metaclass=GenericMeta):
1183 """Abstract base class for generic types.
1184
Guido van Rossumb24569a2016-11-20 18:01:29 -08001185 A generic type is typically declared by inheriting from
1186 this class parameterized with one or more type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001187 For example, a generic mapping type might be defined as::
1188
1189 class Mapping(Generic[KT, VT]):
1190 def __getitem__(self, key: KT) -> VT:
1191 ...
1192 # Etc.
1193
1194 This class can then be used as follows::
1195
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001196 def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001197 try:
1198 return mapping[key]
1199 except KeyError:
1200 return default
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001201 """
1202
Guido van Rossumd70fe632015-08-05 12:11:06 +02001203 __slots__ = ()
1204
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001205 def __new__(cls, *args, **kwds):
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001206 if _geqv(cls, Generic):
1207 raise TypeError("Type Generic cannot be instantiated; "
1208 "it can be used only as a base class")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001209 return _generic_new(cls.__next_in_mro__, cls, *args, **kwds)
1210
1211
1212class _TypingEmpty:
Guido van Rossumb24569a2016-11-20 18:01:29 -08001213 """Internal placeholder for () or []. Used by TupleMeta and CallableMeta
1214 to allow empty list/tuple in specific places, without allowing them
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001215 to sneak in where prohibited.
1216 """
1217
1218
1219class _TypingEllipsis:
Guido van Rossumb24569a2016-11-20 18:01:29 -08001220 """Internal placeholder for ... (ellipsis)."""
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001221
1222
1223class TupleMeta(GenericMeta):
Guido van Rossumb24569a2016-11-20 18:01:29 -08001224 """Metaclass for Tuple (internal)."""
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001225
1226 @_tp_cache
1227 def __getitem__(self, parameters):
1228 if self.__origin__ is not None or not _geqv(self, Tuple):
1229 # Normal generic rules apply if this is not the first subscription
1230 # or a subscription of a subclass.
1231 return super().__getitem__(parameters)
1232 if parameters == ():
1233 return super().__getitem__((_TypingEmpty,))
1234 if not isinstance(parameters, tuple):
1235 parameters = (parameters,)
1236 if len(parameters) == 2 and parameters[1] is ...:
1237 msg = "Tuple[t, ...]: t must be a type."
1238 p = _type_check(parameters[0], msg)
1239 return super().__getitem__((p, _TypingEllipsis))
1240 msg = "Tuple[t0, t1, ...]: each t must be a type."
1241 parameters = tuple(_type_check(p, msg) for p in parameters)
1242 return super().__getitem__(parameters)
1243
1244 def __instancecheck__(self, obj):
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001245 if self.__args__ is None:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001246 return isinstance(obj, tuple)
1247 raise TypeError("Parameterized Tuple cannot be used "
1248 "with isinstance().")
1249
1250 def __subclasscheck__(self, cls):
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001251 if self.__args__ is None:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001252 return issubclass(cls, tuple)
1253 raise TypeError("Parameterized Tuple cannot be used "
1254 "with issubclass().")
1255
1256
1257class Tuple(tuple, extra=tuple, metaclass=TupleMeta):
1258 """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
1259
1260 Example: Tuple[T1, T2] is a tuple of two elements corresponding
1261 to type variables T1 and T2. Tuple[int, float, str] is a tuple
1262 of an int, a float and a string.
1263
1264 To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
1265 """
1266
1267 __slots__ = ()
1268
1269 def __new__(cls, *args, **kwds):
1270 if _geqv(cls, Tuple):
1271 raise TypeError("Type Tuple cannot be instantiated; "
1272 "use tuple() instead")
1273 return _generic_new(tuple, cls, *args, **kwds)
1274
1275
1276class CallableMeta(GenericMeta):
Guido van Rossumb24569a2016-11-20 18:01:29 -08001277 """Metaclass for Callable (internal)."""
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001278
1279 def __repr__(self):
1280 if self.__origin__ is None:
1281 return super().__repr__()
1282 return self._tree_repr(self._subs_tree())
1283
1284 def _tree_repr(self, tree):
1285 if _gorg(self) is not Callable:
1286 return super()._tree_repr(tree)
1287 # For actual Callable (not its subclass) we override
1288 # super()._tree_repr() for nice formatting.
1289 arg_list = []
1290 for arg in tree[1:]:
Guido van Rossum991d14f2016-11-09 13:12:51 -08001291 if not isinstance(arg, tuple):
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001292 arg_list.append(_type_repr(arg))
1293 else:
1294 arg_list.append(arg[0]._tree_repr(arg))
Guido van Rossum991d14f2016-11-09 13:12:51 -08001295 if arg_list[0] == '...':
1296 return repr(tree[0]) + '[..., %s]' % arg_list[1]
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001297 return (repr(tree[0]) +
1298 '[[%s], %s]' % (', '.join(arg_list[:-1]), arg_list[-1]))
1299
1300 def __getitem__(self, parameters):
Guido van Rossumb24569a2016-11-20 18:01:29 -08001301 """A thin wrapper around __getitem_inner__ to provide the latter
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001302 with hashable arguments to improve speed.
1303 """
1304
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001305 if self.__origin__ is not None or not _geqv(self, Callable):
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001306 return super().__getitem__(parameters)
1307 if not isinstance(parameters, tuple) or len(parameters) != 2:
1308 raise TypeError("Callable must be used as "
1309 "Callable[[arg, ...], result].")
1310 args, result = parameters
Guido van Rossum991d14f2016-11-09 13:12:51 -08001311 if args is Ellipsis:
1312 parameters = (Ellipsis, result)
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001313 else:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001314 if not isinstance(args, list):
1315 raise TypeError("Callable[args, result]: args must be a list."
1316 " Got %.100r." % (args,))
Guido van Rossum991d14f2016-11-09 13:12:51 -08001317 parameters = (tuple(args), result)
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001318 return self.__getitem_inner__(parameters)
1319
1320 @_tp_cache
1321 def __getitem_inner__(self, parameters):
Guido van Rossum991d14f2016-11-09 13:12:51 -08001322 args, result = parameters
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001323 msg = "Callable[args, result]: result must be a type."
1324 result = _type_check(result, msg)
Guido van Rossum991d14f2016-11-09 13:12:51 -08001325 if args is Ellipsis:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001326 return super().__getitem__((_TypingEllipsis, result))
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001327 msg = "Callable[[arg, ...], result]: each arg must be a type."
1328 args = tuple(_type_check(arg, msg) for arg in args)
1329 parameters = args + (result,)
1330 return super().__getitem__(parameters)
1331
1332
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001333class Callable(extra=collections_abc.Callable, metaclass=CallableMeta):
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001334 """Callable type; Callable[[int], str] is a function of (int) -> str.
1335
1336 The subscription syntax must always be used with exactly two
1337 values: the argument list and the return type. The argument list
Guido van Rossumb24569a2016-11-20 18:01:29 -08001338 must be a list of types or ellipsis; the return type must be a single type.
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001339
1340 There is no syntax to indicate optional or keyword arguments,
1341 such function types are rarely used as callback types.
1342 """
1343
1344 __slots__ = ()
1345
1346 def __new__(cls, *args, **kwds):
1347 if _geqv(cls, Callable):
1348 raise TypeError("Type Callable cannot be instantiated; "
1349 "use a non-abstract subclass instead")
1350 return _generic_new(cls.__next_in_mro__, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001351
1352
Guido van Rossum4cefe742016-09-27 15:20:12 -07001353class _ClassVar(_FinalTypingBase, _root=True):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001354 """Special type construct to mark class variables.
1355
1356 An annotation wrapped in ClassVar indicates that a given
1357 attribute is intended to be used as a class variable and
1358 should not be set on instances of that class. Usage::
1359
1360 class Starship:
1361 stats: ClassVar[Dict[str, int]] = {} # class variable
1362 damage: int = 10 # instance variable
1363
1364 ClassVar accepts only types and cannot be further subscribed.
1365
1366 Note that ClassVar is not a class itself, and should not
1367 be used with isinstance() or issubclass().
1368 """
1369
Guido van Rossum4cefe742016-09-27 15:20:12 -07001370 __slots__ = ('__type__',)
1371
1372 def __init__(self, tp=None, **kwds):
1373 self.__type__ = tp
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001374
1375 def __getitem__(self, item):
1376 cls = type(self)
1377 if self.__type__ is None:
1378 return cls(_type_check(item,
Guido van Rossum4cefe742016-09-27 15:20:12 -07001379 '{} accepts only single type.'.format(cls.__name__[1:])),
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001380 _root=True)
1381 raise TypeError('{} cannot be further subscripted'
1382 .format(cls.__name__[1:]))
1383
1384 def _eval_type(self, globalns, localns):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001385 new_tp = _eval_type(self.__type__, globalns, localns)
1386 if new_tp == self.__type__:
1387 return self
1388 return type(self)(new_tp, _root=True)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001389
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001390 def __repr__(self):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001391 r = super().__repr__()
1392 if self.__type__ is not None:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001393 r += '[{}]'.format(_type_repr(self.__type__))
Guido van Rossum4cefe742016-09-27 15:20:12 -07001394 return r
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001395
1396 def __hash__(self):
1397 return hash((type(self).__name__, self.__type__))
1398
1399 def __eq__(self, other):
1400 if not isinstance(other, _ClassVar):
1401 return NotImplemented
1402 if self.__type__ is not None:
1403 return self.__type__ == other.__type__
1404 return self is other
1405
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001406
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001407ClassVar = _ClassVar(_root=True)
1408
1409
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001410def cast(typ, val):
1411 """Cast a value to a type.
1412
1413 This returns the value unchanged. To the type checker this
1414 signals that the return value has the designated type, but at
1415 runtime we intentionally don't check anything (we want this
1416 to be as fast as possible).
1417 """
1418 return val
1419
1420
1421def _get_defaults(func):
1422 """Internal helper to extract the default arguments, by name."""
Guido van Rossum991d14f2016-11-09 13:12:51 -08001423 try:
1424 code = func.__code__
1425 except AttributeError:
1426 # Some built-in functions don't have __code__, __defaults__, etc.
1427 return {}
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001428 pos_count = code.co_argcount
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001429 arg_names = code.co_varnames
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001430 arg_names = arg_names[:pos_count]
1431 defaults = func.__defaults__ or ()
1432 kwdefaults = func.__kwdefaults__
1433 res = dict(kwdefaults) if kwdefaults else {}
1434 pos_offset = pos_count - len(defaults)
1435 for name, value in zip(arg_names[pos_offset:], defaults):
1436 assert name not in res
1437 res[name] = value
1438 return res
1439
1440
Mariatta0230e642017-02-14 06:11:12 -08001441_allowed_types = (types.FunctionType, types.BuiltinFunctionType,
1442 types.MethodType, types.ModuleType,
1443 SlotWrapperType, MethodWrapperType, MethodDescriptorType)
1444
1445
Guido van Rossum991d14f2016-11-09 13:12:51 -08001446def get_type_hints(obj, globalns=None, localns=None):
1447 """Return type hints for an object.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001448
Guido van Rossum991d14f2016-11-09 13:12:51 -08001449 This is often the same as obj.__annotations__, but it handles
1450 forward references encoded as string literals, and if necessary
1451 adds Optional[t] if a default value equal to None is set.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001452
Guido van Rossum991d14f2016-11-09 13:12:51 -08001453 The argument may be a module, class, method, or function. The annotations
1454 are returned as a dictionary. For classes, annotations include also
1455 inherited members.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001456
Guido van Rossum991d14f2016-11-09 13:12:51 -08001457 TypeError is raised if the argument is not of a type that can contain
1458 annotations, and an empty dictionary is returned if no annotations are
1459 present.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001460
Guido van Rossum991d14f2016-11-09 13:12:51 -08001461 BEWARE -- the behavior of globalns and localns is counterintuitive
1462 (unless you are familiar with how eval() and exec() work). The
1463 search order is locals first, then globals.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001464
Guido van Rossum991d14f2016-11-09 13:12:51 -08001465 - If no dict arguments are passed, an attempt is made to use the
1466 globals from obj, and these are also used as the locals. If the
1467 object does not appear to have globals, an exception is raised.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001468
Guido van Rossum991d14f2016-11-09 13:12:51 -08001469 - If one dict argument is passed, it is used for both globals and
1470 locals.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001471
Guido van Rossum991d14f2016-11-09 13:12:51 -08001472 - If two dict arguments are passed, they specify globals and
1473 locals, respectively.
1474 """
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001475
Guido van Rossum991d14f2016-11-09 13:12:51 -08001476 if getattr(obj, '__no_type_check__', None):
1477 return {}
1478 if globalns is None:
1479 globalns = getattr(obj, '__globals__', {})
1480 if localns is None:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001481 localns = globalns
Guido van Rossum991d14f2016-11-09 13:12:51 -08001482 elif localns is None:
1483 localns = globalns
1484 # Classes require a special treatment.
1485 if isinstance(obj, type):
1486 hints = {}
1487 for base in reversed(obj.__mro__):
1488 ann = base.__dict__.get('__annotations__', {})
1489 for name, value in ann.items():
1490 if value is None:
1491 value = type(None)
1492 if isinstance(value, str):
1493 value = _ForwardRef(value)
1494 value = _eval_type(value, globalns, localns)
1495 hints[name] = value
1496 return hints
1497 hints = getattr(obj, '__annotations__', None)
1498 if hints is None:
1499 # Return empty annotations for something that _could_ have them.
Mariatta0230e642017-02-14 06:11:12 -08001500 if isinstance(obj, _allowed_types):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001501 return {}
Guido van Rossum991d14f2016-11-09 13:12:51 -08001502 else:
1503 raise TypeError('{!r} is not a module, class, method, '
1504 'or function.'.format(obj))
1505 defaults = _get_defaults(obj)
1506 hints = dict(hints)
1507 for name, value in hints.items():
1508 if value is None:
1509 value = type(None)
1510 if isinstance(value, str):
1511 value = _ForwardRef(value)
1512 value = _eval_type(value, globalns, localns)
1513 if name in defaults and defaults[name] is None:
1514 value = Optional[value]
1515 hints[name] = value
1516 return hints
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001517
1518
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001519def no_type_check(arg):
1520 """Decorator to indicate that annotations are not type hints.
1521
1522 The argument must be a class or function; if it is a class, it
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001523 applies recursively to all methods and classes defined in that class
1524 (but not to methods defined in its superclasses or subclasses).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001525
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001526 This mutates the function(s) or class(es) in place.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001527 """
1528 if isinstance(arg, type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001529 arg_attrs = arg.__dict__.copy()
1530 for attr, val in arg.__dict__.items():
1531 if val in arg.__bases__:
1532 arg_attrs.pop(attr)
1533 for obj in arg_attrs.values():
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001534 if isinstance(obj, types.FunctionType):
1535 obj.__no_type_check__ = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001536 if isinstance(obj, type):
1537 no_type_check(obj)
1538 try:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001539 arg.__no_type_check__ = True
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001540 except TypeError: # built-in classes
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001541 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001542 return arg
1543
1544
1545def no_type_check_decorator(decorator):
1546 """Decorator to give another decorator the @no_type_check effect.
1547
1548 This wraps the decorator with something that wraps the decorated
1549 function in @no_type_check.
1550 """
1551
1552 @functools.wraps(decorator)
1553 def wrapped_decorator(*args, **kwds):
1554 func = decorator(*args, **kwds)
1555 func = no_type_check(func)
1556 return func
1557
1558 return wrapped_decorator
1559
1560
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001561def _overload_dummy(*args, **kwds):
1562 """Helper for @overload to raise when called."""
1563 raise NotImplementedError(
1564 "You should not call an overloaded function. "
1565 "A series of @overload-decorated functions "
1566 "outside a stub module should always be followed "
1567 "by an implementation that is not @overload-ed.")
1568
1569
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001570def overload(func):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001571 """Decorator for overloaded functions/methods.
1572
1573 In a stub file, place two or more stub definitions for the same
1574 function in a row, each decorated with @overload. For example:
1575
1576 @overload
1577 def utf8(value: None) -> None: ...
1578 @overload
1579 def utf8(value: bytes) -> bytes: ...
1580 @overload
1581 def utf8(value: str) -> bytes: ...
1582
1583 In a non-stub file (i.e. a regular .py file), do the same but
1584 follow it with an implementation. The implementation should *not*
1585 be decorated with @overload. For example:
1586
1587 @overload
1588 def utf8(value: None) -> None: ...
1589 @overload
1590 def utf8(value: bytes) -> bytes: ...
1591 @overload
1592 def utf8(value: str) -> bytes: ...
1593 def utf8(value):
1594 # implementation goes here
1595 """
1596 return _overload_dummy
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001597
1598
1599class _ProtocolMeta(GenericMeta):
1600 """Internal metaclass for _Protocol.
1601
1602 This exists so _Protocol classes can be generic without deriving
1603 from Generic.
1604 """
1605
Guido van Rossumd70fe632015-08-05 12:11:06 +02001606 def __instancecheck__(self, obj):
Guido van Rossumca4b2522016-11-19 10:32:41 -08001607 if _Protocol not in self.__bases__:
1608 return super().__instancecheck__(obj)
Guido van Rossumd70fe632015-08-05 12:11:06 +02001609 raise TypeError("Protocols cannot be used with isinstance().")
1610
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001611 def __subclasscheck__(self, cls):
1612 if not self._is_protocol:
1613 # No structural checks since this isn't a protocol.
1614 return NotImplemented
1615
1616 if self is _Protocol:
1617 # Every class is a subclass of the empty protocol.
1618 return True
1619
1620 # Find all attributes defined in the protocol.
1621 attrs = self._get_protocol_attrs()
1622
1623 for attr in attrs:
1624 if not any(attr in d.__dict__ for d in cls.__mro__):
1625 return False
1626 return True
1627
1628 def _get_protocol_attrs(self):
1629 # Get all Protocol base classes.
1630 protocol_bases = []
1631 for c in self.__mro__:
1632 if getattr(c, '_is_protocol', False) and c.__name__ != '_Protocol':
1633 protocol_bases.append(c)
1634
1635 # Get attributes included in protocol.
1636 attrs = set()
1637 for base in protocol_bases:
1638 for attr in base.__dict__.keys():
1639 # Include attributes not defined in any non-protocol bases.
1640 for c in self.__mro__:
1641 if (c is not base and attr in c.__dict__ and
1642 not getattr(c, '_is_protocol', False)):
1643 break
1644 else:
1645 if (not attr.startswith('_abc_') and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001646 attr != '__abstractmethods__' and
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001647 attr != '__annotations__' and
1648 attr != '__weakref__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001649 attr != '_is_protocol' and
1650 attr != '__dict__' and
1651 attr != '__args__' and
1652 attr != '__slots__' and
1653 attr != '_get_protocol_attrs' and
1654 attr != '__next_in_mro__' and
1655 attr != '__parameters__' and
1656 attr != '__origin__' and
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001657 attr != '__orig_bases__' and
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001658 attr != '__extra__' and
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001659 attr != '__tree_hash__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001660 attr != '__module__'):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001661 attrs.add(attr)
1662
1663 return attrs
1664
1665
1666class _Protocol(metaclass=_ProtocolMeta):
1667 """Internal base class for protocol classes.
1668
Guido van Rossumb24569a2016-11-20 18:01:29 -08001669 This implements a simple-minded structural issubclass check
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001670 (similar but more general than the one-offs in collections.abc
1671 such as Hashable).
1672 """
1673
Guido van Rossumd70fe632015-08-05 12:11:06 +02001674 __slots__ = ()
1675
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001676 _is_protocol = True
1677
1678
1679# Various ABCs mimicking those in collections.abc.
1680# A few are simply re-exported for completeness.
1681
1682Hashable = collections_abc.Hashable # Not generic.
1683
1684
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001685if hasattr(collections_abc, 'Awaitable'):
1686 class Awaitable(Generic[T_co], extra=collections_abc.Awaitable):
1687 __slots__ = ()
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001688
1689 __all__.append('Awaitable')
1690
1691
1692if hasattr(collections_abc, 'Coroutine'):
1693 class Coroutine(Awaitable[V_co], Generic[T_co, T_contra, V_co],
1694 extra=collections_abc.Coroutine):
1695 __slots__ = ()
1696
1697 __all__.append('Coroutine')
Guido van Rossumf17c2002015-12-03 17:31:24 -08001698
1699
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001700if hasattr(collections_abc, 'AsyncIterable'):
Guido van Rossumf17c2002015-12-03 17:31:24 -08001701
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001702 class AsyncIterable(Generic[T_co], extra=collections_abc.AsyncIterable):
1703 __slots__ = ()
Guido van Rossumf17c2002015-12-03 17:31:24 -08001704
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001705 class AsyncIterator(AsyncIterable[T_co],
1706 extra=collections_abc.AsyncIterator):
1707 __slots__ = ()
1708
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001709 __all__.append('AsyncIterable')
1710 __all__.append('AsyncIterator')
Guido van Rossumf17c2002015-12-03 17:31:24 -08001711
1712
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001713class Iterable(Generic[T_co], extra=collections_abc.Iterable):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001714 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001715
1716
1717class Iterator(Iterable[T_co], extra=collections_abc.Iterator):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001718 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001719
1720
1721class SupportsInt(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001722 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001723
1724 @abstractmethod
1725 def __int__(self) -> int:
1726 pass
1727
1728
1729class SupportsFloat(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001730 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001731
1732 @abstractmethod
1733 def __float__(self) -> float:
1734 pass
1735
1736
1737class SupportsComplex(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001738 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001739
1740 @abstractmethod
1741 def __complex__(self) -> complex:
1742 pass
1743
1744
1745class SupportsBytes(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001746 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001747
1748 @abstractmethod
1749 def __bytes__(self) -> bytes:
1750 pass
1751
1752
Guido van Rossumd70fe632015-08-05 12:11:06 +02001753class SupportsAbs(_Protocol[T_co]):
1754 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001755
1756 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001757 def __abs__(self) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001758 pass
1759
1760
Guido van Rossumd70fe632015-08-05 12:11:06 +02001761class SupportsRound(_Protocol[T_co]):
1762 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001763
1764 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001765 def __round__(self, ndigits: int = 0) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001766 pass
1767
1768
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001769if hasattr(collections_abc, 'Reversible'):
1770 class Reversible(Iterable[T_co], extra=collections_abc.Reversible):
1771 __slots__ = ()
1772else:
1773 class Reversible(_Protocol[T_co]):
1774 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001775
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001776 @abstractmethod
1777 def __reversed__(self) -> 'Iterator[T_co]':
1778 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001779
1780
1781Sized = collections_abc.Sized # Not generic.
1782
1783
1784class Container(Generic[T_co], extra=collections_abc.Container):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001785 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001786
1787
Guido van Rossumefa798d2016-08-23 11:01:50 -07001788if hasattr(collections_abc, 'Collection'):
1789 class Collection(Sized, Iterable[T_co], Container[T_co],
1790 extra=collections_abc.Collection):
1791 __slots__ = ()
1792
1793 __all__.append('Collection')
1794
1795
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001796# Callable was defined earlier.
1797
Guido van Rossumefa798d2016-08-23 11:01:50 -07001798if hasattr(collections_abc, 'Collection'):
1799 class AbstractSet(Collection[T_co],
1800 extra=collections_abc.Set):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001801 __slots__ = ()
Guido van Rossumefa798d2016-08-23 11:01:50 -07001802else:
1803 class AbstractSet(Sized, Iterable[T_co], Container[T_co],
1804 extra=collections_abc.Set):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001805 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001806
1807
1808class MutableSet(AbstractSet[T], extra=collections_abc.MutableSet):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001809 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001810
1811
Guido van Rossumefa798d2016-08-23 11:01:50 -07001812# NOTE: It is only covariant in the value type.
1813if hasattr(collections_abc, 'Collection'):
1814 class Mapping(Collection[KT], Generic[KT, VT_co],
1815 extra=collections_abc.Mapping):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001816 __slots__ = ()
Guido van Rossumefa798d2016-08-23 11:01:50 -07001817else:
1818 class Mapping(Sized, Iterable[KT], Container[KT], Generic[KT, VT_co],
1819 extra=collections_abc.Mapping):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001820 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001821
1822
1823class MutableMapping(Mapping[KT, VT], extra=collections_abc.MutableMapping):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001824 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001825
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001826
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001827if hasattr(collections_abc, 'Reversible'):
Guido van Rossumefa798d2016-08-23 11:01:50 -07001828 if hasattr(collections_abc, 'Collection'):
1829 class Sequence(Reversible[T_co], Collection[T_co],
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001830 extra=collections_abc.Sequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001831 __slots__ = ()
Guido van Rossumefa798d2016-08-23 11:01:50 -07001832 else:
1833 class Sequence(Sized, Reversible[T_co], Container[T_co],
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001834 extra=collections_abc.Sequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001835 __slots__ = ()
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001836else:
1837 class Sequence(Sized, Iterable[T_co], Container[T_co],
1838 extra=collections_abc.Sequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001839 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001840
1841
1842class MutableSequence(Sequence[T], extra=collections_abc.MutableSequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001843 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001844
1845
1846class ByteString(Sequence[int], extra=collections_abc.ByteString):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001847 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001848
1849
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001850class List(list, MutableSequence[T], extra=list):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001851
Guido van Rossum4cefe742016-09-27 15:20:12 -07001852 __slots__ = ()
1853
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001854 def __new__(cls, *args, **kwds):
1855 if _geqv(cls, List):
1856 raise TypeError("Type List cannot be instantiated; "
1857 "use list() instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001858 return _generic_new(list, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001859
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001860
Raymond Hettinger80490522017-01-16 22:42:37 -08001861class Deque(collections.deque, MutableSequence[T], extra=collections.deque):
1862
1863 __slots__ = ()
1864
1865 def __new__(cls, *args, **kwds):
1866 if _geqv(cls, Deque):
Mariatta0230e642017-02-14 06:11:12 -08001867 return collections.deque(*args, **kwds)
Raymond Hettinger80490522017-01-16 22:42:37 -08001868 return _generic_new(collections.deque, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001869
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001870
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001871class Set(set, MutableSet[T], extra=set):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001872
Guido van Rossum4cefe742016-09-27 15:20:12 -07001873 __slots__ = ()
1874
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001875 def __new__(cls, *args, **kwds):
1876 if _geqv(cls, Set):
1877 raise TypeError("Type Set cannot be instantiated; "
1878 "use set() instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001879 return _generic_new(set, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001880
1881
Guido van Rossum4cefe742016-09-27 15:20:12 -07001882class FrozenSet(frozenset, AbstractSet[T_co], extra=frozenset):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001883 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001884
1885 def __new__(cls, *args, **kwds):
1886 if _geqv(cls, FrozenSet):
1887 raise TypeError("Type FrozenSet cannot be instantiated; "
1888 "use frozenset() instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001889 return _generic_new(frozenset, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001890
1891
1892class MappingView(Sized, Iterable[T_co], extra=collections_abc.MappingView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001893 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001894
1895
Guido van Rossumd70fe632015-08-05 12:11:06 +02001896class KeysView(MappingView[KT], AbstractSet[KT],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001897 extra=collections_abc.KeysView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001898 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001899
1900
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001901class ItemsView(MappingView[Tuple[KT, VT_co]],
Guido van Rossum0e0563c2016-04-05 14:54:25 -07001902 AbstractSet[Tuple[KT, VT_co]],
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001903 Generic[KT, VT_co],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001904 extra=collections_abc.ItemsView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001905 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001906
1907
1908class ValuesView(MappingView[VT_co], extra=collections_abc.ValuesView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001909 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001910
1911
Brett Cannonf3ad0422016-04-15 10:51:30 -07001912if hasattr(contextlib, 'AbstractContextManager'):
1913 class ContextManager(Generic[T_co], extra=contextlib.AbstractContextManager):
1914 __slots__ = ()
1915 __all__.append('ContextManager')
1916
1917
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001918class Dict(dict, MutableMapping[KT, VT], extra=dict):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001919
Guido van Rossum4cefe742016-09-27 15:20:12 -07001920 __slots__ = ()
1921
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001922 def __new__(cls, *args, **kwds):
1923 if _geqv(cls, Dict):
1924 raise TypeError("Type Dict cannot be instantiated; "
1925 "use dict() instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001926 return _generic_new(dict, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001927
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001928
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001929class DefaultDict(collections.defaultdict, MutableMapping[KT, VT],
1930 extra=collections.defaultdict):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001931
Guido van Rossum4cefe742016-09-27 15:20:12 -07001932 __slots__ = ()
1933
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001934 def __new__(cls, *args, **kwds):
1935 if _geqv(cls, DefaultDict):
Mariatta0230e642017-02-14 06:11:12 -08001936 return collections.defaultdict(*args, **kwds)
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001937 return _generic_new(collections.defaultdict, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001938
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001939
Mariatta0230e642017-02-14 06:11:12 -08001940class Counter(collections.Counter, Dict[T, int], extra=collections.Counter):
1941
1942 __slots__ = ()
1943
1944 def __new__(cls, *args, **kwds):
1945 if _geqv(cls, Counter):
1946 return collections.Counter(*args, **kwds)
1947 return _generic_new(collections.Counter, cls, *args, **kwds)
1948
1949
1950if hasattr(collections, 'ChainMap'):
1951 # ChainMap only exists in 3.3+
1952 __all__.append('ChainMap')
1953
1954 class ChainMap(collections.ChainMap, MutableMapping[KT, VT],
1955 extra=collections.ChainMap):
1956
1957 __slots__ = ()
1958
1959 def __new__(cls, *args, **kwds):
1960 if _geqv(cls, ChainMap):
1961 return collections.ChainMap(*args, **kwds)
1962 return _generic_new(collections.ChainMap, cls, *args, **kwds)
1963
1964
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001965# Determine what base class to use for Generator.
1966if hasattr(collections_abc, 'Generator'):
1967 # Sufficiently recent versions of 3.5 have a Generator ABC.
1968 _G_base = collections_abc.Generator
1969else:
1970 # Fall back on the exact type.
1971 _G_base = types.GeneratorType
1972
1973
1974class Generator(Iterator[T_co], Generic[T_co, T_contra, V_co],
1975 extra=_G_base):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001976 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001977
1978 def __new__(cls, *args, **kwds):
1979 if _geqv(cls, Generator):
1980 raise TypeError("Type Generator cannot be instantiated; "
1981 "create a subclass instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001982 return _generic_new(_G_base, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001983
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001984
Guido van Rossume9ed5602017-01-18 13:10:31 -08001985if hasattr(collections_abc, 'AsyncGenerator'):
1986 class AsyncGenerator(AsyncIterator[T_co], Generic[T_co, T_contra],
1987 extra=collections_abc.AsyncGenerator):
1988 __slots__ = ()
1989
1990 __all__.append('AsyncGenerator')
1991
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001992
Guido van Rossumeb9aca32016-05-24 16:38:22 -07001993# Internal type variable used for Type[].
Guido van Rossumefa798d2016-08-23 11:01:50 -07001994CT_co = TypeVar('CT_co', covariant=True, bound=type)
Guido van Rossumeb9aca32016-05-24 16:38:22 -07001995
1996
Guido van Rossumb22c7082016-05-26 09:56:19 -07001997# This is not a real generic class. Don't use outside annotations.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001998class Type(Generic[CT_co], extra=type):
Guido van Rossumb22c7082016-05-26 09:56:19 -07001999 """A special construct usable to annotate class objects.
Guido van Rossumeb9aca32016-05-24 16:38:22 -07002000
2001 For example, suppose we have the following classes::
2002
2003 class User: ... # Abstract base for User classes
2004 class BasicUser(User): ...
2005 class ProUser(User): ...
2006 class TeamUser(User): ...
2007
2008 And a function that takes a class argument that's a subclass of
2009 User and returns an instance of the corresponding class::
2010
2011 U = TypeVar('U', bound=User)
2012 def new_user(user_class: Type[U]) -> U:
2013 user = user_class()
2014 # (Here we could write the user object to a database)
2015 return user
2016
2017 joe = new_user(BasicUser)
2018
2019 At this point the type checker knows that joe has type BasicUser.
2020 """
2021
Guido van Rossum4cefe742016-09-27 15:20:12 -07002022 __slots__ = ()
2023
Guido van Rossumeb9aca32016-05-24 16:38:22 -07002024
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002025def _make_nmtuple(name, types):
Guido van Rossum2f841442016-11-15 09:48:06 -08002026 msg = "NamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a type"
2027 types = [(n, _type_check(t, msg)) for n, t in types]
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002028 nm_tpl = collections.namedtuple(name, [n for n, t in types])
Guido van Rossum83ec3022017-01-17 20:43:28 -08002029 # Prior to PEP 526, only _field_types attribute was assigned.
2030 # Now, both __annotations__ and _field_types are used to maintain compatibility.
2031 nm_tpl.__annotations__ = nm_tpl._field_types = collections.OrderedDict(types)
Guido van Rossum557d1eb2015-11-19 08:16:31 -08002032 try:
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002033 nm_tpl.__module__ = sys._getframe(2).f_globals.get('__name__', '__main__')
Guido van Rossum557d1eb2015-11-19 08:16:31 -08002034 except (AttributeError, ValueError):
2035 pass
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002036 return nm_tpl
2037
2038
Guido van Rossum2f841442016-11-15 09:48:06 -08002039_PY36 = sys.version_info[:2] >= (3, 6)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002040
Mariatta0230e642017-02-14 06:11:12 -08002041# attributes prohibited to set in NamedTuple class syntax
2042_prohibited = ('__new__', '__init__', '__slots__', '__getnewargs__',
2043 '_fields', '_field_defaults', '_field_types',
2044 '_make', '_replace', '_asdict')
2045
2046_special = ('__module__', '__name__', '__qualname__', '__annotations__')
2047
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002048
Guido van Rossum2f841442016-11-15 09:48:06 -08002049class NamedTupleMeta(type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002050
Guido van Rossum2f841442016-11-15 09:48:06 -08002051 def __new__(cls, typename, bases, ns):
2052 if ns.get('_root', False):
2053 return super().__new__(cls, typename, bases, ns)
2054 if not _PY36:
2055 raise TypeError("Class syntax for NamedTuple is only supported"
2056 " in Python 3.6+")
2057 types = ns.get('__annotations__', {})
Guido van Rossum3c268be2017-01-18 08:03:50 -08002058 nm_tpl = _make_nmtuple(typename, types.items())
2059 defaults = []
2060 defaults_dict = {}
2061 for field_name in types:
2062 if field_name in ns:
2063 default_value = ns[field_name]
2064 defaults.append(default_value)
2065 defaults_dict[field_name] = default_value
2066 elif defaults:
Guido van Rossumd7adfe12017-01-22 17:43:53 -08002067 raise TypeError("Non-default namedtuple field {field_name} cannot "
2068 "follow default field(s) {default_names}"
Guido van Rossum3c268be2017-01-18 08:03:50 -08002069 .format(field_name=field_name,
2070 default_names=', '.join(defaults_dict.keys())))
2071 nm_tpl.__new__.__defaults__ = tuple(defaults)
2072 nm_tpl._field_defaults = defaults_dict
Guido van Rossum95919c02017-01-22 17:47:20 -08002073 # update from user namespace without overriding special namedtuple attributes
2074 for key in ns:
Mariatta0230e642017-02-14 06:11:12 -08002075 if key in _prohibited:
2076 raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
2077 elif key not in _special and key not in nm_tpl._fields:
Guido van Rossum95919c02017-01-22 17:47:20 -08002078 setattr(nm_tpl, key, ns[key])
Guido van Rossum3c268be2017-01-18 08:03:50 -08002079 return nm_tpl
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002080
Guido van Rossumd7adfe12017-01-22 17:43:53 -08002081
Guido van Rossum2f841442016-11-15 09:48:06 -08002082class NamedTuple(metaclass=NamedTupleMeta):
2083 """Typed version of namedtuple.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002084
Guido van Rossum2f841442016-11-15 09:48:06 -08002085 Usage in Python versions >= 3.6::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002086
Guido van Rossum2f841442016-11-15 09:48:06 -08002087 class Employee(NamedTuple):
2088 name: str
2089 id: int
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002090
Guido van Rossum2f841442016-11-15 09:48:06 -08002091 This is equivalent to::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002092
Guido van Rossum2f841442016-11-15 09:48:06 -08002093 Employee = collections.namedtuple('Employee', ['name', 'id'])
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002094
Guido van Rossum83ec3022017-01-17 20:43:28 -08002095 The resulting class has extra __annotations__ and _field_types
2096 attributes, giving an ordered dict mapping field names to types.
2097 __annotations__ should be preferred, while _field_types
2098 is kept to maintain pre PEP 526 compatibility. (The field names
Guido van Rossum2f841442016-11-15 09:48:06 -08002099 are in the _fields attribute, which is part of the namedtuple
2100 API.) Alternative equivalent keyword syntax is also accepted::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002101
Guido van Rossum2f841442016-11-15 09:48:06 -08002102 Employee = NamedTuple('Employee', name=str, id=int)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002103
Guido van Rossum2f841442016-11-15 09:48:06 -08002104 In Python versions <= 3.5 use::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002105
Guido van Rossum2f841442016-11-15 09:48:06 -08002106 Employee = NamedTuple('Employee', [('name', str), ('id', int)])
2107 """
2108 _root = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002109
Guido van Rossum2f841442016-11-15 09:48:06 -08002110 def __new__(self, typename, fields=None, **kwargs):
2111 if kwargs and not _PY36:
2112 raise TypeError("Keyword syntax for NamedTuple is only supported"
2113 " in Python 3.6+")
2114 if fields is None:
2115 fields = kwargs.items()
2116 elif kwargs:
2117 raise TypeError("Either list of fields or keywords"
2118 " can be provided to NamedTuple, not both")
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002119 return _make_nmtuple(typename, fields)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002120
2121
Guido van Rossum91185fe2016-06-08 11:19:11 -07002122def NewType(name, tp):
2123 """NewType creates simple unique types with almost zero
2124 runtime overhead. NewType(name, tp) is considered a subtype of tp
2125 by static type checkers. At runtime, NewType(name, tp) returns
2126 a dummy function that simply returns its argument. Usage::
2127
2128 UserId = NewType('UserId', int)
2129
2130 def name_by_id(user_id: UserId) -> str:
2131 ...
2132
2133 UserId('user') # Fails type check
2134
2135 name_by_id(42) # Fails type check
2136 name_by_id(UserId(42)) # OK
2137
2138 num = UserId(5) + 1 # type: int
2139 """
2140
2141 def new_type(x):
2142 return x
2143
2144 new_type.__name__ = name
2145 new_type.__supertype__ = tp
2146 return new_type
2147
2148
Guido van Rossum0e0563c2016-04-05 14:54:25 -07002149# Python-version-specific alias (Python 2: unicode; Python 3: str)
2150Text = str
2151
2152
Guido van Rossum91185fe2016-06-08 11:19:11 -07002153# Constant that's True when type checking, but False here.
2154TYPE_CHECKING = False
2155
2156
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002157class IO(Generic[AnyStr]):
2158 """Generic base class for TextIO and BinaryIO.
2159
2160 This is an abstract, generic version of the return of open().
2161
2162 NOTE: This does not distinguish between the different possible
2163 classes (text vs. binary, read vs. write vs. read/write,
2164 append-only, unbuffered). The TextIO and BinaryIO subclasses
2165 below capture the distinctions between text vs. binary, which is
2166 pervasive in the interface; however we currently do not offer a
2167 way to track the other distinctions in the type system.
2168 """
2169
Guido van Rossumd70fe632015-08-05 12:11:06 +02002170 __slots__ = ()
2171
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002172 @abstractproperty
2173 def mode(self) -> str:
2174 pass
2175
2176 @abstractproperty
2177 def name(self) -> str:
2178 pass
2179
2180 @abstractmethod
2181 def close(self) -> None:
2182 pass
2183
2184 @abstractmethod
2185 def closed(self) -> bool:
2186 pass
2187
2188 @abstractmethod
2189 def fileno(self) -> int:
2190 pass
2191
2192 @abstractmethod
2193 def flush(self) -> None:
2194 pass
2195
2196 @abstractmethod
2197 def isatty(self) -> bool:
2198 pass
2199
2200 @abstractmethod
2201 def read(self, n: int = -1) -> AnyStr:
2202 pass
2203
2204 @abstractmethod
2205 def readable(self) -> bool:
2206 pass
2207
2208 @abstractmethod
2209 def readline(self, limit: int = -1) -> AnyStr:
2210 pass
2211
2212 @abstractmethod
2213 def readlines(self, hint: int = -1) -> List[AnyStr]:
2214 pass
2215
2216 @abstractmethod
2217 def seek(self, offset: int, whence: int = 0) -> int:
2218 pass
2219
2220 @abstractmethod
2221 def seekable(self) -> bool:
2222 pass
2223
2224 @abstractmethod
2225 def tell(self) -> int:
2226 pass
2227
2228 @abstractmethod
2229 def truncate(self, size: int = None) -> int:
2230 pass
2231
2232 @abstractmethod
2233 def writable(self) -> bool:
2234 pass
2235
2236 @abstractmethod
2237 def write(self, s: AnyStr) -> int:
2238 pass
2239
2240 @abstractmethod
2241 def writelines(self, lines: List[AnyStr]) -> None:
2242 pass
2243
2244 @abstractmethod
2245 def __enter__(self) -> 'IO[AnyStr]':
2246 pass
2247
2248 @abstractmethod
2249 def __exit__(self, type, value, traceback) -> None:
2250 pass
2251
2252
2253class BinaryIO(IO[bytes]):
2254 """Typed version of the return of open() in binary mode."""
2255
Guido van Rossumd70fe632015-08-05 12:11:06 +02002256 __slots__ = ()
2257
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002258 @abstractmethod
2259 def write(self, s: Union[bytes, bytearray]) -> int:
2260 pass
2261
2262 @abstractmethod
2263 def __enter__(self) -> 'BinaryIO':
2264 pass
2265
2266
2267class TextIO(IO[str]):
2268 """Typed version of the return of open() in text mode."""
2269
Guido van Rossumd70fe632015-08-05 12:11:06 +02002270 __slots__ = ()
2271
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002272 @abstractproperty
2273 def buffer(self) -> BinaryIO:
2274 pass
2275
2276 @abstractproperty
2277 def encoding(self) -> str:
2278 pass
2279
2280 @abstractproperty
Guido van Rossum991d14f2016-11-09 13:12:51 -08002281 def errors(self) -> Optional[str]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002282 pass
2283
2284 @abstractproperty
2285 def line_buffering(self) -> bool:
2286 pass
2287
2288 @abstractproperty
2289 def newlines(self) -> Any:
2290 pass
2291
2292 @abstractmethod
2293 def __enter__(self) -> 'TextIO':
2294 pass
2295
2296
2297class io:
2298 """Wrapper namespace for IO generic classes."""
2299
2300 __all__ = ['IO', 'TextIO', 'BinaryIO']
2301 IO = IO
2302 TextIO = TextIO
2303 BinaryIO = BinaryIO
2304
Guido van Rossumd7adfe12017-01-22 17:43:53 -08002305
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002306io.__name__ = __name__ + '.io'
2307sys.modules[io.__name__] = io
2308
2309
2310Pattern = _TypeAlias('Pattern', AnyStr, type(stdlib_re.compile('')),
2311 lambda p: p.pattern)
2312Match = _TypeAlias('Match', AnyStr, type(stdlib_re.match('', '')),
2313 lambda m: m.re.pattern)
2314
2315
2316class re:
2317 """Wrapper namespace for re type aliases."""
2318
2319 __all__ = ['Pattern', 'Match']
2320 Pattern = Pattern
2321 Match = Match
2322
Guido van Rossumd7adfe12017-01-22 17:43:53 -08002323
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002324re.__name__ = __name__ + '.re'
2325sys.modules[re.__name__] = re