blob: 0aeb089d5d61a595832b7826f293aeb9198f55ce [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.
13
14
15# Please keep __all__ alphabetized within each category.
16__all__ = [
17 # Super-special typing primitives.
18 'Any',
19 'Callable',
Guido van Rossum0a6976d2016-09-11 15:34:56 -070020 'ClassVar',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070021 'Generic',
22 'Optional',
Guido van Rossumeb9aca32016-05-24 16:38:22 -070023 'Tuple',
24 'Type',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070025 'TypeVar',
26 'Union',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070027
28 # ABCs (from collections.abc).
29 'AbstractSet', # collections.abc.Set.
Guido van Rossum83ec3022017-01-17 20:43:28 -080030 'GenericMeta', # subclass of abc.ABCMeta and a metaclass
31 # for 'Generic' and ABCs below.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070032 'ByteString',
33 'Container',
34 'Hashable',
35 'ItemsView',
36 'Iterable',
37 'Iterator',
38 'KeysView',
39 'Mapping',
40 'MappingView',
41 'MutableMapping',
42 'MutableSequence',
43 'MutableSet',
44 'Sequence',
45 'Sized',
46 'ValuesView',
Guido van Rossum62fe1bb2016-10-29 16:05:26 -070047 # The following are added depending on presence
48 # of their non-generic counterparts in stdlib:
49 # Awaitable,
50 # AsyncIterator,
51 # AsyncIterable,
52 # Coroutine,
53 # Collection,
54 # ContextManager
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070055
56 # Structural checks, a.k.a. protocols.
57 'Reversible',
58 'SupportsAbs',
59 'SupportsFloat',
60 'SupportsInt',
61 'SupportsRound',
62
63 # Concrete collection types.
Raymond Hettinger80490522017-01-16 22:42:37 -080064 'Deque',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070065 'Dict',
Guido van Rossumbd5b9a02016-04-05 08:28:52 -070066 'DefaultDict',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070067 'List',
68 'Set',
Guido van Rossumefa798d2016-08-23 11:01:50 -070069 'FrozenSet',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070070 'NamedTuple', # Not really a type.
71 'Generator',
72
73 # One-off things.
74 'AnyStr',
75 'cast',
76 'get_type_hints',
Guido van Rossum91185fe2016-06-08 11:19:11 -070077 'NewType',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070078 'no_type_check',
79 'no_type_check_decorator',
80 'overload',
Guido van Rossum0e0563c2016-04-05 14:54:25 -070081 'Text',
Guido van Rossum91185fe2016-06-08 11:19:11 -070082 'TYPE_CHECKING',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070083]
84
Guido van Rossumbd5b9a02016-04-05 08:28:52 -070085# The pseudo-submodules 're' and 'io' are part of the public
86# namespace, but excluded from __all__ because they might stomp on
87# legitimate imports of those modules.
88
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070089
90def _qualname(x):
91 if sys.version_info[:2] >= (3, 3):
92 return x.__qualname__
93 else:
94 # Fall back to just name.
95 return x.__name__
96
97
Guido van Rossum4cefe742016-09-27 15:20:12 -070098def _trim_name(nm):
99 if nm.startswith('_') and nm not in ('_TypeAlias',
100 '_ForwardRef', '_TypingBase', '_FinalTypingBase'):
101 nm = nm[1:]
102 return nm
103
104
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700105class TypingMeta(type):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800106 """Metaclass for most types defined in typing module
107 (not a part of public API).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700108
109 This overrides __new__() to require an extra keyword parameter
110 '_root', which serves as a guard against naive subclassing of the
111 typing classes. Any legitimate class defined using a metaclass
Guido van Rossumb24569a2016-11-20 18:01:29 -0800112 derived from TypingMeta must pass _root=True.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700113
Guido van Rossumb24569a2016-11-20 18:01:29 -0800114 This also defines a dummy constructor (all the work for most typing
115 constructs is done in __new__) and a nicer repr().
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700116 """
117
118 _is_protocol = False
119
120 def __new__(cls, name, bases, namespace, *, _root=False):
121 if not _root:
122 raise TypeError("Cannot subclass %s" %
123 (', '.join(map(_type_repr, bases)) or '()'))
124 return super().__new__(cls, name, bases, namespace)
125
126 def __init__(self, *args, **kwds):
127 pass
128
129 def _eval_type(self, globalns, localns):
130 """Override this in subclasses to interpret forward references.
131
Guido van Rossumb24569a2016-11-20 18:01:29 -0800132 For example, List['C'] is internally stored as
133 List[_ForwardRef('C')], which should evaluate to List[C],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700134 where C is an object found in globalns or localns (searching
135 localns first, of course).
136 """
137 return self
138
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700139 def _get_type_vars(self, tvars):
140 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700141
142 def __repr__(self):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700143 qname = _trim_name(_qualname(self))
144 return '%s.%s' % (self.__module__, qname)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700145
146
Guido van Rossum4cefe742016-09-27 15:20:12 -0700147class _TypingBase(metaclass=TypingMeta, _root=True):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800148 """Internal indicator of special typing constructs."""
Guido van Rossum4cefe742016-09-27 15:20:12 -0700149
Guido van Rossum83ec3022017-01-17 20:43:28 -0800150 __slots__ = ('__weakref__',)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700151
Guido van Rossum4cefe742016-09-27 15:20:12 -0700152 def __init__(self, *args, **kwds):
153 pass
154
155 def __new__(cls, *args, **kwds):
156 """Constructor.
157
158 This only exists to give a better error message in case
159 someone tries to subclass a special typing object (not a good idea).
160 """
161 if (len(args) == 3 and
162 isinstance(args[0], str) and
163 isinstance(args[1], tuple)):
164 # Close enough.
165 raise TypeError("Cannot subclass %r" % cls)
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700166 return super().__new__(cls)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700167
168 # Things that are not classes also need these.
169 def _eval_type(self, globalns, localns):
170 return self
171
172 def _get_type_vars(self, tvars):
173 pass
174
175 def __repr__(self):
176 cls = type(self)
177 qname = _trim_name(_qualname(cls))
178 return '%s.%s' % (cls.__module__, qname)
179
180 def __call__(self, *args, **kwds):
181 raise TypeError("Cannot instantiate %r" % type(self))
182
183
184class _FinalTypingBase(_TypingBase, _root=True):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800185 """Internal mix-in class to prevent instantiation.
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700186
187 Prevents instantiation unless _root=True is given in class call.
Guido van Rossumb24569a2016-11-20 18:01:29 -0800188 It is used to create pseudo-singleton instances Any, Union, Optional, etc.
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700189 """
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700190
Guido van Rossumd70fe632015-08-05 12:11:06 +0200191 __slots__ = ()
192
Guido van Rossum4cefe742016-09-27 15:20:12 -0700193 def __new__(cls, *args, _root=False, **kwds):
194 self = super().__new__(cls, *args, **kwds)
195 if _root is True:
196 return self
197 raise TypeError("Cannot instantiate %r" % cls)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700198
Guido van Rossumb7dedc82016-10-29 12:44:29 -0700199 def __reduce__(self):
200 return _trim_name(type(self).__name__)
201
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700202
Guido van Rossum4cefe742016-09-27 15:20:12 -0700203class _ForwardRef(_TypingBase, _root=True):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800204 """Internal wrapper to hold a forward reference."""
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700205
Guido van Rossum4cefe742016-09-27 15:20:12 -0700206 __slots__ = ('__forward_arg__', '__forward_code__',
Guido van Rossumc7b92952016-11-10 08:24:06 -0800207 '__forward_evaluated__', '__forward_value__')
Guido van Rossum4cefe742016-09-27 15:20:12 -0700208
209 def __init__(self, arg):
210 super().__init__(arg)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700211 if not isinstance(arg, str):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800212 raise TypeError('Forward reference must be a string -- got %r' % (arg,))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700213 try:
214 code = compile(arg, '<string>', 'eval')
215 except SyntaxError:
Guido van Rossumb24569a2016-11-20 18:01:29 -0800216 raise SyntaxError('Forward reference must be an expression -- got %r' %
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700217 (arg,))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700218 self.__forward_arg__ = arg
219 self.__forward_code__ = code
220 self.__forward_evaluated__ = False
221 self.__forward_value__ = None
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700222
223 def _eval_type(self, globalns, localns):
Guido van Rossumdad17902016-11-10 08:29:18 -0800224 if not self.__forward_evaluated__ or localns is not globalns:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700225 if globalns is None and localns is None:
226 globalns = localns = {}
227 elif globalns is None:
228 globalns = localns
229 elif localns is None:
230 localns = globalns
231 self.__forward_value__ = _type_check(
232 eval(self.__forward_code__, globalns, localns),
233 "Forward references must evaluate to types.")
234 self.__forward_evaluated__ = True
235 return self.__forward_value__
236
Guido van Rossum4cefe742016-09-27 15:20:12 -0700237 def __eq__(self, other):
238 if not isinstance(other, _ForwardRef):
239 return NotImplemented
240 return (self.__forward_arg__ == other.__forward_arg__ and
Guido van Rossumc7b92952016-11-10 08:24:06 -0800241 self.__forward_value__ == other.__forward_value__)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700242
243 def __hash__(self):
Guido van Rossumc7b92952016-11-10 08:24:06 -0800244 return hash((self.__forward_arg__, self.__forward_value__))
Guido van Rossum4cefe742016-09-27 15:20:12 -0700245
Guido van Rossumd70fe632015-08-05 12:11:06 +0200246 def __instancecheck__(self, obj):
247 raise TypeError("Forward references cannot be used with isinstance().")
248
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700249 def __subclasscheck__(self, cls):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700250 raise TypeError("Forward references cannot be used with issubclass().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700251
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700252 def __repr__(self):
253 return '_ForwardRef(%r)' % (self.__forward_arg__,)
254
255
Guido van Rossum4cefe742016-09-27 15:20:12 -0700256class _TypeAlias(_TypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700257 """Internal helper class for defining generic variants of concrete types.
258
Guido van Rossum4cefe742016-09-27 15:20:12 -0700259 Note that this is not a type; let's call it a pseudo-type. It cannot
260 be used in instance and subclass checks in parameterized form, i.e.
261 ``isinstance(42, Match[str])`` raises ``TypeError`` instead of returning
262 ``False``.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700263 """
264
Guido van Rossumd70fe632015-08-05 12:11:06 +0200265 __slots__ = ('name', 'type_var', 'impl_type', 'type_checker')
266
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700267 def __init__(self, name, type_var, impl_type, type_checker):
268 """Initializer.
269
270 Args:
271 name: The name, e.g. 'Pattern'.
272 type_var: The type parameter, e.g. AnyStr, or the
273 specific type, e.g. str.
274 impl_type: The implementation type.
275 type_checker: Function that takes an impl_type instance.
276 and returns a value that should be a type_var instance.
277 """
278 assert isinstance(name, str), repr(name)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700279 assert isinstance(impl_type, type), repr(impl_type)
280 assert not isinstance(impl_type, TypingMeta), repr(impl_type)
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700281 assert isinstance(type_var, (type, _TypingBase)), repr(type_var)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700282 self.name = name
283 self.type_var = type_var
284 self.impl_type = impl_type
285 self.type_checker = type_checker
286
287 def __repr__(self):
288 return "%s[%s]" % (self.name, _type_repr(self.type_var))
289
290 def __getitem__(self, parameter):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700291 if not isinstance(self.type_var, TypeVar):
292 raise TypeError("%s cannot be further parameterized." % self)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700293 if self.type_var.__constraints__ and isinstance(parameter, type):
294 if not issubclass(parameter, self.type_var.__constraints__):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700295 raise TypeError("%s is not a valid substitution for %s." %
296 (parameter, self.type_var))
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700297 if isinstance(parameter, TypeVar) and parameter is not self.type_var:
298 raise TypeError("%s cannot be re-parameterized." % self)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700299 return self.__class__(self.name, parameter,
300 self.impl_type, self.type_checker)
301
Guido van Rossum4cefe742016-09-27 15:20:12 -0700302 def __eq__(self, other):
303 if not isinstance(other, _TypeAlias):
304 return NotImplemented
305 return self.name == other.name and self.type_var == other.type_var
306
307 def __hash__(self):
308 return hash((self.name, self.type_var))
309
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700310 def __instancecheck__(self, obj):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700311 if not isinstance(self.type_var, TypeVar):
312 raise TypeError("Parameterized type aliases cannot be used "
313 "with isinstance().")
314 return isinstance(obj, self.impl_type)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700315
316 def __subclasscheck__(self, cls):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700317 if not isinstance(self.type_var, TypeVar):
318 raise TypeError("Parameterized type aliases cannot be used "
319 "with issubclass().")
320 return issubclass(cls, self.impl_type)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700321
322
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700323def _get_type_vars(types, tvars):
324 for t in types:
Guido van Rossum4cefe742016-09-27 15:20:12 -0700325 if isinstance(t, TypingMeta) or isinstance(t, _TypingBase):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700326 t._get_type_vars(tvars)
327
328
329def _type_vars(types):
330 tvars = []
331 _get_type_vars(types, tvars)
332 return tuple(tvars)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700333
334
335def _eval_type(t, globalns, localns):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700336 if isinstance(t, TypingMeta) or isinstance(t, _TypingBase):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700337 return t._eval_type(globalns, localns)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700338 return t
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700339
340
341def _type_check(arg, msg):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800342 """Check that the argument is a type, and return it (internal helper).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700343
344 As a special case, accept None and return type(None) instead.
345 Also, _TypeAlias instances (e.g. Match, Pattern) are acceptable.
346
347 The msg argument is a human-readable error message, e.g.
348
349 "Union[arg, ...]: arg should be a type."
350
351 We append the repr() of the actual value (truncated to 100 chars).
352 """
353 if arg is None:
354 return type(None)
355 if isinstance(arg, str):
356 arg = _ForwardRef(arg)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700357 if (isinstance(arg, _TypingBase) and type(arg).__name__ == '_ClassVar' or
358 not isinstance(arg, (type, _TypingBase)) and not callable(arg)):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700359 raise TypeError(msg + " Got %.100r." % (arg,))
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700360 # Bare Union etc. are not valid as type arguments
361 if (type(arg).__name__ in ('_Union', '_Optional')
362 and not getattr(arg, '__origin__', None)
363 or isinstance(arg, TypingMeta) and _gorg(arg) in (Generic, _Protocol)):
364 raise TypeError("Plain %s is not valid as type argument" % arg)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700365 return arg
366
367
368def _type_repr(obj):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800369 """Return the repr() of an object, special-casing types (internal helper).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700370
371 If obj is a type, we return a shorter version than the default
372 type.__repr__, based on the module and qualified name, which is
373 typically enough to uniquely identify a type. For everything
374 else, we fall back on repr(obj).
375 """
376 if isinstance(obj, type) and not isinstance(obj, TypingMeta):
377 if obj.__module__ == 'builtins':
378 return _qualname(obj)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700379 return '%s.%s' % (obj.__module__, _qualname(obj))
380 if obj is ...:
381 return('...')
382 if isinstance(obj, types.FunctionType):
383 return obj.__name__
384 return repr(obj)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700385
386
Guido van Rossum4cefe742016-09-27 15:20:12 -0700387class _Any(_FinalTypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700388 """Special type indicating an unconstrained type.
389
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700390 - Any is compatible with every type.
391 - Any assumed to have all methods.
392 - All values assumed to be instances of Any.
393
394 Note that all the above statements are true from the point of view of
395 static type checkers. At runtime, Any should not be used with instance
396 or class checks.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700397 """
398
Guido van Rossumd70fe632015-08-05 12:11:06 +0200399 __slots__ = ()
400
Guido van Rossum4cefe742016-09-27 15:20:12 -0700401 def __instancecheck__(self, obj):
402 raise TypeError("Any cannot be used with isinstance().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700403
Guido van Rossum4cefe742016-09-27 15:20:12 -0700404 def __subclasscheck__(self, cls):
405 raise TypeError("Any cannot be used with issubclass().")
406
407
408Any = _Any(_root=True)
409
410
411class TypeVar(_TypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700412 """Type variable.
413
414 Usage::
415
416 T = TypeVar('T') # Can be anything
417 A = TypeVar('A', str, bytes) # Must be str or bytes
418
419 Type variables exist primarily for the benefit of static type
420 checkers. They serve as the parameters for generic types as well
421 as for generic function definitions. See class Generic for more
422 information on generic types. Generic functions work as follows:
423
Guido van Rossumb24569a2016-11-20 18:01:29 -0800424 def repeat(x: T, n: int) -> List[T]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700425 '''Return a list containing n references to x.'''
426 return [x]*n
427
428 def longest(x: A, y: A) -> A:
429 '''Return the longest of two strings.'''
430 return x if len(x) >= len(y) else y
431
432 The latter example's signature is essentially the overloading
433 of (str, str) -> str and (bytes, bytes) -> bytes. Also note
434 that if the arguments are instances of some subclass of str,
435 the return type is still plain str.
436
Guido van Rossumb24569a2016-11-20 18:01:29 -0800437 At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700438
Guido van Rossumefa798d2016-08-23 11:01:50 -0700439 Type variables defined with covariant=True or contravariant=True
440 can be used do declare covariant or contravariant generic types.
441 See PEP 484 for more details. By default generic types are invariant
442 in all type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700443
444 Type variables can be introspected. e.g.:
445
446 T.__name__ == 'T'
447 T.__constraints__ == ()
448 T.__covariant__ == False
449 T.__contravariant__ = False
450 A.__constraints__ == (str, bytes)
451 """
452
Guido van Rossum4cefe742016-09-27 15:20:12 -0700453 __slots__ = ('__name__', '__bound__', '__constraints__',
454 '__covariant__', '__contravariant__')
455
456 def __init__(self, name, *constraints, bound=None,
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700457 covariant=False, contravariant=False):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700458 super().__init__(name, *constraints, bound=bound,
459 covariant=covariant, contravariant=contravariant)
460 self.__name__ = name
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700461 if covariant and contravariant:
Guido van Rossumefa798d2016-08-23 11:01:50 -0700462 raise ValueError("Bivariant types are not supported.")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700463 self.__covariant__ = bool(covariant)
464 self.__contravariant__ = bool(contravariant)
465 if constraints and bound is not None:
466 raise TypeError("Constraints cannot be combined with bound=...")
467 if constraints and len(constraints) == 1:
468 raise TypeError("A single constraint is not allowed")
469 msg = "TypeVar(name, constraint, ...): constraints must be types."
470 self.__constraints__ = tuple(_type_check(t, msg) for t in constraints)
471 if bound:
472 self.__bound__ = _type_check(bound, "Bound must be a type.")
473 else:
474 self.__bound__ = None
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700475
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700476 def _get_type_vars(self, tvars):
477 if self not in tvars:
478 tvars.append(self)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700479
480 def __repr__(self):
481 if self.__covariant__:
482 prefix = '+'
483 elif self.__contravariant__:
484 prefix = '-'
485 else:
486 prefix = '~'
487 return prefix + self.__name__
488
489 def __instancecheck__(self, instance):
490 raise TypeError("Type variables cannot be used with isinstance().")
491
492 def __subclasscheck__(self, cls):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700493 raise TypeError("Type variables cannot be used with issubclass().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700494
495
496# Some unconstrained type variables. These are used by the container types.
Guido van Rossumeb9aca32016-05-24 16:38:22 -0700497# (These are not for export.)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700498T = TypeVar('T') # Any type.
499KT = TypeVar('KT') # Key type.
500VT = TypeVar('VT') # Value type.
501T_co = TypeVar('T_co', covariant=True) # Any type covariant containers.
502V_co = TypeVar('V_co', covariant=True) # Any type covariant containers.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700503VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
504T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
505
506# A useful type variable with constraints. This represents string types.
Guido van Rossumeb9aca32016-05-24 16:38:22 -0700507# (This one *is* for export!)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700508AnyStr = TypeVar('AnyStr', bytes, str)
509
510
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700511def _replace_arg(arg, tvars, args):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800512 """An internal helper function: replace arg if it is a type variable
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700513 found in tvars with corresponding substitution from args or
514 with corresponding substitution sub-tree if arg is a generic type.
515 """
516
517 if tvars is None:
518 tvars = []
Guido van Rossum83ec3022017-01-17 20:43:28 -0800519 if hasattr(arg, '_subs_tree') and isinstance(arg, (GenericMeta, _TypingBase)):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700520 return arg._subs_tree(tvars, args)
521 if isinstance(arg, TypeVar):
522 for i, tvar in enumerate(tvars):
523 if arg == tvar:
524 return args[i]
525 return arg
526
527
Guido van Rossum83ec3022017-01-17 20:43:28 -0800528# Special typing constructs Union, Optional, Generic, Callable and Tuple
529# use three special attributes for internal bookkeeping of generic types:
530# * __parameters__ is a tuple of unique free type parameters of a generic
531# type, for example, Dict[T, T].__parameters__ == (T,);
532# * __origin__ keeps a reference to a type that was subscripted,
533# e.g., Union[T, int].__origin__ == Union;
534# * __args__ is a tuple of all arguments used in subscripting,
535# e.g., Dict[T, int].__args__ == (T, int).
536
537
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700538def _subs_tree(cls, tvars=None, args=None):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800539 """An internal helper function: calculate substitution tree
540 for generic cls after replacing its type parameters with
541 substitutions in tvars -> args (if any).
542 Repeat the same following __origin__'s.
543
544 Return a list of arguments with all possible substitutions
545 performed. Arguments that are generic classes themselves are represented
546 as tuples (so that no new classes are created by this function).
547 For example: _subs_tree(List[Tuple[int, T]][str]) == [(Tuple, int, str)]
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700548 """
549
550 if cls.__origin__ is None:
551 return cls
552 # Make of chain of origins (i.e. cls -> cls.__origin__)
553 current = cls.__origin__
554 orig_chain = []
555 while current.__origin__ is not None:
556 orig_chain.append(current)
557 current = current.__origin__
558 # Replace type variables in __args__ if asked ...
559 tree_args = []
560 for arg in cls.__args__:
561 tree_args.append(_replace_arg(arg, tvars, args))
562 # ... then continue replacing down the origin chain.
563 for ocls in orig_chain:
564 new_tree_args = []
565 for i, arg in enumerate(ocls.__args__):
566 new_tree_args.append(_replace_arg(arg, ocls.__parameters__, tree_args))
567 tree_args = new_tree_args
568 return tree_args
569
570
571def _remove_dups_flatten(parameters):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800572 """An internal helper for Union creation and substitution: flatten Union's
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700573 among parameters, then remove duplicates and strict subclasses.
574 """
575
576 # Flatten out Union[Union[...], ...].
577 params = []
578 for p in parameters:
579 if isinstance(p, _Union) and p.__origin__ is Union:
580 params.extend(p.__args__)
581 elif isinstance(p, tuple) and len(p) > 0 and p[0] is Union:
582 params.extend(p[1:])
583 else:
584 params.append(p)
585 # Weed out strict duplicates, preserving the first of each occurrence.
586 all_params = set(params)
587 if len(all_params) < len(params):
588 new_params = []
589 for t in params:
590 if t in all_params:
591 new_params.append(t)
592 all_params.remove(t)
593 params = new_params
594 assert not all_params, all_params
595 # Weed out subclasses.
596 # E.g. Union[int, Employee, Manager] == Union[int, Employee].
597 # If object is present it will be sole survivor among proper classes.
598 # Never discard type variables.
599 # (In particular, Union[str, AnyStr] != AnyStr.)
600 all_params = set(params)
601 for t1 in params:
602 if not isinstance(t1, type):
603 continue
604 if any(isinstance(t2, type) and issubclass(t1, t2)
605 for t2 in all_params - {t1}
606 if not (isinstance(t2, GenericMeta) and
607 t2.__origin__ is not None)):
608 all_params.remove(t1)
609 return tuple(t for t in params if t in all_params)
610
611
612def _check_generic(cls, parameters):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800613 # Check correct count for parameters of a generic cls (internal helper).
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700614 if not cls.__parameters__:
615 raise TypeError("%s is not a generic class" % repr(cls))
616 alen = len(parameters)
617 elen = len(cls.__parameters__)
618 if alen != elen:
619 raise TypeError("Too %s parameters for %s; actual %s, expected %s" %
620 ("many" if alen > elen else "few", repr(cls), alen, elen))
621
622
Guido van Rossum9b107562016-11-09 13:23:04 -0800623_cleanups = []
624
625
Guido van Rossum4cefe742016-09-27 15:20:12 -0700626def _tp_cache(func):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800627 """Internal wrapper caching __getitem__ of generic types with a fallback to
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700628 original function for non-hashable arguments.
629 """
630
Guido van Rossum4cefe742016-09-27 15:20:12 -0700631 cached = functools.lru_cache()(func)
Guido van Rossum9b107562016-11-09 13:23:04 -0800632 _cleanups.append(cached.cache_clear)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700633 @functools.wraps(func)
634 def inner(*args, **kwds):
635 try:
636 return cached(*args, **kwds)
637 except TypeError:
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700638 pass # All real errors (not unhashable args) are raised below.
Guido van Rossum4cefe742016-09-27 15:20:12 -0700639 return func(*args, **kwds)
640 return inner
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700641
642
Guido van Rossum4cefe742016-09-27 15:20:12 -0700643class _Union(_FinalTypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700644 """Union type; Union[X, Y] means either X or Y.
645
646 To define a union, use e.g. Union[int, str]. Details:
647
648 - The arguments must be types and there must be at least one.
649
650 - None as an argument is a special case and is replaced by
651 type(None).
652
653 - Unions of unions are flattened, e.g.::
654
655 Union[Union[int, str], float] == Union[int, str, float]
656
657 - Unions of a single argument vanish, e.g.::
658
659 Union[int] == int # The constructor actually returns int
660
661 - Redundant arguments are skipped, e.g.::
662
663 Union[int, str, int] == Union[int, str]
664
665 - When comparing unions, the argument order is ignored, e.g.::
666
667 Union[int, str] == Union[str, int]
668
669 - When two arguments have a subclass relationship, the least
670 derived argument is kept, e.g.::
671
672 class Employee: pass
673 class Manager(Employee): pass
674 Union[int, Employee, Manager] == Union[int, Employee]
675 Union[Manager, int, Employee] == Union[int, Employee]
676 Union[Employee, Manager] == Employee
677
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700678 - Similar for object::
679
680 Union[int, object] == object
681
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700682 - You cannot subclass or instantiate a union.
683
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700684 - You can use Optional[X] as a shorthand for Union[X, None].
685 """
686
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700687 __slots__ = ('__parameters__', '__args__', '__origin__', '__tree_hash__')
Guido van Rossum4cefe742016-09-27 15:20:12 -0700688
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700689 def __new__(cls, parameters=None, origin=None, *args, _root=False):
690 self = super().__new__(cls, parameters, origin, *args, _root=_root)
691 if origin is None:
692 self.__parameters__ = None
693 self.__args__ = None
694 self.__origin__ = None
695 self.__tree_hash__ = hash(frozenset(('Union',)))
Guido van Rossum4cefe742016-09-27 15:20:12 -0700696 return self
697 if not isinstance(parameters, tuple):
698 raise TypeError("Expected parameters=<tuple>")
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700699 if origin is Union:
700 parameters = _remove_dups_flatten(parameters)
701 # It's not a union if there's only one type left.
702 if len(parameters) == 1:
703 return parameters[0]
704 self.__parameters__ = _type_vars(parameters)
705 self.__args__ = parameters
706 self.__origin__ = origin
707 # Pre-calculate the __hash__ on instantiation.
708 # This improves speed for complex substitutions.
709 subs_tree = self._subs_tree()
710 if isinstance(subs_tree, tuple):
711 self.__tree_hash__ = hash(frozenset(subs_tree))
712 else:
713 self.__tree_hash__ = hash(subs_tree)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700714 return self
715
716 def _eval_type(self, globalns, localns):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700717 if self.__args__ is None:
Guido van Rossum4cefe742016-09-27 15:20:12 -0700718 return self
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700719 ev_args = tuple(_eval_type(t, globalns, localns) for t in self.__args__)
720 ev_origin = _eval_type(self.__origin__, globalns, localns)
721 if ev_args == self.__args__ and ev_origin == self.__origin__:
722 # Everything is already evaluated.
723 return self
724 return self.__class__(ev_args, ev_origin, _root=True)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700725
726 def _get_type_vars(self, tvars):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700727 if self.__origin__ and self.__parameters__:
728 _get_type_vars(self.__parameters__, tvars)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700729
730 def __repr__(self):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700731 if self.__origin__ is None:
732 return super().__repr__()
733 tree = self._subs_tree()
734 if not isinstance(tree, tuple):
735 return repr(tree)
736 return tree[0]._tree_repr(tree)
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700737
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700738 def _tree_repr(self, tree):
739 arg_list = []
740 for arg in tree[1:]:
741 if not isinstance(arg, tuple):
742 arg_list.append(_type_repr(arg))
743 else:
744 arg_list.append(arg[0]._tree_repr(arg))
745 return super().__repr__() + '[%s]' % ', '.join(arg_list)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700746
747 @_tp_cache
748 def __getitem__(self, parameters):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700749 if parameters == ():
750 raise TypeError("Cannot take a Union of no types.")
751 if not isinstance(parameters, tuple):
752 parameters = (parameters,)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700753 if self.__origin__ is None:
754 msg = "Union[arg, ...]: each arg must be a type."
755 else:
756 msg = "Parameters to generic types must be types."
757 parameters = tuple(_type_check(p, msg) for p in parameters)
758 if self is not Union:
759 _check_generic(self, parameters)
760 return self.__class__(parameters, origin=self, _root=True)
761
762 def _subs_tree(self, tvars=None, args=None):
763 if self is Union:
764 return Union # Nothing to substitute
765 tree_args = _subs_tree(self, tvars, args)
766 tree_args = _remove_dups_flatten(tree_args)
767 if len(tree_args) == 1:
768 return tree_args[0] # Union of a single type is that type
769 return (Union,) + tree_args
Guido van Rossum4cefe742016-09-27 15:20:12 -0700770
771 def __eq__(self, other):
Guido van Rossum83ec3022017-01-17 20:43:28 -0800772 if isinstance(other, _Union):
773 return self.__tree_hash__ == other.__tree_hash__
774 elif self is not Union:
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700775 return self._subs_tree() == other
Guido van Rossum83ec3022017-01-17 20:43:28 -0800776 else:
777 return self is other
Guido van Rossum4cefe742016-09-27 15:20:12 -0700778
779 def __hash__(self):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700780 return self.__tree_hash__
Guido van Rossum4cefe742016-09-27 15:20:12 -0700781
782 def __instancecheck__(self, obj):
783 raise TypeError("Unions cannot be used with isinstance().")
784
785 def __subclasscheck__(self, cls):
786 raise TypeError("Unions cannot be used with issubclass().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700787
788
Guido van Rossum4cefe742016-09-27 15:20:12 -0700789Union = _Union(_root=True)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700790
791
Guido van Rossum4cefe742016-09-27 15:20:12 -0700792class _Optional(_FinalTypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700793 """Optional type.
794
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700795 Optional[X] is equivalent to Union[X, None].
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700796 """
797
Guido van Rossumd70fe632015-08-05 12:11:06 +0200798 __slots__ = ()
799
Guido van Rossum4cefe742016-09-27 15:20:12 -0700800 @_tp_cache
801 def __getitem__(self, arg):
802 arg = _type_check(arg, "Optional[t] requires a single type.")
803 return Union[arg, type(None)]
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700804
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700805
Guido van Rossum4cefe742016-09-27 15:20:12 -0700806Optional = _Optional(_root=True)
807
808
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700809def _gorg(a):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800810 """Return the farthest origin of a generic class (internal helper)."""
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700811 assert isinstance(a, GenericMeta)
812 while a.__origin__ is not None:
813 a = a.__origin__
814 return a
815
816
817def _geqv(a, b):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800818 """Return whether two generic classes are equivalent (internal helper).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700819
820 The intention is to consider generic class X and any of its
Guido van Rossumb24569a2016-11-20 18:01:29 -0800821 parameterized forms (X[T], X[int], etc.) as equivalent.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700822
823 However, X is not equivalent to a subclass of X.
824
825 The relation is reflexive, symmetric and transitive.
826 """
827 assert isinstance(a, GenericMeta) and isinstance(b, GenericMeta)
828 # Reduce each to its origin.
829 return _gorg(a) is _gorg(b)
830
831
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700832def _next_in_mro(cls):
833 """Helper for Generic.__new__.
834
835 Returns the class after the last occurrence of Generic or
836 Generic[...] in cls.__mro__.
837 """
838 next_in_mro = object
839 # Look for the last occurrence of Generic or Generic[...].
840 for i, c in enumerate(cls.__mro__[:-1]):
841 if isinstance(c, GenericMeta) and _gorg(c) is Generic:
842 next_in_mro = cls.__mro__[i+1]
843 return next_in_mro
844
845
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700846def _valid_for_check(cls):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800847 """An internal helper to prohibit isinstance([1], List[str]) etc."""
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700848 if cls is Generic:
849 raise TypeError("Class %r cannot be used with class "
850 "or instance checks" % cls)
851 if (cls.__origin__ is not None and
852 sys._getframe(3).f_globals['__name__'] not in ['abc', 'functools']):
853 raise TypeError("Parameterized generics cannot be used with class "
854 "or instance checks")
855
856
857def _make_subclasshook(cls):
858 """Construct a __subclasshook__ callable that incorporates
859 the associated __extra__ class in subclass checks performed
860 against cls.
861 """
862 if isinstance(cls.__extra__, abc.ABCMeta):
863 # The logic mirrors that of ABCMeta.__subclasscheck__.
864 # Registered classes need not be checked here because
865 # cls and its extra share the same _abc_registry.
866 def __extrahook__(subclass):
867 _valid_for_check(cls)
868 res = cls.__extra__.__subclasshook__(subclass)
869 if res is not NotImplemented:
870 return res
871 if cls.__extra__ in subclass.__mro__:
872 return True
873 for scls in cls.__extra__.__subclasses__():
874 if isinstance(scls, GenericMeta):
875 continue
876 if issubclass(subclass, scls):
877 return True
878 return NotImplemented
879 else:
880 # For non-ABC extras we'll just call issubclass().
881 def __extrahook__(subclass):
882 _valid_for_check(cls)
883 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)
969 self = super().__new__(cls, name, bases, namespace, _root=True)
970
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700971 self.__parameters__ = tvars
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700972 # Be prepared that GenericMeta will be subclassed by TupleMeta
973 # and CallableMeta, those two allow ..., (), or [] in __args___.
974 self.__args__ = tuple(... if a is _TypingEllipsis else
975 () if a is _TypingEmpty else
976 a for a in args) if args else None
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700977 self.__origin__ = origin
Guido van Rossum1cea70f2016-05-18 08:35:00 -0700978 self.__extra__ = extra
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700979 # Speed hack (https://github.com/python/typing/issues/196).
980 self.__next_in_mro__ = _next_in_mro(self)
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700981 # Preserve base classes on subclassing (__bases__ are type erased now).
982 if orig_bases is None:
983 self.__orig_bases__ = initial_bases
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700984
985 # This allows unparameterized generic collections to be used
986 # with issubclass() and isinstance() in the same way as their
987 # collections.abc counterparts (e.g., isinstance([], Iterable)).
Guido van Rossume2592672016-10-08 20:27:22 -0700988 if ('__subclasshook__' not in namespace and extra # allow overriding
989 or hasattr(self.__subclasshook__, '__name__') and
990 self.__subclasshook__.__name__ == '__extrahook__'):
991 self.__subclasshook__ = _make_subclasshook(self)
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700992 if isinstance(extra, abc.ABCMeta):
993 self._abc_registry = extra._abc_registry
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700994
995 if origin and hasattr(origin, '__qualname__'): # Fix for Python 3.2.
996 self.__qualname__ = origin.__qualname__
997 self.__tree_hash__ = hash(self._subs_tree()) if origin else hash((self.__name__,))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700998 return self
999
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001000 def _get_type_vars(self, tvars):
1001 if self.__origin__ and self.__parameters__:
1002 _get_type_vars(self.__parameters__, tvars)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001003
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001004 def _eval_type(self, globalns, localns):
1005 ev_origin = (self.__origin__._eval_type(globalns, localns)
1006 if self.__origin__ else None)
1007 ev_args = tuple(_eval_type(a, globalns, localns) for a
1008 in self.__args__) if self.__args__ else None
1009 if ev_origin == self.__origin__ and ev_args == self.__args__:
1010 return self
1011 return self.__class__(self.__name__,
1012 self.__bases__,
Guido van Rossum61f0a022016-11-29 09:46:21 -08001013 _no_slots_copy(self.__dict__),
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001014 tvars=_type_vars(ev_args) if ev_args else None,
1015 args=ev_args,
1016 origin=ev_origin,
1017 extra=self.__extra__,
1018 orig_bases=self.__orig_bases__)
1019
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001020 def __repr__(self):
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001021 if self.__origin__ is None:
1022 return super().__repr__()
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001023 return self._tree_repr(self._subs_tree())
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001024
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001025 def _tree_repr(self, tree):
1026 arg_list = []
1027 for arg in tree[1:]:
1028 if arg == ():
1029 arg_list.append('()')
1030 elif not isinstance(arg, tuple):
1031 arg_list.append(_type_repr(arg))
1032 else:
1033 arg_list.append(arg[0]._tree_repr(arg))
1034 return super().__repr__() + '[%s]' % ', '.join(arg_list)
1035
1036 def _subs_tree(self, tvars=None, args=None):
1037 if self.__origin__ is None:
1038 return self
1039 tree_args = _subs_tree(self, tvars, args)
1040 return (_gorg(self),) + tuple(tree_args)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001041
1042 def __eq__(self, other):
1043 if not isinstance(other, GenericMeta):
1044 return NotImplemented
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001045 if self.__origin__ is None or other.__origin__ is None:
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001046 return self is other
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001047 return self.__tree_hash__ == other.__tree_hash__
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001048
1049 def __hash__(self):
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001050 return self.__tree_hash__
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001051
Guido van Rossum4cefe742016-09-27 15:20:12 -07001052 @_tp_cache
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001053 def __getitem__(self, params):
1054 if not isinstance(params, tuple):
1055 params = (params,)
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001056 if not params and not _gorg(self) is Tuple:
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001057 raise TypeError(
1058 "Parameter list to %s[...] cannot be empty" % _qualname(self))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001059 msg = "Parameters to generic types must be types."
1060 params = tuple(_type_check(p, msg) for p in params)
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001061 if self is Generic:
1062 # Generic can only be subscripted with unique type variables.
1063 if not all(isinstance(p, TypeVar) for p in params):
1064 raise TypeError(
1065 "Parameters to Generic[...] must all be type variables")
Guido van Rossumd70fe632015-08-05 12:11:06 +02001066 if len(set(params)) != len(params):
Guido van Rossum1b669102015-09-04 12:15:54 -07001067 raise TypeError(
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001068 "Parameters to Generic[...] must all be unique")
1069 tvars = params
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001070 args = params
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001071 elif self in (Tuple, Callable):
1072 tvars = _type_vars(params)
1073 args = params
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001074 elif self is _Protocol:
1075 # _Protocol is internal, don't check anything.
1076 tvars = params
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001077 args = params
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001078 elif self.__origin__ in (Generic, _Protocol):
1079 # Can't subscript Generic[...] or _Protocol[...].
1080 raise TypeError("Cannot subscript already-subscripted %s" %
1081 repr(self))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001082 else:
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001083 # Subscripting a regular Generic subclass.
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001084 _check_generic(self, params)
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001085 tvars = _type_vars(params)
1086 args = params
1087 return self.__class__(self.__name__,
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001088 self.__bases__,
Guido van Rossum61f0a022016-11-29 09:46:21 -08001089 _no_slots_copy(self.__dict__),
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001090 tvars=tvars,
1091 args=args,
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001092 origin=self,
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001093 extra=self.__extra__,
1094 orig_bases=self.__orig_bases__)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001095
Guido van Rossum1b669102015-09-04 12:15:54 -07001096 def __instancecheck__(self, instance):
1097 # Since we extend ABC.__subclasscheck__ and
1098 # ABC.__instancecheck__ inlines the cache checking done by the
1099 # latter, we must extend __instancecheck__ too. For simplicity
1100 # we just skip the cache check -- instance checks for generic
1101 # classes are supposed to be rare anyways.
Guido van Rossumb47c9d22016-10-03 08:40:50 -07001102 return issubclass(instance.__class__, self)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001103
Guido van Rossumb7dedc82016-10-29 12:44:29 -07001104 def __copy__(self):
Guido van Rossum61f0a022016-11-29 09:46:21 -08001105 return self.__class__(self.__name__, self.__bases__,
1106 _no_slots_copy(self.__dict__),
Guido van Rossumb7dedc82016-10-29 12:44:29 -07001107 self.__parameters__, self.__args__, self.__origin__,
1108 self.__extra__, self.__orig_bases__)
1109
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001110
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001111# Prevent checks for Generic to crash when defining Generic.
1112Generic = None
1113
1114
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001115def _generic_new(base_cls, cls, *args, **kwds):
1116 # Assure type is erased on instantiation,
1117 # but attempt to store it in __orig_class__
1118 if cls.__origin__ is None:
1119 return base_cls.__new__(cls)
1120 else:
1121 origin = _gorg(cls)
1122 obj = base_cls.__new__(origin)
1123 try:
1124 obj.__orig_class__ = cls
1125 except AttributeError:
1126 pass
1127 obj.__init__(*args, **kwds)
1128 return obj
1129
1130
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001131class Generic(metaclass=GenericMeta):
1132 """Abstract base class for generic types.
1133
Guido van Rossumb24569a2016-11-20 18:01:29 -08001134 A generic type is typically declared by inheriting from
1135 this class parameterized with one or more type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001136 For example, a generic mapping type might be defined as::
1137
1138 class Mapping(Generic[KT, VT]):
1139 def __getitem__(self, key: KT) -> VT:
1140 ...
1141 # Etc.
1142
1143 This class can then be used as follows::
1144
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001145 def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001146 try:
1147 return mapping[key]
1148 except KeyError:
1149 return default
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001150 """
1151
Guido van Rossumd70fe632015-08-05 12:11:06 +02001152 __slots__ = ()
1153
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001154 def __new__(cls, *args, **kwds):
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001155 if _geqv(cls, Generic):
1156 raise TypeError("Type Generic cannot be instantiated; "
1157 "it can be used only as a base class")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001158 return _generic_new(cls.__next_in_mro__, cls, *args, **kwds)
1159
1160
1161class _TypingEmpty:
Guido van Rossumb24569a2016-11-20 18:01:29 -08001162 """Internal placeholder for () or []. Used by TupleMeta and CallableMeta
1163 to allow empty list/tuple in specific places, without allowing them
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001164 to sneak in where prohibited.
1165 """
1166
1167
1168class _TypingEllipsis:
Guido van Rossumb24569a2016-11-20 18:01:29 -08001169 """Internal placeholder for ... (ellipsis)."""
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001170
1171
1172class TupleMeta(GenericMeta):
Guido van Rossumb24569a2016-11-20 18:01:29 -08001173 """Metaclass for Tuple (internal)."""
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001174
1175 @_tp_cache
1176 def __getitem__(self, parameters):
1177 if self.__origin__ is not None or not _geqv(self, Tuple):
1178 # Normal generic rules apply if this is not the first subscription
1179 # or a subscription of a subclass.
1180 return super().__getitem__(parameters)
1181 if parameters == ():
1182 return super().__getitem__((_TypingEmpty,))
1183 if not isinstance(parameters, tuple):
1184 parameters = (parameters,)
1185 if len(parameters) == 2 and parameters[1] is ...:
1186 msg = "Tuple[t, ...]: t must be a type."
1187 p = _type_check(parameters[0], msg)
1188 return super().__getitem__((p, _TypingEllipsis))
1189 msg = "Tuple[t0, t1, ...]: each t must be a type."
1190 parameters = tuple(_type_check(p, msg) for p in parameters)
1191 return super().__getitem__(parameters)
1192
1193 def __instancecheck__(self, obj):
1194 if self.__args__ == None:
1195 return isinstance(obj, tuple)
1196 raise TypeError("Parameterized Tuple cannot be used "
1197 "with isinstance().")
1198
1199 def __subclasscheck__(self, cls):
1200 if self.__args__ == None:
1201 return issubclass(cls, tuple)
1202 raise TypeError("Parameterized Tuple cannot be used "
1203 "with issubclass().")
1204
1205
1206class Tuple(tuple, extra=tuple, metaclass=TupleMeta):
1207 """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
1208
1209 Example: Tuple[T1, T2] is a tuple of two elements corresponding
1210 to type variables T1 and T2. Tuple[int, float, str] is a tuple
1211 of an int, a float and a string.
1212
1213 To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
1214 """
1215
1216 __slots__ = ()
1217
1218 def __new__(cls, *args, **kwds):
1219 if _geqv(cls, Tuple):
1220 raise TypeError("Type Tuple cannot be instantiated; "
1221 "use tuple() instead")
1222 return _generic_new(tuple, cls, *args, **kwds)
1223
1224
1225class CallableMeta(GenericMeta):
Guido van Rossumb24569a2016-11-20 18:01:29 -08001226 """Metaclass for Callable (internal)."""
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001227
1228 def __repr__(self):
1229 if self.__origin__ is None:
1230 return super().__repr__()
1231 return self._tree_repr(self._subs_tree())
1232
1233 def _tree_repr(self, tree):
1234 if _gorg(self) is not Callable:
1235 return super()._tree_repr(tree)
1236 # For actual Callable (not its subclass) we override
1237 # super()._tree_repr() for nice formatting.
1238 arg_list = []
1239 for arg in tree[1:]:
Guido van Rossum991d14f2016-11-09 13:12:51 -08001240 if not isinstance(arg, tuple):
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001241 arg_list.append(_type_repr(arg))
1242 else:
1243 arg_list.append(arg[0]._tree_repr(arg))
Guido van Rossum991d14f2016-11-09 13:12:51 -08001244 if arg_list[0] == '...':
1245 return repr(tree[0]) + '[..., %s]' % arg_list[1]
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001246 return (repr(tree[0]) +
1247 '[[%s], %s]' % (', '.join(arg_list[:-1]), arg_list[-1]))
1248
1249 def __getitem__(self, parameters):
Guido van Rossumb24569a2016-11-20 18:01:29 -08001250 """A thin wrapper around __getitem_inner__ to provide the latter
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001251 with hashable arguments to improve speed.
1252 """
1253
1254 if self.__origin__ is not None or not _geqv(self, Callable):
1255 return super().__getitem__(parameters)
1256 if not isinstance(parameters, tuple) or len(parameters) != 2:
1257 raise TypeError("Callable must be used as "
1258 "Callable[[arg, ...], result].")
1259 args, result = parameters
Guido van Rossum991d14f2016-11-09 13:12:51 -08001260 if args is Ellipsis:
1261 parameters = (Ellipsis, result)
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001262 else:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001263 if not isinstance(args, list):
1264 raise TypeError("Callable[args, result]: args must be a list."
1265 " Got %.100r." % (args,))
Guido van Rossum991d14f2016-11-09 13:12:51 -08001266 parameters = (tuple(args), result)
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001267 return self.__getitem_inner__(parameters)
1268
1269 @_tp_cache
1270 def __getitem_inner__(self, parameters):
Guido van Rossum991d14f2016-11-09 13:12:51 -08001271 args, result = parameters
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001272 msg = "Callable[args, result]: result must be a type."
1273 result = _type_check(result, msg)
Guido van Rossum991d14f2016-11-09 13:12:51 -08001274 if args is Ellipsis:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001275 return super().__getitem__((_TypingEllipsis, result))
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001276 msg = "Callable[[arg, ...], result]: each arg must be a type."
1277 args = tuple(_type_check(arg, msg) for arg in args)
1278 parameters = args + (result,)
1279 return super().__getitem__(parameters)
1280
1281
1282class Callable(extra=collections_abc.Callable, metaclass = CallableMeta):
1283 """Callable type; Callable[[int], str] is a function of (int) -> str.
1284
1285 The subscription syntax must always be used with exactly two
1286 values: the argument list and the return type. The argument list
Guido van Rossumb24569a2016-11-20 18:01:29 -08001287 must be a list of types or ellipsis; the return type must be a single type.
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001288
1289 There is no syntax to indicate optional or keyword arguments,
1290 such function types are rarely used as callback types.
1291 """
1292
1293 __slots__ = ()
1294
1295 def __new__(cls, *args, **kwds):
1296 if _geqv(cls, Callable):
1297 raise TypeError("Type Callable cannot be instantiated; "
1298 "use a non-abstract subclass instead")
1299 return _generic_new(cls.__next_in_mro__, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001300
1301
Guido van Rossum4cefe742016-09-27 15:20:12 -07001302class _ClassVar(_FinalTypingBase, _root=True):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001303 """Special type construct to mark class variables.
1304
1305 An annotation wrapped in ClassVar indicates that a given
1306 attribute is intended to be used as a class variable and
1307 should not be set on instances of that class. Usage::
1308
1309 class Starship:
1310 stats: ClassVar[Dict[str, int]] = {} # class variable
1311 damage: int = 10 # instance variable
1312
1313 ClassVar accepts only types and cannot be further subscribed.
1314
1315 Note that ClassVar is not a class itself, and should not
1316 be used with isinstance() or issubclass().
1317 """
1318
Guido van Rossum4cefe742016-09-27 15:20:12 -07001319 __slots__ = ('__type__',)
1320
1321 def __init__(self, tp=None, **kwds):
1322 self.__type__ = tp
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001323
1324 def __getitem__(self, item):
1325 cls = type(self)
1326 if self.__type__ is None:
1327 return cls(_type_check(item,
Guido van Rossum4cefe742016-09-27 15:20:12 -07001328 '{} accepts only single type.'.format(cls.__name__[1:])),
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001329 _root=True)
1330 raise TypeError('{} cannot be further subscripted'
1331 .format(cls.__name__[1:]))
1332
1333 def _eval_type(self, globalns, localns):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001334 new_tp = _eval_type(self.__type__, globalns, localns)
1335 if new_tp == self.__type__:
1336 return self
1337 return type(self)(new_tp, _root=True)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001338
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001339 def __repr__(self):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001340 r = super().__repr__()
1341 if self.__type__ is not None:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001342 r += '[{}]'.format(_type_repr(self.__type__))
Guido van Rossum4cefe742016-09-27 15:20:12 -07001343 return r
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001344
1345 def __hash__(self):
1346 return hash((type(self).__name__, self.__type__))
1347
1348 def __eq__(self, other):
1349 if not isinstance(other, _ClassVar):
1350 return NotImplemented
1351 if self.__type__ is not None:
1352 return self.__type__ == other.__type__
1353 return self is other
1354
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001355
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001356ClassVar = _ClassVar(_root=True)
1357
1358
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001359def cast(typ, val):
1360 """Cast a value to a type.
1361
1362 This returns the value unchanged. To the type checker this
1363 signals that the return value has the designated type, but at
1364 runtime we intentionally don't check anything (we want this
1365 to be as fast as possible).
1366 """
1367 return val
1368
1369
1370def _get_defaults(func):
1371 """Internal helper to extract the default arguments, by name."""
Guido van Rossum991d14f2016-11-09 13:12:51 -08001372 try:
1373 code = func.__code__
1374 except AttributeError:
1375 # Some built-in functions don't have __code__, __defaults__, etc.
1376 return {}
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001377 pos_count = code.co_argcount
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001378 arg_names = code.co_varnames
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001379 arg_names = arg_names[:pos_count]
1380 defaults = func.__defaults__ or ()
1381 kwdefaults = func.__kwdefaults__
1382 res = dict(kwdefaults) if kwdefaults else {}
1383 pos_offset = pos_count - len(defaults)
1384 for name, value in zip(arg_names[pos_offset:], defaults):
1385 assert name not in res
1386 res[name] = value
1387 return res
1388
1389
Guido van Rossum991d14f2016-11-09 13:12:51 -08001390def get_type_hints(obj, globalns=None, localns=None):
1391 """Return type hints for an object.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001392
Guido van Rossum991d14f2016-11-09 13:12:51 -08001393 This is often the same as obj.__annotations__, but it handles
1394 forward references encoded as string literals, and if necessary
1395 adds Optional[t] if a default value equal to None is set.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001396
Guido van Rossum991d14f2016-11-09 13:12:51 -08001397 The argument may be a module, class, method, or function. The annotations
1398 are returned as a dictionary. For classes, annotations include also
1399 inherited members.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001400
Guido van Rossum991d14f2016-11-09 13:12:51 -08001401 TypeError is raised if the argument is not of a type that can contain
1402 annotations, and an empty dictionary is returned if no annotations are
1403 present.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001404
Guido van Rossum991d14f2016-11-09 13:12:51 -08001405 BEWARE -- the behavior of globalns and localns is counterintuitive
1406 (unless you are familiar with how eval() and exec() work). The
1407 search order is locals first, then globals.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001408
Guido van Rossum991d14f2016-11-09 13:12:51 -08001409 - If no dict arguments are passed, an attempt is made to use the
1410 globals from obj, and these are also used as the locals. If the
1411 object does not appear to have globals, an exception is raised.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001412
Guido van Rossum991d14f2016-11-09 13:12:51 -08001413 - If one dict argument is passed, it is used for both globals and
1414 locals.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001415
Guido van Rossum991d14f2016-11-09 13:12:51 -08001416 - If two dict arguments are passed, they specify globals and
1417 locals, respectively.
1418 """
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001419
Guido van Rossum991d14f2016-11-09 13:12:51 -08001420 if getattr(obj, '__no_type_check__', None):
1421 return {}
1422 if globalns is None:
1423 globalns = getattr(obj, '__globals__', {})
1424 if localns is None:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001425 localns = globalns
Guido van Rossum991d14f2016-11-09 13:12:51 -08001426 elif localns is None:
1427 localns = globalns
1428 # Classes require a special treatment.
1429 if isinstance(obj, type):
1430 hints = {}
1431 for base in reversed(obj.__mro__):
1432 ann = base.__dict__.get('__annotations__', {})
1433 for name, value in ann.items():
1434 if value is None:
1435 value = type(None)
1436 if isinstance(value, str):
1437 value = _ForwardRef(value)
1438 value = _eval_type(value, globalns, localns)
1439 hints[name] = value
1440 return hints
1441 hints = getattr(obj, '__annotations__', None)
1442 if hints is None:
1443 # Return empty annotations for something that _could_ have them.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001444 if (isinstance(obj, types.FunctionType) or
1445 isinstance(obj, types.BuiltinFunctionType) or
Guido van Rossum991d14f2016-11-09 13:12:51 -08001446 isinstance(obj, types.MethodType) or
1447 isinstance(obj, types.ModuleType)):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001448 return {}
Guido van Rossum991d14f2016-11-09 13:12:51 -08001449 else:
1450 raise TypeError('{!r} is not a module, class, method, '
1451 'or function.'.format(obj))
1452 defaults = _get_defaults(obj)
1453 hints = dict(hints)
1454 for name, value in hints.items():
1455 if value is None:
1456 value = type(None)
1457 if isinstance(value, str):
1458 value = _ForwardRef(value)
1459 value = _eval_type(value, globalns, localns)
1460 if name in defaults and defaults[name] is None:
1461 value = Optional[value]
1462 hints[name] = value
1463 return hints
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001464
1465
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001466def no_type_check(arg):
1467 """Decorator to indicate that annotations are not type hints.
1468
1469 The argument must be a class or function; if it is a class, it
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001470 applies recursively to all methods and classes defined in that class
1471 (but not to methods defined in its superclasses or subclasses).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001472
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001473 This mutates the function(s) or class(es) in place.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001474 """
1475 if isinstance(arg, type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001476 arg_attrs = arg.__dict__.copy()
1477 for attr, val in arg.__dict__.items():
1478 if val in arg.__bases__:
1479 arg_attrs.pop(attr)
1480 for obj in arg_attrs.values():
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001481 if isinstance(obj, types.FunctionType):
1482 obj.__no_type_check__ = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001483 if isinstance(obj, type):
1484 no_type_check(obj)
1485 try:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001486 arg.__no_type_check__ = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001487 except TypeError: # built-in classes
1488 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001489 return arg
1490
1491
1492def no_type_check_decorator(decorator):
1493 """Decorator to give another decorator the @no_type_check effect.
1494
1495 This wraps the decorator with something that wraps the decorated
1496 function in @no_type_check.
1497 """
1498
1499 @functools.wraps(decorator)
1500 def wrapped_decorator(*args, **kwds):
1501 func = decorator(*args, **kwds)
1502 func = no_type_check(func)
1503 return func
1504
1505 return wrapped_decorator
1506
1507
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001508def _overload_dummy(*args, **kwds):
1509 """Helper for @overload to raise when called."""
1510 raise NotImplementedError(
1511 "You should not call an overloaded function. "
1512 "A series of @overload-decorated functions "
1513 "outside a stub module should always be followed "
1514 "by an implementation that is not @overload-ed.")
1515
1516
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001517def overload(func):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001518 """Decorator for overloaded functions/methods.
1519
1520 In a stub file, place two or more stub definitions for the same
1521 function in a row, each decorated with @overload. For example:
1522
1523 @overload
1524 def utf8(value: None) -> None: ...
1525 @overload
1526 def utf8(value: bytes) -> bytes: ...
1527 @overload
1528 def utf8(value: str) -> bytes: ...
1529
1530 In a non-stub file (i.e. a regular .py file), do the same but
1531 follow it with an implementation. The implementation should *not*
1532 be decorated with @overload. For example:
1533
1534 @overload
1535 def utf8(value: None) -> None: ...
1536 @overload
1537 def utf8(value: bytes) -> bytes: ...
1538 @overload
1539 def utf8(value: str) -> bytes: ...
1540 def utf8(value):
1541 # implementation goes here
1542 """
1543 return _overload_dummy
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001544
1545
1546class _ProtocolMeta(GenericMeta):
1547 """Internal metaclass for _Protocol.
1548
1549 This exists so _Protocol classes can be generic without deriving
1550 from Generic.
1551 """
1552
Guido van Rossumd70fe632015-08-05 12:11:06 +02001553 def __instancecheck__(self, obj):
Guido van Rossumca4b2522016-11-19 10:32:41 -08001554 if _Protocol not in self.__bases__:
1555 return super().__instancecheck__(obj)
Guido van Rossumd70fe632015-08-05 12:11:06 +02001556 raise TypeError("Protocols cannot be used with isinstance().")
1557
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001558 def __subclasscheck__(self, cls):
1559 if not self._is_protocol:
1560 # No structural checks since this isn't a protocol.
1561 return NotImplemented
1562
1563 if self is _Protocol:
1564 # Every class is a subclass of the empty protocol.
1565 return True
1566
1567 # Find all attributes defined in the protocol.
1568 attrs = self._get_protocol_attrs()
1569
1570 for attr in attrs:
1571 if not any(attr in d.__dict__ for d in cls.__mro__):
1572 return False
1573 return True
1574
1575 def _get_protocol_attrs(self):
1576 # Get all Protocol base classes.
1577 protocol_bases = []
1578 for c in self.__mro__:
1579 if getattr(c, '_is_protocol', False) and c.__name__ != '_Protocol':
1580 protocol_bases.append(c)
1581
1582 # Get attributes included in protocol.
1583 attrs = set()
1584 for base in protocol_bases:
1585 for attr in base.__dict__.keys():
1586 # Include attributes not defined in any non-protocol bases.
1587 for c in self.__mro__:
1588 if (c is not base and attr in c.__dict__ and
1589 not getattr(c, '_is_protocol', False)):
1590 break
1591 else:
1592 if (not attr.startswith('_abc_') and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001593 attr != '__abstractmethods__' and
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001594 attr != '__annotations__' and
1595 attr != '__weakref__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001596 attr != '_is_protocol' and
1597 attr != '__dict__' and
1598 attr != '__args__' and
1599 attr != '__slots__' and
1600 attr != '_get_protocol_attrs' and
1601 attr != '__next_in_mro__' and
1602 attr != '__parameters__' and
1603 attr != '__origin__' and
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001604 attr != '__orig_bases__' and
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001605 attr != '__extra__' and
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001606 attr != '__tree_hash__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001607 attr != '__module__'):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001608 attrs.add(attr)
1609
1610 return attrs
1611
1612
1613class _Protocol(metaclass=_ProtocolMeta):
1614 """Internal base class for protocol classes.
1615
Guido van Rossumb24569a2016-11-20 18:01:29 -08001616 This implements a simple-minded structural issubclass check
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001617 (similar but more general than the one-offs in collections.abc
1618 such as Hashable).
1619 """
1620
Guido van Rossumd70fe632015-08-05 12:11:06 +02001621 __slots__ = ()
1622
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001623 _is_protocol = True
1624
1625
1626# Various ABCs mimicking those in collections.abc.
1627# A few are simply re-exported for completeness.
1628
1629Hashable = collections_abc.Hashable # Not generic.
1630
1631
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001632if hasattr(collections_abc, 'Awaitable'):
1633 class Awaitable(Generic[T_co], extra=collections_abc.Awaitable):
1634 __slots__ = ()
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001635
1636 __all__.append('Awaitable')
1637
1638
1639if hasattr(collections_abc, 'Coroutine'):
1640 class Coroutine(Awaitable[V_co], Generic[T_co, T_contra, V_co],
1641 extra=collections_abc.Coroutine):
1642 __slots__ = ()
1643
1644 __all__.append('Coroutine')
Guido van Rossumf17c2002015-12-03 17:31:24 -08001645
1646
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001647if hasattr(collections_abc, 'AsyncIterable'):
Guido van Rossumf17c2002015-12-03 17:31:24 -08001648
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001649 class AsyncIterable(Generic[T_co], extra=collections_abc.AsyncIterable):
1650 __slots__ = ()
Guido van Rossumf17c2002015-12-03 17:31:24 -08001651
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001652 class AsyncIterator(AsyncIterable[T_co],
1653 extra=collections_abc.AsyncIterator):
1654 __slots__ = ()
1655
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001656 __all__.append('AsyncIterable')
1657 __all__.append('AsyncIterator')
Guido van Rossumf17c2002015-12-03 17:31:24 -08001658
1659
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001660class Iterable(Generic[T_co], extra=collections_abc.Iterable):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001661 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001662
1663
1664class Iterator(Iterable[T_co], extra=collections_abc.Iterator):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001665 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001666
1667
1668class SupportsInt(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001669 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001670
1671 @abstractmethod
1672 def __int__(self) -> int:
1673 pass
1674
1675
1676class SupportsFloat(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001677 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001678
1679 @abstractmethod
1680 def __float__(self) -> float:
1681 pass
1682
1683
1684class SupportsComplex(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001685 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001686
1687 @abstractmethod
1688 def __complex__(self) -> complex:
1689 pass
1690
1691
1692class SupportsBytes(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001693 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001694
1695 @abstractmethod
1696 def __bytes__(self) -> bytes:
1697 pass
1698
1699
Guido van Rossumd70fe632015-08-05 12:11:06 +02001700class SupportsAbs(_Protocol[T_co]):
1701 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001702
1703 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001704 def __abs__(self) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001705 pass
1706
1707
Guido van Rossumd70fe632015-08-05 12:11:06 +02001708class SupportsRound(_Protocol[T_co]):
1709 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001710
1711 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001712 def __round__(self, ndigits: int = 0) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001713 pass
1714
1715
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001716if hasattr(collections_abc, 'Reversible'):
1717 class Reversible(Iterable[T_co], extra=collections_abc.Reversible):
1718 __slots__ = ()
1719else:
1720 class Reversible(_Protocol[T_co]):
1721 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001722
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001723 @abstractmethod
1724 def __reversed__(self) -> 'Iterator[T_co]':
1725 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001726
1727
1728Sized = collections_abc.Sized # Not generic.
1729
1730
1731class Container(Generic[T_co], extra=collections_abc.Container):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001732 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001733
1734
Guido van Rossumefa798d2016-08-23 11:01:50 -07001735if hasattr(collections_abc, 'Collection'):
1736 class Collection(Sized, Iterable[T_co], Container[T_co],
1737 extra=collections_abc.Collection):
1738 __slots__ = ()
1739
1740 __all__.append('Collection')
1741
1742
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001743# Callable was defined earlier.
1744
Guido van Rossumefa798d2016-08-23 11:01:50 -07001745if hasattr(collections_abc, 'Collection'):
1746 class AbstractSet(Collection[T_co],
1747 extra=collections_abc.Set):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001748 __slots__ = ()
Guido van Rossumefa798d2016-08-23 11:01:50 -07001749else:
1750 class AbstractSet(Sized, Iterable[T_co], Container[T_co],
1751 extra=collections_abc.Set):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001752 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001753
1754
1755class MutableSet(AbstractSet[T], extra=collections_abc.MutableSet):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001756 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001757
1758
Guido van Rossumefa798d2016-08-23 11:01:50 -07001759# NOTE: It is only covariant in the value type.
1760if hasattr(collections_abc, 'Collection'):
1761 class Mapping(Collection[KT], Generic[KT, VT_co],
1762 extra=collections_abc.Mapping):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001763 __slots__ = ()
Guido van Rossumefa798d2016-08-23 11:01:50 -07001764else:
1765 class Mapping(Sized, Iterable[KT], Container[KT], Generic[KT, VT_co],
1766 extra=collections_abc.Mapping):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001767 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001768
1769
1770class MutableMapping(Mapping[KT, VT], extra=collections_abc.MutableMapping):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001771 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001772
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001773if hasattr(collections_abc, 'Reversible'):
Guido van Rossumefa798d2016-08-23 11:01:50 -07001774 if hasattr(collections_abc, 'Collection'):
1775 class Sequence(Reversible[T_co], Collection[T_co],
1776 extra=collections_abc.Sequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001777 __slots__ = ()
Guido van Rossumefa798d2016-08-23 11:01:50 -07001778 else:
1779 class Sequence(Sized, Reversible[T_co], Container[T_co],
1780 extra=collections_abc.Sequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001781 __slots__ = ()
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001782else:
1783 class Sequence(Sized, Iterable[T_co], Container[T_co],
1784 extra=collections_abc.Sequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001785 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001786
1787
1788class MutableSequence(Sequence[T], extra=collections_abc.MutableSequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001789 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001790
1791
1792class ByteString(Sequence[int], extra=collections_abc.ByteString):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001793 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001794
1795
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001796class List(list, MutableSequence[T], extra=list):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001797
Guido van Rossum4cefe742016-09-27 15:20:12 -07001798 __slots__ = ()
1799
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001800 def __new__(cls, *args, **kwds):
1801 if _geqv(cls, List):
1802 raise TypeError("Type List cannot be instantiated; "
1803 "use list() instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001804 return _generic_new(list, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001805
Raymond Hettinger80490522017-01-16 22:42:37 -08001806class Deque(collections.deque, MutableSequence[T], extra=collections.deque):
1807
1808 __slots__ = ()
1809
1810 def __new__(cls, *args, **kwds):
1811 if _geqv(cls, Deque):
1812 raise TypeError("Type Deque cannot be instantiated; "
1813 "use deque() instead")
1814 return _generic_new(collections.deque, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001815
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001816class Set(set, MutableSet[T], extra=set):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001817
Guido van Rossum4cefe742016-09-27 15:20:12 -07001818 __slots__ = ()
1819
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001820 def __new__(cls, *args, **kwds):
1821 if _geqv(cls, Set):
1822 raise TypeError("Type Set cannot be instantiated; "
1823 "use set() instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001824 return _generic_new(set, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001825
1826
Guido van Rossum4cefe742016-09-27 15:20:12 -07001827class FrozenSet(frozenset, AbstractSet[T_co], extra=frozenset):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001828 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001829
1830 def __new__(cls, *args, **kwds):
1831 if _geqv(cls, FrozenSet):
1832 raise TypeError("Type FrozenSet cannot be instantiated; "
1833 "use frozenset() instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001834 return _generic_new(frozenset, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001835
1836
1837class MappingView(Sized, Iterable[T_co], extra=collections_abc.MappingView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001838 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001839
1840
Guido van Rossumd70fe632015-08-05 12:11:06 +02001841class KeysView(MappingView[KT], AbstractSet[KT],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001842 extra=collections_abc.KeysView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001843 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001844
1845
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001846class ItemsView(MappingView[Tuple[KT, VT_co]],
Guido van Rossum0e0563c2016-04-05 14:54:25 -07001847 AbstractSet[Tuple[KT, VT_co]],
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001848 Generic[KT, VT_co],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001849 extra=collections_abc.ItemsView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001850 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001851
1852
1853class ValuesView(MappingView[VT_co], extra=collections_abc.ValuesView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001854 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001855
1856
Brett Cannonf3ad0422016-04-15 10:51:30 -07001857if hasattr(contextlib, 'AbstractContextManager'):
1858 class ContextManager(Generic[T_co], extra=contextlib.AbstractContextManager):
1859 __slots__ = ()
1860 __all__.append('ContextManager')
1861
1862
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001863class Dict(dict, MutableMapping[KT, VT], extra=dict):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001864
Guido van Rossum4cefe742016-09-27 15:20:12 -07001865 __slots__ = ()
1866
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001867 def __new__(cls, *args, **kwds):
1868 if _geqv(cls, Dict):
1869 raise TypeError("Type Dict cannot be instantiated; "
1870 "use dict() instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001871 return _generic_new(dict, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001872
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001873class DefaultDict(collections.defaultdict, MutableMapping[KT, VT],
1874 extra=collections.defaultdict):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001875
Guido van Rossum4cefe742016-09-27 15:20:12 -07001876 __slots__ = ()
1877
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001878 def __new__(cls, *args, **kwds):
1879 if _geqv(cls, DefaultDict):
1880 raise TypeError("Type DefaultDict cannot be instantiated; "
1881 "use collections.defaultdict() instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001882 return _generic_new(collections.defaultdict, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001883
1884# Determine what base class to use for Generator.
1885if hasattr(collections_abc, 'Generator'):
1886 # Sufficiently recent versions of 3.5 have a Generator ABC.
1887 _G_base = collections_abc.Generator
1888else:
1889 # Fall back on the exact type.
1890 _G_base = types.GeneratorType
1891
1892
1893class Generator(Iterator[T_co], Generic[T_co, T_contra, V_co],
1894 extra=_G_base):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001895 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001896
1897 def __new__(cls, *args, **kwds):
1898 if _geqv(cls, Generator):
1899 raise TypeError("Type Generator cannot be instantiated; "
1900 "create a subclass instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001901 return _generic_new(_G_base, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001902
1903
Guido van Rossumeb9aca32016-05-24 16:38:22 -07001904# Internal type variable used for Type[].
Guido van Rossumefa798d2016-08-23 11:01:50 -07001905CT_co = TypeVar('CT_co', covariant=True, bound=type)
Guido van Rossumeb9aca32016-05-24 16:38:22 -07001906
1907
Guido van Rossumb22c7082016-05-26 09:56:19 -07001908# This is not a real generic class. Don't use outside annotations.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001909class Type(Generic[CT_co], extra=type):
Guido van Rossumb22c7082016-05-26 09:56:19 -07001910 """A special construct usable to annotate class objects.
Guido van Rossumeb9aca32016-05-24 16:38:22 -07001911
1912 For example, suppose we have the following classes::
1913
1914 class User: ... # Abstract base for User classes
1915 class BasicUser(User): ...
1916 class ProUser(User): ...
1917 class TeamUser(User): ...
1918
1919 And a function that takes a class argument that's a subclass of
1920 User and returns an instance of the corresponding class::
1921
1922 U = TypeVar('U', bound=User)
1923 def new_user(user_class: Type[U]) -> U:
1924 user = user_class()
1925 # (Here we could write the user object to a database)
1926 return user
1927
1928 joe = new_user(BasicUser)
1929
1930 At this point the type checker knows that joe has type BasicUser.
1931 """
1932
Guido van Rossum4cefe742016-09-27 15:20:12 -07001933 __slots__ = ()
1934
Guido van Rossumeb9aca32016-05-24 16:38:22 -07001935
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001936def _make_nmtuple(name, types):
Guido van Rossum2f841442016-11-15 09:48:06 -08001937 msg = "NamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a type"
1938 types = [(n, _type_check(t, msg)) for n, t in types]
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001939 nm_tpl = collections.namedtuple(name, [n for n, t in types])
Guido van Rossum83ec3022017-01-17 20:43:28 -08001940 # Prior to PEP 526, only _field_types attribute was assigned.
1941 # Now, both __annotations__ and _field_types are used to maintain compatibility.
1942 nm_tpl.__annotations__ = nm_tpl._field_types = collections.OrderedDict(types)
Guido van Rossum557d1eb2015-11-19 08:16:31 -08001943 try:
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001944 nm_tpl.__module__ = sys._getframe(2).f_globals.get('__name__', '__main__')
Guido van Rossum557d1eb2015-11-19 08:16:31 -08001945 except (AttributeError, ValueError):
1946 pass
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001947 return nm_tpl
1948
1949
Guido van Rossum2f841442016-11-15 09:48:06 -08001950_PY36 = sys.version_info[:2] >= (3, 6)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001951
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001952
Guido van Rossum2f841442016-11-15 09:48:06 -08001953class NamedTupleMeta(type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001954
Guido van Rossum2f841442016-11-15 09:48:06 -08001955 def __new__(cls, typename, bases, ns):
1956 if ns.get('_root', False):
1957 return super().__new__(cls, typename, bases, ns)
1958 if not _PY36:
1959 raise TypeError("Class syntax for NamedTuple is only supported"
1960 " in Python 3.6+")
1961 types = ns.get('__annotations__', {})
Guido van Rossum3c268be2017-01-18 08:03:50 -08001962 nm_tpl = _make_nmtuple(typename, types.items())
1963 defaults = []
1964 defaults_dict = {}
1965 for field_name in types:
1966 if field_name in ns:
1967 default_value = ns[field_name]
1968 defaults.append(default_value)
1969 defaults_dict[field_name] = default_value
1970 elif defaults:
1971 raise TypeError("Non-default namedtuple field {field_name} cannot follow default"
1972 " field(s) {default_names}"
1973 .format(field_name=field_name,
1974 default_names=', '.join(defaults_dict.keys())))
1975 nm_tpl.__new__.__defaults__ = tuple(defaults)
1976 nm_tpl._field_defaults = defaults_dict
1977 return nm_tpl
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001978
Guido van Rossum2f841442016-11-15 09:48:06 -08001979class NamedTuple(metaclass=NamedTupleMeta):
1980 """Typed version of namedtuple.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001981
Guido van Rossum2f841442016-11-15 09:48:06 -08001982 Usage in Python versions >= 3.6::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001983
Guido van Rossum2f841442016-11-15 09:48:06 -08001984 class Employee(NamedTuple):
1985 name: str
1986 id: int
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001987
Guido van Rossum2f841442016-11-15 09:48:06 -08001988 This is equivalent to::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001989
Guido van Rossum2f841442016-11-15 09:48:06 -08001990 Employee = collections.namedtuple('Employee', ['name', 'id'])
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001991
Guido van Rossum83ec3022017-01-17 20:43:28 -08001992 The resulting class has extra __annotations__ and _field_types
1993 attributes, giving an ordered dict mapping field names to types.
1994 __annotations__ should be preferred, while _field_types
1995 is kept to maintain pre PEP 526 compatibility. (The field names
Guido van Rossum2f841442016-11-15 09:48:06 -08001996 are in the _fields attribute, which is part of the namedtuple
1997 API.) Alternative equivalent keyword syntax is also accepted::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001998
Guido van Rossum2f841442016-11-15 09:48:06 -08001999 Employee = NamedTuple('Employee', name=str, id=int)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002000
Guido van Rossum2f841442016-11-15 09:48:06 -08002001 In Python versions <= 3.5 use::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002002
Guido van Rossum2f841442016-11-15 09:48:06 -08002003 Employee = NamedTuple('Employee', [('name', str), ('id', int)])
2004 """
2005 _root = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002006
Guido van Rossum2f841442016-11-15 09:48:06 -08002007 def __new__(self, typename, fields=None, **kwargs):
2008 if kwargs and not _PY36:
2009 raise TypeError("Keyword syntax for NamedTuple is only supported"
2010 " in Python 3.6+")
2011 if fields is None:
2012 fields = kwargs.items()
2013 elif kwargs:
2014 raise TypeError("Either list of fields or keywords"
2015 " can be provided to NamedTuple, not both")
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002016 return _make_nmtuple(typename, fields)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002017
2018
Guido van Rossum91185fe2016-06-08 11:19:11 -07002019def NewType(name, tp):
2020 """NewType creates simple unique types with almost zero
2021 runtime overhead. NewType(name, tp) is considered a subtype of tp
2022 by static type checkers. At runtime, NewType(name, tp) returns
2023 a dummy function that simply returns its argument. Usage::
2024
2025 UserId = NewType('UserId', int)
2026
2027 def name_by_id(user_id: UserId) -> str:
2028 ...
2029
2030 UserId('user') # Fails type check
2031
2032 name_by_id(42) # Fails type check
2033 name_by_id(UserId(42)) # OK
2034
2035 num = UserId(5) + 1 # type: int
2036 """
2037
2038 def new_type(x):
2039 return x
2040
2041 new_type.__name__ = name
2042 new_type.__supertype__ = tp
2043 return new_type
2044
2045
Guido van Rossum0e0563c2016-04-05 14:54:25 -07002046# Python-version-specific alias (Python 2: unicode; Python 3: str)
2047Text = str
2048
2049
Guido van Rossum91185fe2016-06-08 11:19:11 -07002050# Constant that's True when type checking, but False here.
2051TYPE_CHECKING = False
2052
2053
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002054class IO(Generic[AnyStr]):
2055 """Generic base class for TextIO and BinaryIO.
2056
2057 This is an abstract, generic version of the return of open().
2058
2059 NOTE: This does not distinguish between the different possible
2060 classes (text vs. binary, read vs. write vs. read/write,
2061 append-only, unbuffered). The TextIO and BinaryIO subclasses
2062 below capture the distinctions between text vs. binary, which is
2063 pervasive in the interface; however we currently do not offer a
2064 way to track the other distinctions in the type system.
2065 """
2066
Guido van Rossumd70fe632015-08-05 12:11:06 +02002067 __slots__ = ()
2068
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002069 @abstractproperty
2070 def mode(self) -> str:
2071 pass
2072
2073 @abstractproperty
2074 def name(self) -> str:
2075 pass
2076
2077 @abstractmethod
2078 def close(self) -> None:
2079 pass
2080
2081 @abstractmethod
2082 def closed(self) -> bool:
2083 pass
2084
2085 @abstractmethod
2086 def fileno(self) -> int:
2087 pass
2088
2089 @abstractmethod
2090 def flush(self) -> None:
2091 pass
2092
2093 @abstractmethod
2094 def isatty(self) -> bool:
2095 pass
2096
2097 @abstractmethod
2098 def read(self, n: int = -1) -> AnyStr:
2099 pass
2100
2101 @abstractmethod
2102 def readable(self) -> bool:
2103 pass
2104
2105 @abstractmethod
2106 def readline(self, limit: int = -1) -> AnyStr:
2107 pass
2108
2109 @abstractmethod
2110 def readlines(self, hint: int = -1) -> List[AnyStr]:
2111 pass
2112
2113 @abstractmethod
2114 def seek(self, offset: int, whence: int = 0) -> int:
2115 pass
2116
2117 @abstractmethod
2118 def seekable(self) -> bool:
2119 pass
2120
2121 @abstractmethod
2122 def tell(self) -> int:
2123 pass
2124
2125 @abstractmethod
2126 def truncate(self, size: int = None) -> int:
2127 pass
2128
2129 @abstractmethod
2130 def writable(self) -> bool:
2131 pass
2132
2133 @abstractmethod
2134 def write(self, s: AnyStr) -> int:
2135 pass
2136
2137 @abstractmethod
2138 def writelines(self, lines: List[AnyStr]) -> None:
2139 pass
2140
2141 @abstractmethod
2142 def __enter__(self) -> 'IO[AnyStr]':
2143 pass
2144
2145 @abstractmethod
2146 def __exit__(self, type, value, traceback) -> None:
2147 pass
2148
2149
2150class BinaryIO(IO[bytes]):
2151 """Typed version of the return of open() in binary mode."""
2152
Guido van Rossumd70fe632015-08-05 12:11:06 +02002153 __slots__ = ()
2154
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002155 @abstractmethod
2156 def write(self, s: Union[bytes, bytearray]) -> int:
2157 pass
2158
2159 @abstractmethod
2160 def __enter__(self) -> 'BinaryIO':
2161 pass
2162
2163
2164class TextIO(IO[str]):
2165 """Typed version of the return of open() in text mode."""
2166
Guido van Rossumd70fe632015-08-05 12:11:06 +02002167 __slots__ = ()
2168
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002169 @abstractproperty
2170 def buffer(self) -> BinaryIO:
2171 pass
2172
2173 @abstractproperty
2174 def encoding(self) -> str:
2175 pass
2176
2177 @abstractproperty
Guido van Rossum991d14f2016-11-09 13:12:51 -08002178 def errors(self) -> Optional[str]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002179 pass
2180
2181 @abstractproperty
2182 def line_buffering(self) -> bool:
2183 pass
2184
2185 @abstractproperty
2186 def newlines(self) -> Any:
2187 pass
2188
2189 @abstractmethod
2190 def __enter__(self) -> 'TextIO':
2191 pass
2192
2193
2194class io:
2195 """Wrapper namespace for IO generic classes."""
2196
2197 __all__ = ['IO', 'TextIO', 'BinaryIO']
2198 IO = IO
2199 TextIO = TextIO
2200 BinaryIO = BinaryIO
2201
2202io.__name__ = __name__ + '.io'
2203sys.modules[io.__name__] = io
2204
2205
2206Pattern = _TypeAlias('Pattern', AnyStr, type(stdlib_re.compile('')),
2207 lambda p: p.pattern)
2208Match = _TypeAlias('Match', AnyStr, type(stdlib_re.match('', '')),
2209 lambda m: m.re.pattern)
2210
2211
2212class re:
2213 """Wrapper namespace for re type aliases."""
2214
2215 __all__ = ['Pattern', 'Match']
2216 Pattern = Pattern
2217 Match = Match
2218
2219re.__name__ = __name__ + '.re'
2220sys.modules[re.__name__] = re