blob: c9e341753769e0133daba86bf82ff136d8d3e173 [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,
Guido van Rossume9ed5602017-01-18 13:10:31 -080054 # ContextManager,
55 # AsyncGenerator,
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070056
57 # Structural checks, a.k.a. protocols.
58 'Reversible',
59 'SupportsAbs',
60 'SupportsFloat',
61 'SupportsInt',
62 'SupportsRound',
63
64 # Concrete collection types.
Raymond Hettinger80490522017-01-16 22:42:37 -080065 'Deque',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070066 'Dict',
Guido van Rossumbd5b9a02016-04-05 08:28:52 -070067 'DefaultDict',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070068 'List',
69 'Set',
Guido van Rossumefa798d2016-08-23 11:01:50 -070070 'FrozenSet',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070071 'NamedTuple', # Not really a type.
72 'Generator',
73
74 # One-off things.
75 'AnyStr',
76 'cast',
77 'get_type_hints',
Guido van Rossum91185fe2016-06-08 11:19:11 -070078 'NewType',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070079 'no_type_check',
80 'no_type_check_decorator',
81 'overload',
Guido van Rossum0e0563c2016-04-05 14:54:25 -070082 'Text',
Guido van Rossum91185fe2016-06-08 11:19:11 -070083 'TYPE_CHECKING',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070084]
85
Guido van Rossumbd5b9a02016-04-05 08:28:52 -070086# The pseudo-submodules 're' and 'io' are part of the public
87# namespace, but excluded from __all__ because they might stomp on
88# legitimate imports of those modules.
89
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070090
91def _qualname(x):
92 if sys.version_info[:2] >= (3, 3):
93 return x.__qualname__
94 else:
95 # Fall back to just name.
96 return x.__name__
97
98
Guido van Rossum4cefe742016-09-27 15:20:12 -070099def _trim_name(nm):
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800100 whitelist = ('_TypeAlias', '_ForwardRef', '_TypingBase', '_FinalTypingBase')
101 if nm.startswith('_') and nm not in whitelist:
Guido van Rossum4cefe742016-09-27 15:20:12 -0700102 nm = nm[1:]
103 return nm
104
105
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700106class TypingMeta(type):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800107 """Metaclass for most types defined in typing module
108 (not a part of public API).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700109
110 This overrides __new__() to require an extra keyword parameter
111 '_root', which serves as a guard against naive subclassing of the
112 typing classes. Any legitimate class defined using a metaclass
Guido van Rossumb24569a2016-11-20 18:01:29 -0800113 derived from TypingMeta must pass _root=True.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700114
Guido van Rossumb24569a2016-11-20 18:01:29 -0800115 This also defines a dummy constructor (all the work for most typing
116 constructs is done in __new__) and a nicer repr().
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700117 """
118
119 _is_protocol = False
120
121 def __new__(cls, name, bases, namespace, *, _root=False):
122 if not _root:
123 raise TypeError("Cannot subclass %s" %
124 (', '.join(map(_type_repr, bases)) or '()'))
125 return super().__new__(cls, name, bases, namespace)
126
127 def __init__(self, *args, **kwds):
128 pass
129
130 def _eval_type(self, globalns, localns):
131 """Override this in subclasses to interpret forward references.
132
Guido van Rossumb24569a2016-11-20 18:01:29 -0800133 For example, List['C'] is internally stored as
134 List[_ForwardRef('C')], which should evaluate to List[C],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700135 where C is an object found in globalns or localns (searching
136 localns first, of course).
137 """
138 return self
139
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700140 def _get_type_vars(self, tvars):
141 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700142
143 def __repr__(self):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700144 qname = _trim_name(_qualname(self))
145 return '%s.%s' % (self.__module__, qname)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700146
147
Guido van Rossum4cefe742016-09-27 15:20:12 -0700148class _TypingBase(metaclass=TypingMeta, _root=True):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800149 """Internal indicator of special typing constructs."""
Guido van Rossum4cefe742016-09-27 15:20:12 -0700150
Guido van Rossum83ec3022017-01-17 20:43:28 -0800151 __slots__ = ('__weakref__',)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700152
Guido van Rossum4cefe742016-09-27 15:20:12 -0700153 def __init__(self, *args, **kwds):
154 pass
155
156 def __new__(cls, *args, **kwds):
157 """Constructor.
158
159 This only exists to give a better error message in case
160 someone tries to subclass a special typing object (not a good idea).
161 """
162 if (len(args) == 3 and
163 isinstance(args[0], str) and
164 isinstance(args[1], tuple)):
165 # Close enough.
166 raise TypeError("Cannot subclass %r" % cls)
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700167 return super().__new__(cls)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700168
169 # Things that are not classes also need these.
170 def _eval_type(self, globalns, localns):
171 return self
172
173 def _get_type_vars(self, tvars):
174 pass
175
176 def __repr__(self):
177 cls = type(self)
178 qname = _trim_name(_qualname(cls))
179 return '%s.%s' % (cls.__module__, qname)
180
181 def __call__(self, *args, **kwds):
182 raise TypeError("Cannot instantiate %r" % type(self))
183
184
185class _FinalTypingBase(_TypingBase, _root=True):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800186 """Internal mix-in class to prevent instantiation.
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700187
188 Prevents instantiation unless _root=True is given in class call.
Guido van Rossumb24569a2016-11-20 18:01:29 -0800189 It is used to create pseudo-singleton instances Any, Union, Optional, etc.
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700190 """
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700191
Guido van Rossumd70fe632015-08-05 12:11:06 +0200192 __slots__ = ()
193
Guido van Rossum4cefe742016-09-27 15:20:12 -0700194 def __new__(cls, *args, _root=False, **kwds):
195 self = super().__new__(cls, *args, **kwds)
196 if _root is True:
197 return self
198 raise TypeError("Cannot instantiate %r" % cls)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700199
Guido van Rossumb7dedc82016-10-29 12:44:29 -0700200 def __reduce__(self):
201 return _trim_name(type(self).__name__)
202
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700203
Guido van Rossum4cefe742016-09-27 15:20:12 -0700204class _ForwardRef(_TypingBase, _root=True):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800205 """Internal wrapper to hold a forward reference."""
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700206
Guido van Rossum4cefe742016-09-27 15:20:12 -0700207 __slots__ = ('__forward_arg__', '__forward_code__',
Guido van Rossumc7b92952016-11-10 08:24:06 -0800208 '__forward_evaluated__', '__forward_value__')
Guido van Rossum4cefe742016-09-27 15:20:12 -0700209
210 def __init__(self, arg):
211 super().__init__(arg)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700212 if not isinstance(arg, str):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800213 raise TypeError('Forward reference must be a string -- got %r' % (arg,))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700214 try:
215 code = compile(arg, '<string>', 'eval')
216 except SyntaxError:
Guido van Rossumb24569a2016-11-20 18:01:29 -0800217 raise SyntaxError('Forward reference must be an expression -- got %r' %
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700218 (arg,))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700219 self.__forward_arg__ = arg
220 self.__forward_code__ = code
221 self.__forward_evaluated__ = False
222 self.__forward_value__ = None
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700223
224 def _eval_type(self, globalns, localns):
Guido van Rossumdad17902016-11-10 08:29:18 -0800225 if not self.__forward_evaluated__ or localns is not globalns:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700226 if globalns is None and localns is None:
227 globalns = localns = {}
228 elif globalns is None:
229 globalns = localns
230 elif localns is None:
231 localns = globalns
232 self.__forward_value__ = _type_check(
233 eval(self.__forward_code__, globalns, localns),
234 "Forward references must evaluate to types.")
235 self.__forward_evaluated__ = True
236 return self.__forward_value__
237
Guido van Rossum4cefe742016-09-27 15:20:12 -0700238 def __eq__(self, other):
239 if not isinstance(other, _ForwardRef):
240 return NotImplemented
241 return (self.__forward_arg__ == other.__forward_arg__ and
Guido van Rossumc7b92952016-11-10 08:24:06 -0800242 self.__forward_value__ == other.__forward_value__)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700243
244 def __hash__(self):
Guido van Rossumc7b92952016-11-10 08:24:06 -0800245 return hash((self.__forward_arg__, self.__forward_value__))
Guido van Rossum4cefe742016-09-27 15:20:12 -0700246
Guido van Rossumd70fe632015-08-05 12:11:06 +0200247 def __instancecheck__(self, obj):
248 raise TypeError("Forward references cannot be used with isinstance().")
249
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700250 def __subclasscheck__(self, cls):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700251 raise TypeError("Forward references cannot be used with issubclass().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700252
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700253 def __repr__(self):
254 return '_ForwardRef(%r)' % (self.__forward_arg__,)
255
256
Guido van Rossum4cefe742016-09-27 15:20:12 -0700257class _TypeAlias(_TypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700258 """Internal helper class for defining generic variants of concrete types.
259
Guido van Rossum4cefe742016-09-27 15:20:12 -0700260 Note that this is not a type; let's call it a pseudo-type. It cannot
261 be used in instance and subclass checks in parameterized form, i.e.
262 ``isinstance(42, Match[str])`` raises ``TypeError`` instead of returning
263 ``False``.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700264 """
265
Guido van Rossumd70fe632015-08-05 12:11:06 +0200266 __slots__ = ('name', 'type_var', 'impl_type', 'type_checker')
267
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700268 def __init__(self, name, type_var, impl_type, type_checker):
269 """Initializer.
270
271 Args:
272 name: The name, e.g. 'Pattern'.
273 type_var: The type parameter, e.g. AnyStr, or the
274 specific type, e.g. str.
275 impl_type: The implementation type.
276 type_checker: Function that takes an impl_type instance.
277 and returns a value that should be a type_var instance.
278 """
279 assert isinstance(name, str), repr(name)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700280 assert isinstance(impl_type, type), repr(impl_type)
281 assert not isinstance(impl_type, TypingMeta), repr(impl_type)
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700282 assert isinstance(type_var, (type, _TypingBase)), repr(type_var)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700283 self.name = name
284 self.type_var = type_var
285 self.impl_type = impl_type
286 self.type_checker = type_checker
287
288 def __repr__(self):
289 return "%s[%s]" % (self.name, _type_repr(self.type_var))
290
291 def __getitem__(self, parameter):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700292 if not isinstance(self.type_var, TypeVar):
293 raise TypeError("%s cannot be further parameterized." % self)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700294 if self.type_var.__constraints__ and isinstance(parameter, type):
295 if not issubclass(parameter, self.type_var.__constraints__):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700296 raise TypeError("%s is not a valid substitution for %s." %
297 (parameter, self.type_var))
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700298 if isinstance(parameter, TypeVar) and parameter is not self.type_var:
299 raise TypeError("%s cannot be re-parameterized." % self)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700300 return self.__class__(self.name, parameter,
301 self.impl_type, self.type_checker)
302
Guido van Rossum4cefe742016-09-27 15:20:12 -0700303 def __eq__(self, other):
304 if not isinstance(other, _TypeAlias):
305 return NotImplemented
306 return self.name == other.name and self.type_var == other.type_var
307
308 def __hash__(self):
309 return hash((self.name, self.type_var))
310
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700311 def __instancecheck__(self, obj):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700312 if not isinstance(self.type_var, TypeVar):
313 raise TypeError("Parameterized type aliases cannot be used "
314 "with isinstance().")
315 return isinstance(obj, self.impl_type)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700316
317 def __subclasscheck__(self, cls):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700318 if not isinstance(self.type_var, TypeVar):
319 raise TypeError("Parameterized type aliases cannot be used "
320 "with issubclass().")
321 return issubclass(cls, self.impl_type)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700322
323
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700324def _get_type_vars(types, tvars):
325 for t in types:
Guido van Rossum4cefe742016-09-27 15:20:12 -0700326 if isinstance(t, TypingMeta) or isinstance(t, _TypingBase):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700327 t._get_type_vars(tvars)
328
329
330def _type_vars(types):
331 tvars = []
332 _get_type_vars(types, tvars)
333 return tuple(tvars)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700334
335
336def _eval_type(t, globalns, localns):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700337 if isinstance(t, TypingMeta) or isinstance(t, _TypingBase):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700338 return t._eval_type(globalns, localns)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700339 return t
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700340
341
342def _type_check(arg, msg):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800343 """Check that the argument is a type, and return it (internal helper).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700344
345 As a special case, accept None and return type(None) instead.
346 Also, _TypeAlias instances (e.g. Match, Pattern) are acceptable.
347
348 The msg argument is a human-readable error message, e.g.
349
350 "Union[arg, ...]: arg should be a type."
351
352 We append the repr() of the actual value (truncated to 100 chars).
353 """
354 if arg is None:
355 return type(None)
356 if isinstance(arg, str):
357 arg = _ForwardRef(arg)
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800358 if (
359 isinstance(arg, _TypingBase) and type(arg).__name__ == '_ClassVar' or
360 not isinstance(arg, (type, _TypingBase)) and not callable(arg)
361 ):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700362 raise TypeError(msg + " Got %.100r." % (arg,))
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700363 # Bare Union etc. are not valid as type arguments
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800364 if (
365 type(arg).__name__ in ('_Union', '_Optional') and
366 not getattr(arg, '__origin__', None) or
367 isinstance(arg, TypingMeta) and _gorg(arg) in (Generic, _Protocol)
368 ):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700369 raise TypeError("Plain %s is not valid as type argument" % arg)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700370 return arg
371
372
373def _type_repr(obj):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800374 """Return the repr() of an object, special-casing types (internal helper).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700375
376 If obj is a type, we return a shorter version than the default
377 type.__repr__, based on the module and qualified name, which is
378 typically enough to uniquely identify a type. For everything
379 else, we fall back on repr(obj).
380 """
381 if isinstance(obj, type) and not isinstance(obj, TypingMeta):
382 if obj.__module__ == 'builtins':
383 return _qualname(obj)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700384 return '%s.%s' % (obj.__module__, _qualname(obj))
385 if obj is ...:
386 return('...')
387 if isinstance(obj, types.FunctionType):
388 return obj.__name__
389 return repr(obj)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700390
391
Guido van Rossum4cefe742016-09-27 15:20:12 -0700392class _Any(_FinalTypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700393 """Special type indicating an unconstrained type.
394
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700395 - Any is compatible with every type.
396 - Any assumed to have all methods.
397 - All values assumed to be instances of Any.
398
399 Note that all the above statements are true from the point of view of
400 static type checkers. At runtime, Any should not be used with instance
401 or class checks.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700402 """
403
Guido van Rossumd70fe632015-08-05 12:11:06 +0200404 __slots__ = ()
405
Guido van Rossum4cefe742016-09-27 15:20:12 -0700406 def __instancecheck__(self, obj):
407 raise TypeError("Any cannot be used with isinstance().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700408
Guido van Rossum4cefe742016-09-27 15:20:12 -0700409 def __subclasscheck__(self, cls):
410 raise TypeError("Any cannot be used with issubclass().")
411
412
413Any = _Any(_root=True)
414
415
416class TypeVar(_TypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700417 """Type variable.
418
419 Usage::
420
421 T = TypeVar('T') # Can be anything
422 A = TypeVar('A', str, bytes) # Must be str or bytes
423
424 Type variables exist primarily for the benefit of static type
425 checkers. They serve as the parameters for generic types as well
426 as for generic function definitions. See class Generic for more
427 information on generic types. Generic functions work as follows:
428
Guido van Rossumb24569a2016-11-20 18:01:29 -0800429 def repeat(x: T, n: int) -> List[T]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700430 '''Return a list containing n references to x.'''
431 return [x]*n
432
433 def longest(x: A, y: A) -> A:
434 '''Return the longest of two strings.'''
435 return x if len(x) >= len(y) else y
436
437 The latter example's signature is essentially the overloading
438 of (str, str) -> str and (bytes, bytes) -> bytes. Also note
439 that if the arguments are instances of some subclass of str,
440 the return type is still plain str.
441
Guido van Rossumb24569a2016-11-20 18:01:29 -0800442 At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700443
Guido van Rossumefa798d2016-08-23 11:01:50 -0700444 Type variables defined with covariant=True or contravariant=True
445 can be used do declare covariant or contravariant generic types.
446 See PEP 484 for more details. By default generic types are invariant
447 in all type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700448
449 Type variables can be introspected. e.g.:
450
451 T.__name__ == 'T'
452 T.__constraints__ == ()
453 T.__covariant__ == False
454 T.__contravariant__ = False
455 A.__constraints__ == (str, bytes)
456 """
457
Guido van Rossum4cefe742016-09-27 15:20:12 -0700458 __slots__ = ('__name__', '__bound__', '__constraints__',
459 '__covariant__', '__contravariant__')
460
461 def __init__(self, name, *constraints, bound=None,
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800462 covariant=False, contravariant=False):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700463 super().__init__(name, *constraints, bound=bound,
464 covariant=covariant, contravariant=contravariant)
465 self.__name__ = name
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700466 if covariant and contravariant:
Guido van Rossumefa798d2016-08-23 11:01:50 -0700467 raise ValueError("Bivariant types are not supported.")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700468 self.__covariant__ = bool(covariant)
469 self.__contravariant__ = bool(contravariant)
470 if constraints and bound is not None:
471 raise TypeError("Constraints cannot be combined with bound=...")
472 if constraints and len(constraints) == 1:
473 raise TypeError("A single constraint is not allowed")
474 msg = "TypeVar(name, constraint, ...): constraints must be types."
475 self.__constraints__ = tuple(_type_check(t, msg) for t in constraints)
476 if bound:
477 self.__bound__ = _type_check(bound, "Bound must be a type.")
478 else:
479 self.__bound__ = None
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700480
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700481 def _get_type_vars(self, tvars):
482 if self not in tvars:
483 tvars.append(self)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700484
485 def __repr__(self):
486 if self.__covariant__:
487 prefix = '+'
488 elif self.__contravariant__:
489 prefix = '-'
490 else:
491 prefix = '~'
492 return prefix + self.__name__
493
494 def __instancecheck__(self, instance):
495 raise TypeError("Type variables cannot be used with isinstance().")
496
497 def __subclasscheck__(self, cls):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700498 raise TypeError("Type variables cannot be used with issubclass().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700499
500
501# Some unconstrained type variables. These are used by the container types.
Guido van Rossumeb9aca32016-05-24 16:38:22 -0700502# (These are not for export.)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700503T = TypeVar('T') # Any type.
504KT = TypeVar('KT') # Key type.
505VT = TypeVar('VT') # Value type.
506T_co = TypeVar('T_co', covariant=True) # Any type covariant containers.
507V_co = TypeVar('V_co', covariant=True) # Any type covariant containers.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700508VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
509T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
510
511# A useful type variable with constraints. This represents string types.
Guido van Rossumeb9aca32016-05-24 16:38:22 -0700512# (This one *is* for export!)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700513AnyStr = TypeVar('AnyStr', bytes, str)
514
515
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700516def _replace_arg(arg, tvars, args):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800517 """An internal helper function: replace arg if it is a type variable
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700518 found in tvars with corresponding substitution from args or
519 with corresponding substitution sub-tree if arg is a generic type.
520 """
521
522 if tvars is None:
523 tvars = []
Guido van Rossum83ec3022017-01-17 20:43:28 -0800524 if hasattr(arg, '_subs_tree') and isinstance(arg, (GenericMeta, _TypingBase)):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700525 return arg._subs_tree(tvars, args)
526 if isinstance(arg, TypeVar):
527 for i, tvar in enumerate(tvars):
528 if arg == tvar:
529 return args[i]
530 return arg
531
532
Guido van Rossum83ec3022017-01-17 20:43:28 -0800533# Special typing constructs Union, Optional, Generic, Callable and Tuple
534# use three special attributes for internal bookkeeping of generic types:
535# * __parameters__ is a tuple of unique free type parameters of a generic
536# type, for example, Dict[T, T].__parameters__ == (T,);
537# * __origin__ keeps a reference to a type that was subscripted,
538# e.g., Union[T, int].__origin__ == Union;
539# * __args__ is a tuple of all arguments used in subscripting,
540# e.g., Dict[T, int].__args__ == (T, int).
541
542
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700543def _subs_tree(cls, tvars=None, args=None):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800544 """An internal helper function: calculate substitution tree
545 for generic cls after replacing its type parameters with
546 substitutions in tvars -> args (if any).
547 Repeat the same following __origin__'s.
548
549 Return a list of arguments with all possible substitutions
550 performed. Arguments that are generic classes themselves are represented
551 as tuples (so that no new classes are created by this function).
552 For example: _subs_tree(List[Tuple[int, T]][str]) == [(Tuple, int, str)]
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700553 """
554
555 if cls.__origin__ is None:
556 return cls
557 # Make of chain of origins (i.e. cls -> cls.__origin__)
558 current = cls.__origin__
559 orig_chain = []
560 while current.__origin__ is not None:
561 orig_chain.append(current)
562 current = current.__origin__
563 # Replace type variables in __args__ if asked ...
564 tree_args = []
565 for arg in cls.__args__:
566 tree_args.append(_replace_arg(arg, tvars, args))
567 # ... then continue replacing down the origin chain.
568 for ocls in orig_chain:
569 new_tree_args = []
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800570 for arg in ocls.__args__:
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700571 new_tree_args.append(_replace_arg(arg, ocls.__parameters__, tree_args))
572 tree_args = new_tree_args
573 return tree_args
574
575
576def _remove_dups_flatten(parameters):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800577 """An internal helper for Union creation and substitution: flatten Union's
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700578 among parameters, then remove duplicates and strict subclasses.
579 """
580
581 # Flatten out Union[Union[...], ...].
582 params = []
583 for p in parameters:
584 if isinstance(p, _Union) and p.__origin__ is Union:
585 params.extend(p.__args__)
586 elif isinstance(p, tuple) and len(p) > 0 and p[0] is Union:
587 params.extend(p[1:])
588 else:
589 params.append(p)
590 # Weed out strict duplicates, preserving the first of each occurrence.
591 all_params = set(params)
592 if len(all_params) < len(params):
593 new_params = []
594 for t in params:
595 if t in all_params:
596 new_params.append(t)
597 all_params.remove(t)
598 params = new_params
599 assert not all_params, all_params
600 # Weed out subclasses.
601 # E.g. Union[int, Employee, Manager] == Union[int, Employee].
602 # If object is present it will be sole survivor among proper classes.
603 # Never discard type variables.
604 # (In particular, Union[str, AnyStr] != AnyStr.)
605 all_params = set(params)
606 for t1 in params:
607 if not isinstance(t1, type):
608 continue
609 if any(isinstance(t2, type) and issubclass(t1, t2)
610 for t2 in all_params - {t1}
611 if not (isinstance(t2, GenericMeta) and
612 t2.__origin__ is not None)):
613 all_params.remove(t1)
614 return tuple(t for t in params if t in all_params)
615
616
617def _check_generic(cls, parameters):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800618 # Check correct count for parameters of a generic cls (internal helper).
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700619 if not cls.__parameters__:
620 raise TypeError("%s is not a generic class" % repr(cls))
621 alen = len(parameters)
622 elen = len(cls.__parameters__)
623 if alen != elen:
624 raise TypeError("Too %s parameters for %s; actual %s, expected %s" %
625 ("many" if alen > elen else "few", repr(cls), alen, elen))
626
627
Guido van Rossum9b107562016-11-09 13:23:04 -0800628_cleanups = []
629
630
Guido van Rossum4cefe742016-09-27 15:20:12 -0700631def _tp_cache(func):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800632 """Internal wrapper caching __getitem__ of generic types with a fallback to
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700633 original function for non-hashable arguments.
634 """
635
Guido van Rossum4cefe742016-09-27 15:20:12 -0700636 cached = functools.lru_cache()(func)
Guido van Rossum9b107562016-11-09 13:23:04 -0800637 _cleanups.append(cached.cache_clear)
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800638
Guido van Rossum4cefe742016-09-27 15:20:12 -0700639 @functools.wraps(func)
640 def inner(*args, **kwds):
641 try:
642 return cached(*args, **kwds)
643 except TypeError:
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700644 pass # All real errors (not unhashable args) are raised below.
Guido van Rossum4cefe742016-09-27 15:20:12 -0700645 return func(*args, **kwds)
646 return inner
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700647
648
Guido van Rossum4cefe742016-09-27 15:20:12 -0700649class _Union(_FinalTypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700650 """Union type; Union[X, Y] means either X or Y.
651
652 To define a union, use e.g. Union[int, str]. Details:
653
654 - The arguments must be types and there must be at least one.
655
656 - None as an argument is a special case and is replaced by
657 type(None).
658
659 - Unions of unions are flattened, e.g.::
660
661 Union[Union[int, str], float] == Union[int, str, float]
662
663 - Unions of a single argument vanish, e.g.::
664
665 Union[int] == int # The constructor actually returns int
666
667 - Redundant arguments are skipped, e.g.::
668
669 Union[int, str, int] == Union[int, str]
670
671 - When comparing unions, the argument order is ignored, e.g.::
672
673 Union[int, str] == Union[str, int]
674
675 - When two arguments have a subclass relationship, the least
676 derived argument is kept, e.g.::
677
678 class Employee: pass
679 class Manager(Employee): pass
680 Union[int, Employee, Manager] == Union[int, Employee]
681 Union[Manager, int, Employee] == Union[int, Employee]
682 Union[Employee, Manager] == Employee
683
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700684 - Similar for object::
685
686 Union[int, object] == object
687
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700688 - You cannot subclass or instantiate a union.
689
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700690 - You can use Optional[X] as a shorthand for Union[X, None].
691 """
692
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700693 __slots__ = ('__parameters__', '__args__', '__origin__', '__tree_hash__')
Guido van Rossum4cefe742016-09-27 15:20:12 -0700694
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700695 def __new__(cls, parameters=None, origin=None, *args, _root=False):
696 self = super().__new__(cls, parameters, origin, *args, _root=_root)
697 if origin is None:
698 self.__parameters__ = None
699 self.__args__ = None
700 self.__origin__ = None
701 self.__tree_hash__ = hash(frozenset(('Union',)))
Guido van Rossum4cefe742016-09-27 15:20:12 -0700702 return self
703 if not isinstance(parameters, tuple):
704 raise TypeError("Expected parameters=<tuple>")
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700705 if origin is Union:
706 parameters = _remove_dups_flatten(parameters)
707 # It's not a union if there's only one type left.
708 if len(parameters) == 1:
709 return parameters[0]
710 self.__parameters__ = _type_vars(parameters)
711 self.__args__ = parameters
712 self.__origin__ = origin
713 # Pre-calculate the __hash__ on instantiation.
714 # This improves speed for complex substitutions.
715 subs_tree = self._subs_tree()
716 if isinstance(subs_tree, tuple):
717 self.__tree_hash__ = hash(frozenset(subs_tree))
718 else:
719 self.__tree_hash__ = hash(subs_tree)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700720 return self
721
722 def _eval_type(self, globalns, localns):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700723 if self.__args__ is None:
Guido van Rossum4cefe742016-09-27 15:20:12 -0700724 return self
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700725 ev_args = tuple(_eval_type(t, globalns, localns) for t in self.__args__)
726 ev_origin = _eval_type(self.__origin__, globalns, localns)
727 if ev_args == self.__args__ and ev_origin == self.__origin__:
728 # Everything is already evaluated.
729 return self
730 return self.__class__(ev_args, ev_origin, _root=True)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700731
732 def _get_type_vars(self, tvars):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700733 if self.__origin__ and self.__parameters__:
734 _get_type_vars(self.__parameters__, tvars)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700735
736 def __repr__(self):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700737 if self.__origin__ is None:
738 return super().__repr__()
739 tree = self._subs_tree()
740 if not isinstance(tree, tuple):
741 return repr(tree)
742 return tree[0]._tree_repr(tree)
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700743
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700744 def _tree_repr(self, tree):
745 arg_list = []
746 for arg in tree[1:]:
747 if not isinstance(arg, tuple):
748 arg_list.append(_type_repr(arg))
749 else:
750 arg_list.append(arg[0]._tree_repr(arg))
751 return super().__repr__() + '[%s]' % ', '.join(arg_list)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700752
753 @_tp_cache
754 def __getitem__(self, parameters):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700755 if parameters == ():
756 raise TypeError("Cannot take a Union of no types.")
757 if not isinstance(parameters, tuple):
758 parameters = (parameters,)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700759 if self.__origin__ is None:
760 msg = "Union[arg, ...]: each arg must be a type."
761 else:
762 msg = "Parameters to generic types must be types."
763 parameters = tuple(_type_check(p, msg) for p in parameters)
764 if self is not Union:
765 _check_generic(self, parameters)
766 return self.__class__(parameters, origin=self, _root=True)
767
768 def _subs_tree(self, tvars=None, args=None):
769 if self is Union:
770 return Union # Nothing to substitute
771 tree_args = _subs_tree(self, tvars, args)
772 tree_args = _remove_dups_flatten(tree_args)
773 if len(tree_args) == 1:
774 return tree_args[0] # Union of a single type is that type
775 return (Union,) + tree_args
Guido van Rossum4cefe742016-09-27 15:20:12 -0700776
777 def __eq__(self, other):
Guido van Rossum83ec3022017-01-17 20:43:28 -0800778 if isinstance(other, _Union):
779 return self.__tree_hash__ == other.__tree_hash__
780 elif self is not Union:
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700781 return self._subs_tree() == other
Guido van Rossum83ec3022017-01-17 20:43:28 -0800782 else:
783 return self is other
Guido van Rossum4cefe742016-09-27 15:20:12 -0700784
785 def __hash__(self):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700786 return self.__tree_hash__
Guido van Rossum4cefe742016-09-27 15:20:12 -0700787
788 def __instancecheck__(self, obj):
789 raise TypeError("Unions cannot be used with isinstance().")
790
791 def __subclasscheck__(self, cls):
792 raise TypeError("Unions cannot be used with issubclass().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700793
794
Guido van Rossum4cefe742016-09-27 15:20:12 -0700795Union = _Union(_root=True)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700796
797
Guido van Rossum4cefe742016-09-27 15:20:12 -0700798class _Optional(_FinalTypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700799 """Optional type.
800
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700801 Optional[X] is equivalent to Union[X, None].
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700802 """
803
Guido van Rossumd70fe632015-08-05 12:11:06 +0200804 __slots__ = ()
805
Guido van Rossum4cefe742016-09-27 15:20:12 -0700806 @_tp_cache
807 def __getitem__(self, arg):
808 arg = _type_check(arg, "Optional[t] requires a single type.")
809 return Union[arg, type(None)]
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700810
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700811
Guido van Rossum4cefe742016-09-27 15:20:12 -0700812Optional = _Optional(_root=True)
813
814
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700815def _gorg(a):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800816 """Return the farthest origin of a generic class (internal helper)."""
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700817 assert isinstance(a, GenericMeta)
818 while a.__origin__ is not None:
819 a = a.__origin__
820 return a
821
822
823def _geqv(a, b):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800824 """Return whether two generic classes are equivalent (internal helper).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700825
826 The intention is to consider generic class X and any of its
Guido van Rossumb24569a2016-11-20 18:01:29 -0800827 parameterized forms (X[T], X[int], etc.) as equivalent.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700828
829 However, X is not equivalent to a subclass of X.
830
831 The relation is reflexive, symmetric and transitive.
832 """
833 assert isinstance(a, GenericMeta) and isinstance(b, GenericMeta)
834 # Reduce each to its origin.
835 return _gorg(a) is _gorg(b)
836
837
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700838def _next_in_mro(cls):
839 """Helper for Generic.__new__.
840
841 Returns the class after the last occurrence of Generic or
842 Generic[...] in cls.__mro__.
843 """
844 next_in_mro = object
845 # Look for the last occurrence of Generic or Generic[...].
846 for i, c in enumerate(cls.__mro__[:-1]):
847 if isinstance(c, GenericMeta) and _gorg(c) is Generic:
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800848 next_in_mro = cls.__mro__[i + 1]
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700849 return next_in_mro
850
851
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700852def _valid_for_check(cls):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800853 """An internal helper to prohibit isinstance([1], List[str]) etc."""
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700854 if cls is Generic:
855 raise TypeError("Class %r cannot be used with class "
856 "or instance checks" % cls)
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800857 if (
858 cls.__origin__ is not None and
859 sys._getframe(3).f_globals['__name__'] not in ['abc', 'functools']
860 ):
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700861 raise TypeError("Parameterized generics cannot be used with class "
862 "or instance checks")
863
864
865def _make_subclasshook(cls):
866 """Construct a __subclasshook__ callable that incorporates
867 the associated __extra__ class in subclass checks performed
868 against cls.
869 """
870 if isinstance(cls.__extra__, abc.ABCMeta):
871 # The logic mirrors that of ABCMeta.__subclasscheck__.
872 # Registered classes need not be checked here because
873 # cls and its extra share the same _abc_registry.
874 def __extrahook__(subclass):
875 _valid_for_check(cls)
876 res = cls.__extra__.__subclasshook__(subclass)
877 if res is not NotImplemented:
878 return res
879 if cls.__extra__ in subclass.__mro__:
880 return True
881 for scls in cls.__extra__.__subclasses__():
882 if isinstance(scls, GenericMeta):
883 continue
884 if issubclass(subclass, scls):
885 return True
886 return NotImplemented
887 else:
888 # For non-ABC extras we'll just call issubclass().
889 def __extrahook__(subclass):
890 _valid_for_check(cls)
891 if cls.__extra__ and issubclass(subclass, cls.__extra__):
892 return True
893 return NotImplemented
894 return __extrahook__
895
896
Guido van Rossum61f0a022016-11-29 09:46:21 -0800897def _no_slots_copy(dct):
898 """Internal helper: copy class __dict__ and clean slots class variables.
899 (They will be re-created if necessary by normal class machinery.)
900 """
901 dict_copy = dict(dct)
902 if '__slots__' in dict_copy:
903 for slot in dict_copy['__slots__']:
904 dict_copy.pop(slot, None)
905 return dict_copy
906
907
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700908class GenericMeta(TypingMeta, abc.ABCMeta):
Guido van Rossum83ec3022017-01-17 20:43:28 -0800909 """Metaclass for generic types.
910
911 This is a metaclass for typing.Generic and generic ABCs defined in
912 typing module. User defined subclasses of GenericMeta can override
913 __new__ and invoke super().__new__. Note that GenericMeta.__new__
914 has strict rules on what is allowed in its bases argument:
915 * plain Generic is disallowed in bases;
916 * Generic[...] should appear in bases at most once;
917 * if Generic[...] is present, then it should list all type variables
918 that appear in other bases.
919 In addition, type of all generic bases is erased, e.g., C[int] is
920 stripped to plain C.
921 """
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700922
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700923 def __new__(cls, name, bases, namespace,
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700924 tvars=None, args=None, origin=None, extra=None, orig_bases=None):
Guido van Rossum83ec3022017-01-17 20:43:28 -0800925 """Create a new generic class. GenericMeta.__new__ accepts
926 keyword arguments that are used for internal bookkeeping, therefore
927 an override should pass unused keyword arguments to super().
928 """
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700929 if tvars is not None:
930 # Called from __getitem__() below.
931 assert origin is not None
932 assert all(isinstance(t, TypeVar) for t in tvars), tvars
933 else:
934 # Called from class statement.
935 assert tvars is None, tvars
936 assert args is None, args
937 assert origin is None, origin
938
939 # Get the full set of tvars from the bases.
940 tvars = _type_vars(bases)
941 # Look for Generic[T1, ..., Tn].
942 # If found, tvars must be a subset of it.
943 # If not found, tvars is it.
944 # Also check for and reject plain Generic,
945 # and reject multiple Generic[...].
946 gvars = None
947 for base in bases:
948 if base is Generic:
949 raise TypeError("Cannot inherit from plain Generic")
950 if (isinstance(base, GenericMeta) and
951 base.__origin__ is Generic):
952 if gvars is not None:
953 raise TypeError(
954 "Cannot inherit from Generic[...] multiple types.")
955 gvars = base.__parameters__
956 if gvars is None:
957 gvars = tvars
958 else:
959 tvarset = set(tvars)
960 gvarset = set(gvars)
961 if not tvarset <= gvarset:
962 raise TypeError(
963 "Some type variables (%s) "
964 "are not listed in Generic[%s]" %
965 (", ".join(str(t) for t in tvars if t not in gvarset),
966 ", ".join(str(g) for g in gvars)))
967 tvars = gvars
968
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700969 initial_bases = bases
970 if extra is not None and type(extra) is abc.ABCMeta and extra not in bases:
971 bases = (extra,) + bases
972 bases = tuple(_gorg(b) if isinstance(b, GenericMeta) else b for b in bases)
973
974 # remove bare Generic from bases if there are other generic bases
975 if any(isinstance(b, GenericMeta) and b is not Generic for b in bases):
976 bases = tuple(b for b in bases if b is not Generic)
977 self = super().__new__(cls, name, bases, namespace, _root=True)
978
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700979 self.__parameters__ = tvars
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700980 # Be prepared that GenericMeta will be subclassed by TupleMeta
981 # and CallableMeta, those two allow ..., (), or [] in __args___.
982 self.__args__ = tuple(... if a is _TypingEllipsis else
983 () if a is _TypingEmpty else
984 a for a in args) if args else None
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700985 self.__origin__ = origin
Guido van Rossum1cea70f2016-05-18 08:35:00 -0700986 self.__extra__ = extra
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700987 # Speed hack (https://github.com/python/typing/issues/196).
988 self.__next_in_mro__ = _next_in_mro(self)
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700989 # Preserve base classes on subclassing (__bases__ are type erased now).
990 if orig_bases is None:
991 self.__orig_bases__ = initial_bases
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700992
993 # This allows unparameterized generic collections to be used
994 # with issubclass() and isinstance() in the same way as their
995 # collections.abc counterparts (e.g., isinstance([], Iterable)).
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800996 if (
997 # allow overriding
998 '__subclasshook__' not in namespace and extra or
999 hasattr(self.__subclasshook__, '__name__') and
1000 self.__subclasshook__.__name__ == '__extrahook__'
1001 ):
Guido van Rossume2592672016-10-08 20:27:22 -07001002 self.__subclasshook__ = _make_subclasshook(self)
Guido van Rossumb47c9d22016-10-03 08:40:50 -07001003 if isinstance(extra, abc.ABCMeta):
1004 self._abc_registry = extra._abc_registry
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001005
1006 if origin and hasattr(origin, '__qualname__'): # Fix for Python 3.2.
1007 self.__qualname__ = origin.__qualname__
1008 self.__tree_hash__ = hash(self._subs_tree()) if origin else hash((self.__name__,))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001009 return self
1010
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001011 def _get_type_vars(self, tvars):
1012 if self.__origin__ and self.__parameters__:
1013 _get_type_vars(self.__parameters__, tvars)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001014
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001015 def _eval_type(self, globalns, localns):
1016 ev_origin = (self.__origin__._eval_type(globalns, localns)
1017 if self.__origin__ else None)
1018 ev_args = tuple(_eval_type(a, globalns, localns) for a
1019 in self.__args__) if self.__args__ else None
1020 if ev_origin == self.__origin__ and ev_args == self.__args__:
1021 return self
1022 return self.__class__(self.__name__,
1023 self.__bases__,
Guido van Rossum61f0a022016-11-29 09:46:21 -08001024 _no_slots_copy(self.__dict__),
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001025 tvars=_type_vars(ev_args) if ev_args else None,
1026 args=ev_args,
1027 origin=ev_origin,
1028 extra=self.__extra__,
1029 orig_bases=self.__orig_bases__)
1030
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001031 def __repr__(self):
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001032 if self.__origin__ is None:
1033 return super().__repr__()
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001034 return self._tree_repr(self._subs_tree())
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001035
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001036 def _tree_repr(self, tree):
1037 arg_list = []
1038 for arg in tree[1:]:
1039 if arg == ():
1040 arg_list.append('()')
1041 elif not isinstance(arg, tuple):
1042 arg_list.append(_type_repr(arg))
1043 else:
1044 arg_list.append(arg[0]._tree_repr(arg))
1045 return super().__repr__() + '[%s]' % ', '.join(arg_list)
1046
1047 def _subs_tree(self, tvars=None, args=None):
1048 if self.__origin__ is None:
1049 return self
1050 tree_args = _subs_tree(self, tvars, args)
1051 return (_gorg(self),) + tuple(tree_args)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001052
1053 def __eq__(self, other):
1054 if not isinstance(other, GenericMeta):
1055 return NotImplemented
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001056 if self.__origin__ is None or other.__origin__ is None:
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001057 return self is other
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001058 return self.__tree_hash__ == other.__tree_hash__
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001059
1060 def __hash__(self):
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001061 return self.__tree_hash__
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001062
Guido van Rossum4cefe742016-09-27 15:20:12 -07001063 @_tp_cache
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001064 def __getitem__(self, params):
1065 if not isinstance(params, tuple):
1066 params = (params,)
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001067 if not params and not _gorg(self) is Tuple:
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001068 raise TypeError(
1069 "Parameter list to %s[...] cannot be empty" % _qualname(self))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001070 msg = "Parameters to generic types must be types."
1071 params = tuple(_type_check(p, msg) for p in params)
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001072 if self is Generic:
1073 # Generic can only be subscripted with unique type variables.
1074 if not all(isinstance(p, TypeVar) for p in params):
1075 raise TypeError(
1076 "Parameters to Generic[...] must all be type variables")
Guido van Rossumd70fe632015-08-05 12:11:06 +02001077 if len(set(params)) != len(params):
Guido van Rossum1b669102015-09-04 12:15:54 -07001078 raise TypeError(
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001079 "Parameters to Generic[...] must all be unique")
1080 tvars = params
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001081 args = params
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001082 elif self in (Tuple, Callable):
1083 tvars = _type_vars(params)
1084 args = params
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001085 elif self is _Protocol:
1086 # _Protocol is internal, don't check anything.
1087 tvars = params
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001088 args = params
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001089 elif self.__origin__ in (Generic, _Protocol):
1090 # Can't subscript Generic[...] or _Protocol[...].
1091 raise TypeError("Cannot subscript already-subscripted %s" %
1092 repr(self))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001093 else:
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001094 # Subscripting a regular Generic subclass.
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001095 _check_generic(self, params)
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001096 tvars = _type_vars(params)
1097 args = params
1098 return self.__class__(self.__name__,
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001099 self.__bases__,
Guido van Rossum61f0a022016-11-29 09:46:21 -08001100 _no_slots_copy(self.__dict__),
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001101 tvars=tvars,
1102 args=args,
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001103 origin=self,
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001104 extra=self.__extra__,
1105 orig_bases=self.__orig_bases__)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001106
Guido van Rossum1b669102015-09-04 12:15:54 -07001107 def __instancecheck__(self, instance):
1108 # Since we extend ABC.__subclasscheck__ and
1109 # ABC.__instancecheck__ inlines the cache checking done by the
1110 # latter, we must extend __instancecheck__ too. For simplicity
1111 # we just skip the cache check -- instance checks for generic
1112 # classes are supposed to be rare anyways.
Guido van Rossumb47c9d22016-10-03 08:40:50 -07001113 return issubclass(instance.__class__, self)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001114
Guido van Rossumb7dedc82016-10-29 12:44:29 -07001115 def __copy__(self):
Guido van Rossum61f0a022016-11-29 09:46:21 -08001116 return self.__class__(self.__name__, self.__bases__,
1117 _no_slots_copy(self.__dict__),
Guido van Rossumb7dedc82016-10-29 12:44:29 -07001118 self.__parameters__, self.__args__, self.__origin__,
1119 self.__extra__, self.__orig_bases__)
1120
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001121
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001122# Prevent checks for Generic to crash when defining Generic.
1123Generic = None
1124
1125
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001126def _generic_new(base_cls, cls, *args, **kwds):
1127 # Assure type is erased on instantiation,
1128 # but attempt to store it in __orig_class__
1129 if cls.__origin__ is None:
1130 return base_cls.__new__(cls)
1131 else:
1132 origin = _gorg(cls)
1133 obj = base_cls.__new__(origin)
1134 try:
1135 obj.__orig_class__ = cls
1136 except AttributeError:
1137 pass
1138 obj.__init__(*args, **kwds)
1139 return obj
1140
1141
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001142class Generic(metaclass=GenericMeta):
1143 """Abstract base class for generic types.
1144
Guido van Rossumb24569a2016-11-20 18:01:29 -08001145 A generic type is typically declared by inheriting from
1146 this class parameterized with one or more type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001147 For example, a generic mapping type might be defined as::
1148
1149 class Mapping(Generic[KT, VT]):
1150 def __getitem__(self, key: KT) -> VT:
1151 ...
1152 # Etc.
1153
1154 This class can then be used as follows::
1155
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001156 def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001157 try:
1158 return mapping[key]
1159 except KeyError:
1160 return default
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001161 """
1162
Guido van Rossumd70fe632015-08-05 12:11:06 +02001163 __slots__ = ()
1164
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001165 def __new__(cls, *args, **kwds):
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001166 if _geqv(cls, Generic):
1167 raise TypeError("Type Generic cannot be instantiated; "
1168 "it can be used only as a base class")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001169 return _generic_new(cls.__next_in_mro__, cls, *args, **kwds)
1170
1171
1172class _TypingEmpty:
Guido van Rossumb24569a2016-11-20 18:01:29 -08001173 """Internal placeholder for () or []. Used by TupleMeta and CallableMeta
1174 to allow empty list/tuple in specific places, without allowing them
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001175 to sneak in where prohibited.
1176 """
1177
1178
1179class _TypingEllipsis:
Guido van Rossumb24569a2016-11-20 18:01:29 -08001180 """Internal placeholder for ... (ellipsis)."""
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001181
1182
1183class TupleMeta(GenericMeta):
Guido van Rossumb24569a2016-11-20 18:01:29 -08001184 """Metaclass for Tuple (internal)."""
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001185
1186 @_tp_cache
1187 def __getitem__(self, parameters):
1188 if self.__origin__ is not None or not _geqv(self, Tuple):
1189 # Normal generic rules apply if this is not the first subscription
1190 # or a subscription of a subclass.
1191 return super().__getitem__(parameters)
1192 if parameters == ():
1193 return super().__getitem__((_TypingEmpty,))
1194 if not isinstance(parameters, tuple):
1195 parameters = (parameters,)
1196 if len(parameters) == 2 and parameters[1] is ...:
1197 msg = "Tuple[t, ...]: t must be a type."
1198 p = _type_check(parameters[0], msg)
1199 return super().__getitem__((p, _TypingEllipsis))
1200 msg = "Tuple[t0, t1, ...]: each t must be a type."
1201 parameters = tuple(_type_check(p, msg) for p in parameters)
1202 return super().__getitem__(parameters)
1203
1204 def __instancecheck__(self, obj):
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001205 if self.__args__ is None:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001206 return isinstance(obj, tuple)
1207 raise TypeError("Parameterized Tuple cannot be used "
1208 "with isinstance().")
1209
1210 def __subclasscheck__(self, cls):
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001211 if self.__args__ is None:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001212 return issubclass(cls, tuple)
1213 raise TypeError("Parameterized Tuple cannot be used "
1214 "with issubclass().")
1215
1216
1217class Tuple(tuple, extra=tuple, metaclass=TupleMeta):
1218 """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
1219
1220 Example: Tuple[T1, T2] is a tuple of two elements corresponding
1221 to type variables T1 and T2. Tuple[int, float, str] is a tuple
1222 of an int, a float and a string.
1223
1224 To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
1225 """
1226
1227 __slots__ = ()
1228
1229 def __new__(cls, *args, **kwds):
1230 if _geqv(cls, Tuple):
1231 raise TypeError("Type Tuple cannot be instantiated; "
1232 "use tuple() instead")
1233 return _generic_new(tuple, cls, *args, **kwds)
1234
1235
1236class CallableMeta(GenericMeta):
Guido van Rossumb24569a2016-11-20 18:01:29 -08001237 """Metaclass for Callable (internal)."""
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001238
1239 def __repr__(self):
1240 if self.__origin__ is None:
1241 return super().__repr__()
1242 return self._tree_repr(self._subs_tree())
1243
1244 def _tree_repr(self, tree):
1245 if _gorg(self) is not Callable:
1246 return super()._tree_repr(tree)
1247 # For actual Callable (not its subclass) we override
1248 # super()._tree_repr() for nice formatting.
1249 arg_list = []
1250 for arg in tree[1:]:
Guido van Rossum991d14f2016-11-09 13:12:51 -08001251 if not isinstance(arg, tuple):
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001252 arg_list.append(_type_repr(arg))
1253 else:
1254 arg_list.append(arg[0]._tree_repr(arg))
Guido van Rossum991d14f2016-11-09 13:12:51 -08001255 if arg_list[0] == '...':
1256 return repr(tree[0]) + '[..., %s]' % arg_list[1]
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001257 return (repr(tree[0]) +
1258 '[[%s], %s]' % (', '.join(arg_list[:-1]), arg_list[-1]))
1259
1260 def __getitem__(self, parameters):
Guido van Rossumb24569a2016-11-20 18:01:29 -08001261 """A thin wrapper around __getitem_inner__ to provide the latter
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001262 with hashable arguments to improve speed.
1263 """
1264
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001265 if self.__origin__ is not None or not _geqv(self, Callable):
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001266 return super().__getitem__(parameters)
1267 if not isinstance(parameters, tuple) or len(parameters) != 2:
1268 raise TypeError("Callable must be used as "
1269 "Callable[[arg, ...], result].")
1270 args, result = parameters
Guido van Rossum991d14f2016-11-09 13:12:51 -08001271 if args is Ellipsis:
1272 parameters = (Ellipsis, result)
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001273 else:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001274 if not isinstance(args, list):
1275 raise TypeError("Callable[args, result]: args must be a list."
1276 " Got %.100r." % (args,))
Guido van Rossum991d14f2016-11-09 13:12:51 -08001277 parameters = (tuple(args), result)
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001278 return self.__getitem_inner__(parameters)
1279
1280 @_tp_cache
1281 def __getitem_inner__(self, parameters):
Guido van Rossum991d14f2016-11-09 13:12:51 -08001282 args, result = parameters
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001283 msg = "Callable[args, result]: result must be a type."
1284 result = _type_check(result, msg)
Guido van Rossum991d14f2016-11-09 13:12:51 -08001285 if args is Ellipsis:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001286 return super().__getitem__((_TypingEllipsis, result))
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001287 msg = "Callable[[arg, ...], result]: each arg must be a type."
1288 args = tuple(_type_check(arg, msg) for arg in args)
1289 parameters = args + (result,)
1290 return super().__getitem__(parameters)
1291
1292
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001293class Callable(extra=collections_abc.Callable, metaclass=CallableMeta):
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001294 """Callable type; Callable[[int], str] is a function of (int) -> str.
1295
1296 The subscription syntax must always be used with exactly two
1297 values: the argument list and the return type. The argument list
Guido van Rossumb24569a2016-11-20 18:01:29 -08001298 must be a list of types or ellipsis; the return type must be a single type.
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001299
1300 There is no syntax to indicate optional or keyword arguments,
1301 such function types are rarely used as callback types.
1302 """
1303
1304 __slots__ = ()
1305
1306 def __new__(cls, *args, **kwds):
1307 if _geqv(cls, Callable):
1308 raise TypeError("Type Callable cannot be instantiated; "
1309 "use a non-abstract subclass instead")
1310 return _generic_new(cls.__next_in_mro__, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001311
1312
Guido van Rossum4cefe742016-09-27 15:20:12 -07001313class _ClassVar(_FinalTypingBase, _root=True):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001314 """Special type construct to mark class variables.
1315
1316 An annotation wrapped in ClassVar indicates that a given
1317 attribute is intended to be used as a class variable and
1318 should not be set on instances of that class. Usage::
1319
1320 class Starship:
1321 stats: ClassVar[Dict[str, int]] = {} # class variable
1322 damage: int = 10 # instance variable
1323
1324 ClassVar accepts only types and cannot be further subscribed.
1325
1326 Note that ClassVar is not a class itself, and should not
1327 be used with isinstance() or issubclass().
1328 """
1329
Guido van Rossum4cefe742016-09-27 15:20:12 -07001330 __slots__ = ('__type__',)
1331
1332 def __init__(self, tp=None, **kwds):
1333 self.__type__ = tp
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001334
1335 def __getitem__(self, item):
1336 cls = type(self)
1337 if self.__type__ is None:
1338 return cls(_type_check(item,
Guido van Rossum4cefe742016-09-27 15:20:12 -07001339 '{} accepts only single type.'.format(cls.__name__[1:])),
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001340 _root=True)
1341 raise TypeError('{} cannot be further subscripted'
1342 .format(cls.__name__[1:]))
1343
1344 def _eval_type(self, globalns, localns):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001345 new_tp = _eval_type(self.__type__, globalns, localns)
1346 if new_tp == self.__type__:
1347 return self
1348 return type(self)(new_tp, _root=True)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001349
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001350 def __repr__(self):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001351 r = super().__repr__()
1352 if self.__type__ is not None:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001353 r += '[{}]'.format(_type_repr(self.__type__))
Guido van Rossum4cefe742016-09-27 15:20:12 -07001354 return r
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001355
1356 def __hash__(self):
1357 return hash((type(self).__name__, self.__type__))
1358
1359 def __eq__(self, other):
1360 if not isinstance(other, _ClassVar):
1361 return NotImplemented
1362 if self.__type__ is not None:
1363 return self.__type__ == other.__type__
1364 return self is other
1365
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001366
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001367ClassVar = _ClassVar(_root=True)
1368
1369
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001370def cast(typ, val):
1371 """Cast a value to a type.
1372
1373 This returns the value unchanged. To the type checker this
1374 signals that the return value has the designated type, but at
1375 runtime we intentionally don't check anything (we want this
1376 to be as fast as possible).
1377 """
1378 return val
1379
1380
1381def _get_defaults(func):
1382 """Internal helper to extract the default arguments, by name."""
Guido van Rossum991d14f2016-11-09 13:12:51 -08001383 try:
1384 code = func.__code__
1385 except AttributeError:
1386 # Some built-in functions don't have __code__, __defaults__, etc.
1387 return {}
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001388 pos_count = code.co_argcount
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001389 arg_names = code.co_varnames
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001390 arg_names = arg_names[:pos_count]
1391 defaults = func.__defaults__ or ()
1392 kwdefaults = func.__kwdefaults__
1393 res = dict(kwdefaults) if kwdefaults else {}
1394 pos_offset = pos_count - len(defaults)
1395 for name, value in zip(arg_names[pos_offset:], defaults):
1396 assert name not in res
1397 res[name] = value
1398 return res
1399
1400
Guido van Rossum991d14f2016-11-09 13:12:51 -08001401def get_type_hints(obj, globalns=None, localns=None):
1402 """Return type hints for an object.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001403
Guido van Rossum991d14f2016-11-09 13:12:51 -08001404 This is often the same as obj.__annotations__, but it handles
1405 forward references encoded as string literals, and if necessary
1406 adds Optional[t] if a default value equal to None is set.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001407
Guido van Rossum991d14f2016-11-09 13:12:51 -08001408 The argument may be a module, class, method, or function. The annotations
1409 are returned as a dictionary. For classes, annotations include also
1410 inherited members.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001411
Guido van Rossum991d14f2016-11-09 13:12:51 -08001412 TypeError is raised if the argument is not of a type that can contain
1413 annotations, and an empty dictionary is returned if no annotations are
1414 present.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001415
Guido van Rossum991d14f2016-11-09 13:12:51 -08001416 BEWARE -- the behavior of globalns and localns is counterintuitive
1417 (unless you are familiar with how eval() and exec() work). The
1418 search order is locals first, then globals.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001419
Guido van Rossum991d14f2016-11-09 13:12:51 -08001420 - If no dict arguments are passed, an attempt is made to use the
1421 globals from obj, and these are also used as the locals. If the
1422 object does not appear to have globals, an exception is raised.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001423
Guido van Rossum991d14f2016-11-09 13:12:51 -08001424 - If one dict argument is passed, it is used for both globals and
1425 locals.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001426
Guido van Rossum991d14f2016-11-09 13:12:51 -08001427 - If two dict arguments are passed, they specify globals and
1428 locals, respectively.
1429 """
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001430
Guido van Rossum991d14f2016-11-09 13:12:51 -08001431 if getattr(obj, '__no_type_check__', None):
1432 return {}
1433 if globalns is None:
1434 globalns = getattr(obj, '__globals__', {})
1435 if localns is None:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001436 localns = globalns
Guido van Rossum991d14f2016-11-09 13:12:51 -08001437 elif localns is None:
1438 localns = globalns
1439 # Classes require a special treatment.
1440 if isinstance(obj, type):
1441 hints = {}
1442 for base in reversed(obj.__mro__):
1443 ann = base.__dict__.get('__annotations__', {})
1444 for name, value in ann.items():
1445 if value is None:
1446 value = type(None)
1447 if isinstance(value, str):
1448 value = _ForwardRef(value)
1449 value = _eval_type(value, globalns, localns)
1450 hints[name] = value
1451 return hints
1452 hints = getattr(obj, '__annotations__', None)
1453 if hints is None:
1454 # Return empty annotations for something that _could_ have them.
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001455 if (
1456 isinstance(obj, types.FunctionType) or
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001457 isinstance(obj, types.BuiltinFunctionType) or
Guido van Rossum991d14f2016-11-09 13:12:51 -08001458 isinstance(obj, types.MethodType) or
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001459 isinstance(obj, types.ModuleType)
1460 ):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001461 return {}
Guido van Rossum991d14f2016-11-09 13:12:51 -08001462 else:
1463 raise TypeError('{!r} is not a module, class, method, '
1464 'or function.'.format(obj))
1465 defaults = _get_defaults(obj)
1466 hints = dict(hints)
1467 for name, value in hints.items():
1468 if value is None:
1469 value = type(None)
1470 if isinstance(value, str):
1471 value = _ForwardRef(value)
1472 value = _eval_type(value, globalns, localns)
1473 if name in defaults and defaults[name] is None:
1474 value = Optional[value]
1475 hints[name] = value
1476 return hints
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001477
1478
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001479def no_type_check(arg):
1480 """Decorator to indicate that annotations are not type hints.
1481
1482 The argument must be a class or function; if it is a class, it
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001483 applies recursively to all methods and classes defined in that class
1484 (but not to methods defined in its superclasses or subclasses).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001485
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001486 This mutates the function(s) or class(es) in place.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001487 """
1488 if isinstance(arg, type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001489 arg_attrs = arg.__dict__.copy()
1490 for attr, val in arg.__dict__.items():
1491 if val in arg.__bases__:
1492 arg_attrs.pop(attr)
1493 for obj in arg_attrs.values():
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001494 if isinstance(obj, types.FunctionType):
1495 obj.__no_type_check__ = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001496 if isinstance(obj, type):
1497 no_type_check(obj)
1498 try:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001499 arg.__no_type_check__ = True
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001500 except TypeError: # built-in classes
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001501 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001502 return arg
1503
1504
1505def no_type_check_decorator(decorator):
1506 """Decorator to give another decorator the @no_type_check effect.
1507
1508 This wraps the decorator with something that wraps the decorated
1509 function in @no_type_check.
1510 """
1511
1512 @functools.wraps(decorator)
1513 def wrapped_decorator(*args, **kwds):
1514 func = decorator(*args, **kwds)
1515 func = no_type_check(func)
1516 return func
1517
1518 return wrapped_decorator
1519
1520
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001521def _overload_dummy(*args, **kwds):
1522 """Helper for @overload to raise when called."""
1523 raise NotImplementedError(
1524 "You should not call an overloaded function. "
1525 "A series of @overload-decorated functions "
1526 "outside a stub module should always be followed "
1527 "by an implementation that is not @overload-ed.")
1528
1529
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001530def overload(func):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001531 """Decorator for overloaded functions/methods.
1532
1533 In a stub file, place two or more stub definitions for the same
1534 function in a row, each decorated with @overload. For example:
1535
1536 @overload
1537 def utf8(value: None) -> None: ...
1538 @overload
1539 def utf8(value: bytes) -> bytes: ...
1540 @overload
1541 def utf8(value: str) -> bytes: ...
1542
1543 In a non-stub file (i.e. a regular .py file), do the same but
1544 follow it with an implementation. The implementation should *not*
1545 be decorated with @overload. For example:
1546
1547 @overload
1548 def utf8(value: None) -> None: ...
1549 @overload
1550 def utf8(value: bytes) -> bytes: ...
1551 @overload
1552 def utf8(value: str) -> bytes: ...
1553 def utf8(value):
1554 # implementation goes here
1555 """
1556 return _overload_dummy
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001557
1558
1559class _ProtocolMeta(GenericMeta):
1560 """Internal metaclass for _Protocol.
1561
1562 This exists so _Protocol classes can be generic without deriving
1563 from Generic.
1564 """
1565
Guido van Rossumd70fe632015-08-05 12:11:06 +02001566 def __instancecheck__(self, obj):
Guido van Rossumca4b2522016-11-19 10:32:41 -08001567 if _Protocol not in self.__bases__:
1568 return super().__instancecheck__(obj)
Guido van Rossumd70fe632015-08-05 12:11:06 +02001569 raise TypeError("Protocols cannot be used with isinstance().")
1570
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001571 def __subclasscheck__(self, cls):
1572 if not self._is_protocol:
1573 # No structural checks since this isn't a protocol.
1574 return NotImplemented
1575
1576 if self is _Protocol:
1577 # Every class is a subclass of the empty protocol.
1578 return True
1579
1580 # Find all attributes defined in the protocol.
1581 attrs = self._get_protocol_attrs()
1582
1583 for attr in attrs:
1584 if not any(attr in d.__dict__ for d in cls.__mro__):
1585 return False
1586 return True
1587
1588 def _get_protocol_attrs(self):
1589 # Get all Protocol base classes.
1590 protocol_bases = []
1591 for c in self.__mro__:
1592 if getattr(c, '_is_protocol', False) and c.__name__ != '_Protocol':
1593 protocol_bases.append(c)
1594
1595 # Get attributes included in protocol.
1596 attrs = set()
1597 for base in protocol_bases:
1598 for attr in base.__dict__.keys():
1599 # Include attributes not defined in any non-protocol bases.
1600 for c in self.__mro__:
1601 if (c is not base and attr in c.__dict__ and
1602 not getattr(c, '_is_protocol', False)):
1603 break
1604 else:
1605 if (not attr.startswith('_abc_') and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001606 attr != '__abstractmethods__' and
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001607 attr != '__annotations__' and
1608 attr != '__weakref__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001609 attr != '_is_protocol' and
1610 attr != '__dict__' and
1611 attr != '__args__' and
1612 attr != '__slots__' and
1613 attr != '_get_protocol_attrs' and
1614 attr != '__next_in_mro__' and
1615 attr != '__parameters__' and
1616 attr != '__origin__' and
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001617 attr != '__orig_bases__' and
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001618 attr != '__extra__' and
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001619 attr != '__tree_hash__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001620 attr != '__module__'):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001621 attrs.add(attr)
1622
1623 return attrs
1624
1625
1626class _Protocol(metaclass=_ProtocolMeta):
1627 """Internal base class for protocol classes.
1628
Guido van Rossumb24569a2016-11-20 18:01:29 -08001629 This implements a simple-minded structural issubclass check
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001630 (similar but more general than the one-offs in collections.abc
1631 such as Hashable).
1632 """
1633
Guido van Rossumd70fe632015-08-05 12:11:06 +02001634 __slots__ = ()
1635
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001636 _is_protocol = True
1637
1638
1639# Various ABCs mimicking those in collections.abc.
1640# A few are simply re-exported for completeness.
1641
1642Hashable = collections_abc.Hashable # Not generic.
1643
1644
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001645if hasattr(collections_abc, 'Awaitable'):
1646 class Awaitable(Generic[T_co], extra=collections_abc.Awaitable):
1647 __slots__ = ()
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001648
1649 __all__.append('Awaitable')
1650
1651
1652if hasattr(collections_abc, 'Coroutine'):
1653 class Coroutine(Awaitable[V_co], Generic[T_co, T_contra, V_co],
1654 extra=collections_abc.Coroutine):
1655 __slots__ = ()
1656
1657 __all__.append('Coroutine')
Guido van Rossumf17c2002015-12-03 17:31:24 -08001658
1659
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001660if hasattr(collections_abc, 'AsyncIterable'):
Guido van Rossumf17c2002015-12-03 17:31:24 -08001661
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001662 class AsyncIterable(Generic[T_co], extra=collections_abc.AsyncIterable):
1663 __slots__ = ()
Guido van Rossumf17c2002015-12-03 17:31:24 -08001664
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001665 class AsyncIterator(AsyncIterable[T_co],
1666 extra=collections_abc.AsyncIterator):
1667 __slots__ = ()
1668
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001669 __all__.append('AsyncIterable')
1670 __all__.append('AsyncIterator')
Guido van Rossumf17c2002015-12-03 17:31:24 -08001671
1672
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001673class Iterable(Generic[T_co], extra=collections_abc.Iterable):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001674 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001675
1676
1677class Iterator(Iterable[T_co], extra=collections_abc.Iterator):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001678 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001679
1680
1681class SupportsInt(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001682 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001683
1684 @abstractmethod
1685 def __int__(self) -> int:
1686 pass
1687
1688
1689class SupportsFloat(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001690 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001691
1692 @abstractmethod
1693 def __float__(self) -> float:
1694 pass
1695
1696
1697class SupportsComplex(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001698 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001699
1700 @abstractmethod
1701 def __complex__(self) -> complex:
1702 pass
1703
1704
1705class SupportsBytes(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001706 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001707
1708 @abstractmethod
1709 def __bytes__(self) -> bytes:
1710 pass
1711
1712
Guido van Rossumd70fe632015-08-05 12:11:06 +02001713class SupportsAbs(_Protocol[T_co]):
1714 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001715
1716 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001717 def __abs__(self) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001718 pass
1719
1720
Guido van Rossumd70fe632015-08-05 12:11:06 +02001721class SupportsRound(_Protocol[T_co]):
1722 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001723
1724 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001725 def __round__(self, ndigits: int = 0) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001726 pass
1727
1728
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001729if hasattr(collections_abc, 'Reversible'):
1730 class Reversible(Iterable[T_co], extra=collections_abc.Reversible):
1731 __slots__ = ()
1732else:
1733 class Reversible(_Protocol[T_co]):
1734 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001735
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001736 @abstractmethod
1737 def __reversed__(self) -> 'Iterator[T_co]':
1738 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001739
1740
1741Sized = collections_abc.Sized # Not generic.
1742
1743
1744class Container(Generic[T_co], extra=collections_abc.Container):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001745 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001746
1747
Guido van Rossumefa798d2016-08-23 11:01:50 -07001748if hasattr(collections_abc, 'Collection'):
1749 class Collection(Sized, Iterable[T_co], Container[T_co],
1750 extra=collections_abc.Collection):
1751 __slots__ = ()
1752
1753 __all__.append('Collection')
1754
1755
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001756# Callable was defined earlier.
1757
Guido van Rossumefa798d2016-08-23 11:01:50 -07001758if hasattr(collections_abc, 'Collection'):
1759 class AbstractSet(Collection[T_co],
1760 extra=collections_abc.Set):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001761 __slots__ = ()
Guido van Rossumefa798d2016-08-23 11:01:50 -07001762else:
1763 class AbstractSet(Sized, Iterable[T_co], Container[T_co],
1764 extra=collections_abc.Set):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001765 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001766
1767
1768class MutableSet(AbstractSet[T], extra=collections_abc.MutableSet):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001769 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001770
1771
Guido van Rossumefa798d2016-08-23 11:01:50 -07001772# NOTE: It is only covariant in the value type.
1773if hasattr(collections_abc, 'Collection'):
1774 class Mapping(Collection[KT], Generic[KT, VT_co],
1775 extra=collections_abc.Mapping):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001776 __slots__ = ()
Guido van Rossumefa798d2016-08-23 11:01:50 -07001777else:
1778 class Mapping(Sized, Iterable[KT], Container[KT], Generic[KT, VT_co],
1779 extra=collections_abc.Mapping):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001780 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001781
1782
1783class MutableMapping(Mapping[KT, VT], extra=collections_abc.MutableMapping):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001784 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001785
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001786
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001787if hasattr(collections_abc, 'Reversible'):
Guido van Rossumefa798d2016-08-23 11:01:50 -07001788 if hasattr(collections_abc, 'Collection'):
1789 class Sequence(Reversible[T_co], Collection[T_co],
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001790 extra=collections_abc.Sequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001791 __slots__ = ()
Guido van Rossumefa798d2016-08-23 11:01:50 -07001792 else:
1793 class Sequence(Sized, Reversible[T_co], Container[T_co],
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001794 extra=collections_abc.Sequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001795 __slots__ = ()
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001796else:
1797 class Sequence(Sized, Iterable[T_co], Container[T_co],
1798 extra=collections_abc.Sequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001799 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001800
1801
1802class MutableSequence(Sequence[T], extra=collections_abc.MutableSequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001803 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001804
1805
1806class ByteString(Sequence[int], extra=collections_abc.ByteString):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001807 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001808
1809
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001810class List(list, MutableSequence[T], extra=list):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001811
Guido van Rossum4cefe742016-09-27 15:20:12 -07001812 __slots__ = ()
1813
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001814 def __new__(cls, *args, **kwds):
1815 if _geqv(cls, List):
1816 raise TypeError("Type List cannot be instantiated; "
1817 "use list() instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001818 return _generic_new(list, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001819
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001820
Raymond Hettinger80490522017-01-16 22:42:37 -08001821class Deque(collections.deque, MutableSequence[T], extra=collections.deque):
1822
1823 __slots__ = ()
1824
1825 def __new__(cls, *args, **kwds):
1826 if _geqv(cls, Deque):
1827 raise TypeError("Type Deque cannot be instantiated; "
1828 "use deque() instead")
1829 return _generic_new(collections.deque, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001830
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001831
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001832class Set(set, MutableSet[T], extra=set):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001833
Guido van Rossum4cefe742016-09-27 15:20:12 -07001834 __slots__ = ()
1835
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001836 def __new__(cls, *args, **kwds):
1837 if _geqv(cls, Set):
1838 raise TypeError("Type Set cannot be instantiated; "
1839 "use set() instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001840 return _generic_new(set, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001841
1842
Guido van Rossum4cefe742016-09-27 15:20:12 -07001843class FrozenSet(frozenset, AbstractSet[T_co], extra=frozenset):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001844 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001845
1846 def __new__(cls, *args, **kwds):
1847 if _geqv(cls, FrozenSet):
1848 raise TypeError("Type FrozenSet cannot be instantiated; "
1849 "use frozenset() instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001850 return _generic_new(frozenset, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001851
1852
1853class MappingView(Sized, Iterable[T_co], extra=collections_abc.MappingView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001854 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001855
1856
Guido van Rossumd70fe632015-08-05 12:11:06 +02001857class KeysView(MappingView[KT], AbstractSet[KT],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001858 extra=collections_abc.KeysView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001859 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001860
1861
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001862class ItemsView(MappingView[Tuple[KT, VT_co]],
Guido van Rossum0e0563c2016-04-05 14:54:25 -07001863 AbstractSet[Tuple[KT, VT_co]],
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001864 Generic[KT, VT_co],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001865 extra=collections_abc.ItemsView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001866 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001867
1868
1869class ValuesView(MappingView[VT_co], extra=collections_abc.ValuesView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001870 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001871
1872
Brett Cannonf3ad0422016-04-15 10:51:30 -07001873if hasattr(contextlib, 'AbstractContextManager'):
1874 class ContextManager(Generic[T_co], extra=contextlib.AbstractContextManager):
1875 __slots__ = ()
1876 __all__.append('ContextManager')
1877
1878
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001879class Dict(dict, MutableMapping[KT, VT], extra=dict):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001880
Guido van Rossum4cefe742016-09-27 15:20:12 -07001881 __slots__ = ()
1882
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001883 def __new__(cls, *args, **kwds):
1884 if _geqv(cls, Dict):
1885 raise TypeError("Type Dict cannot be instantiated; "
1886 "use dict() instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001887 return _generic_new(dict, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001888
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001889
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001890class DefaultDict(collections.defaultdict, MutableMapping[KT, VT],
1891 extra=collections.defaultdict):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001892
Guido van Rossum4cefe742016-09-27 15:20:12 -07001893 __slots__ = ()
1894
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001895 def __new__(cls, *args, **kwds):
1896 if _geqv(cls, DefaultDict):
1897 raise TypeError("Type DefaultDict cannot be instantiated; "
1898 "use collections.defaultdict() instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001899 return _generic_new(collections.defaultdict, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001900
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001901
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001902# Determine what base class to use for Generator.
1903if hasattr(collections_abc, 'Generator'):
1904 # Sufficiently recent versions of 3.5 have a Generator ABC.
1905 _G_base = collections_abc.Generator
1906else:
1907 # Fall back on the exact type.
1908 _G_base = types.GeneratorType
1909
1910
1911class Generator(Iterator[T_co], Generic[T_co, T_contra, V_co],
1912 extra=_G_base):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001913 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001914
1915 def __new__(cls, *args, **kwds):
1916 if _geqv(cls, Generator):
1917 raise TypeError("Type Generator cannot be instantiated; "
1918 "create a subclass instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001919 return _generic_new(_G_base, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001920
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001921
Guido van Rossume9ed5602017-01-18 13:10:31 -08001922if hasattr(collections_abc, 'AsyncGenerator'):
1923 class AsyncGenerator(AsyncIterator[T_co], Generic[T_co, T_contra],
1924 extra=collections_abc.AsyncGenerator):
1925 __slots__ = ()
1926
1927 __all__.append('AsyncGenerator')
1928
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001929
Guido van Rossumeb9aca32016-05-24 16:38:22 -07001930# Internal type variable used for Type[].
Guido van Rossumefa798d2016-08-23 11:01:50 -07001931CT_co = TypeVar('CT_co', covariant=True, bound=type)
Guido van Rossumeb9aca32016-05-24 16:38:22 -07001932
1933
Guido van Rossumb22c7082016-05-26 09:56:19 -07001934# This is not a real generic class. Don't use outside annotations.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001935class Type(Generic[CT_co], extra=type):
Guido van Rossumb22c7082016-05-26 09:56:19 -07001936 """A special construct usable to annotate class objects.
Guido van Rossumeb9aca32016-05-24 16:38:22 -07001937
1938 For example, suppose we have the following classes::
1939
1940 class User: ... # Abstract base for User classes
1941 class BasicUser(User): ...
1942 class ProUser(User): ...
1943 class TeamUser(User): ...
1944
1945 And a function that takes a class argument that's a subclass of
1946 User and returns an instance of the corresponding class::
1947
1948 U = TypeVar('U', bound=User)
1949 def new_user(user_class: Type[U]) -> U:
1950 user = user_class()
1951 # (Here we could write the user object to a database)
1952 return user
1953
1954 joe = new_user(BasicUser)
1955
1956 At this point the type checker knows that joe has type BasicUser.
1957 """
1958
Guido van Rossum4cefe742016-09-27 15:20:12 -07001959 __slots__ = ()
1960
Guido van Rossumeb9aca32016-05-24 16:38:22 -07001961
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001962def _make_nmtuple(name, types):
Guido van Rossum2f841442016-11-15 09:48:06 -08001963 msg = "NamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a type"
1964 types = [(n, _type_check(t, msg)) for n, t in types]
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001965 nm_tpl = collections.namedtuple(name, [n for n, t in types])
Guido van Rossum83ec3022017-01-17 20:43:28 -08001966 # Prior to PEP 526, only _field_types attribute was assigned.
1967 # Now, both __annotations__ and _field_types are used to maintain compatibility.
1968 nm_tpl.__annotations__ = nm_tpl._field_types = collections.OrderedDict(types)
Guido van Rossum557d1eb2015-11-19 08:16:31 -08001969 try:
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001970 nm_tpl.__module__ = sys._getframe(2).f_globals.get('__name__', '__main__')
Guido van Rossum557d1eb2015-11-19 08:16:31 -08001971 except (AttributeError, ValueError):
1972 pass
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001973 return nm_tpl
1974
1975
Guido van Rossum2f841442016-11-15 09:48:06 -08001976_PY36 = sys.version_info[:2] >= (3, 6)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001977
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001978
Guido van Rossum2f841442016-11-15 09:48:06 -08001979class NamedTupleMeta(type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001980
Guido van Rossum2f841442016-11-15 09:48:06 -08001981 def __new__(cls, typename, bases, ns):
1982 if ns.get('_root', False):
1983 return super().__new__(cls, typename, bases, ns)
1984 if not _PY36:
1985 raise TypeError("Class syntax for NamedTuple is only supported"
1986 " in Python 3.6+")
1987 types = ns.get('__annotations__', {})
Guido van Rossum3c268be2017-01-18 08:03:50 -08001988 nm_tpl = _make_nmtuple(typename, types.items())
1989 defaults = []
1990 defaults_dict = {}
1991 for field_name in types:
1992 if field_name in ns:
1993 default_value = ns[field_name]
1994 defaults.append(default_value)
1995 defaults_dict[field_name] = default_value
1996 elif defaults:
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001997 raise TypeError("Non-default namedtuple field {field_name} cannot "
1998 "follow default field(s) {default_names}"
Guido van Rossum3c268be2017-01-18 08:03:50 -08001999 .format(field_name=field_name,
2000 default_names=', '.join(defaults_dict.keys())))
2001 nm_tpl.__new__.__defaults__ = tuple(defaults)
2002 nm_tpl._field_defaults = defaults_dict
Guido van Rossum95919c02017-01-22 17:47:20 -08002003 # update from user namespace without overriding special namedtuple attributes
2004 for key in ns:
2005 if not hasattr(nm_tpl, key):
2006 setattr(nm_tpl, key, ns[key])
Guido van Rossum3c268be2017-01-18 08:03:50 -08002007 return nm_tpl
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002008
Guido van Rossumd7adfe12017-01-22 17:43:53 -08002009
Guido van Rossum2f841442016-11-15 09:48:06 -08002010class NamedTuple(metaclass=NamedTupleMeta):
2011 """Typed version of namedtuple.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002012
Guido van Rossum2f841442016-11-15 09:48:06 -08002013 Usage in Python versions >= 3.6::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002014
Guido van Rossum2f841442016-11-15 09:48:06 -08002015 class Employee(NamedTuple):
2016 name: str
2017 id: int
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002018
Guido van Rossum2f841442016-11-15 09:48:06 -08002019 This is equivalent to::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002020
Guido van Rossum2f841442016-11-15 09:48:06 -08002021 Employee = collections.namedtuple('Employee', ['name', 'id'])
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002022
Guido van Rossum83ec3022017-01-17 20:43:28 -08002023 The resulting class has extra __annotations__ and _field_types
2024 attributes, giving an ordered dict mapping field names to types.
2025 __annotations__ should be preferred, while _field_types
2026 is kept to maintain pre PEP 526 compatibility. (The field names
Guido van Rossum2f841442016-11-15 09:48:06 -08002027 are in the _fields attribute, which is part of the namedtuple
2028 API.) Alternative equivalent keyword syntax is also accepted::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002029
Guido van Rossum2f841442016-11-15 09:48:06 -08002030 Employee = NamedTuple('Employee', name=str, id=int)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002031
Guido van Rossum2f841442016-11-15 09:48:06 -08002032 In Python versions <= 3.5 use::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002033
Guido van Rossum2f841442016-11-15 09:48:06 -08002034 Employee = NamedTuple('Employee', [('name', str), ('id', int)])
2035 """
2036 _root = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002037
Guido van Rossum2f841442016-11-15 09:48:06 -08002038 def __new__(self, typename, fields=None, **kwargs):
2039 if kwargs and not _PY36:
2040 raise TypeError("Keyword syntax for NamedTuple is only supported"
2041 " in Python 3.6+")
2042 if fields is None:
2043 fields = kwargs.items()
2044 elif kwargs:
2045 raise TypeError("Either list of fields or keywords"
2046 " can be provided to NamedTuple, not both")
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002047 return _make_nmtuple(typename, fields)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002048
2049
Guido van Rossum91185fe2016-06-08 11:19:11 -07002050def NewType(name, tp):
2051 """NewType creates simple unique types with almost zero
2052 runtime overhead. NewType(name, tp) is considered a subtype of tp
2053 by static type checkers. At runtime, NewType(name, tp) returns
2054 a dummy function that simply returns its argument. Usage::
2055
2056 UserId = NewType('UserId', int)
2057
2058 def name_by_id(user_id: UserId) -> str:
2059 ...
2060
2061 UserId('user') # Fails type check
2062
2063 name_by_id(42) # Fails type check
2064 name_by_id(UserId(42)) # OK
2065
2066 num = UserId(5) + 1 # type: int
2067 """
2068
2069 def new_type(x):
2070 return x
2071
2072 new_type.__name__ = name
2073 new_type.__supertype__ = tp
2074 return new_type
2075
2076
Guido van Rossum0e0563c2016-04-05 14:54:25 -07002077# Python-version-specific alias (Python 2: unicode; Python 3: str)
2078Text = str
2079
2080
Guido van Rossum91185fe2016-06-08 11:19:11 -07002081# Constant that's True when type checking, but False here.
2082TYPE_CHECKING = False
2083
2084
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002085class IO(Generic[AnyStr]):
2086 """Generic base class for TextIO and BinaryIO.
2087
2088 This is an abstract, generic version of the return of open().
2089
2090 NOTE: This does not distinguish between the different possible
2091 classes (text vs. binary, read vs. write vs. read/write,
2092 append-only, unbuffered). The TextIO and BinaryIO subclasses
2093 below capture the distinctions between text vs. binary, which is
2094 pervasive in the interface; however we currently do not offer a
2095 way to track the other distinctions in the type system.
2096 """
2097
Guido van Rossumd70fe632015-08-05 12:11:06 +02002098 __slots__ = ()
2099
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002100 @abstractproperty
2101 def mode(self) -> str:
2102 pass
2103
2104 @abstractproperty
2105 def name(self) -> str:
2106 pass
2107
2108 @abstractmethod
2109 def close(self) -> None:
2110 pass
2111
2112 @abstractmethod
2113 def closed(self) -> bool:
2114 pass
2115
2116 @abstractmethod
2117 def fileno(self) -> int:
2118 pass
2119
2120 @abstractmethod
2121 def flush(self) -> None:
2122 pass
2123
2124 @abstractmethod
2125 def isatty(self) -> bool:
2126 pass
2127
2128 @abstractmethod
2129 def read(self, n: int = -1) -> AnyStr:
2130 pass
2131
2132 @abstractmethod
2133 def readable(self) -> bool:
2134 pass
2135
2136 @abstractmethod
2137 def readline(self, limit: int = -1) -> AnyStr:
2138 pass
2139
2140 @abstractmethod
2141 def readlines(self, hint: int = -1) -> List[AnyStr]:
2142 pass
2143
2144 @abstractmethod
2145 def seek(self, offset: int, whence: int = 0) -> int:
2146 pass
2147
2148 @abstractmethod
2149 def seekable(self) -> bool:
2150 pass
2151
2152 @abstractmethod
2153 def tell(self) -> int:
2154 pass
2155
2156 @abstractmethod
2157 def truncate(self, size: int = None) -> int:
2158 pass
2159
2160 @abstractmethod
2161 def writable(self) -> bool:
2162 pass
2163
2164 @abstractmethod
2165 def write(self, s: AnyStr) -> int:
2166 pass
2167
2168 @abstractmethod
2169 def writelines(self, lines: List[AnyStr]) -> None:
2170 pass
2171
2172 @abstractmethod
2173 def __enter__(self) -> 'IO[AnyStr]':
2174 pass
2175
2176 @abstractmethod
2177 def __exit__(self, type, value, traceback) -> None:
2178 pass
2179
2180
2181class BinaryIO(IO[bytes]):
2182 """Typed version of the return of open() in binary mode."""
2183
Guido van Rossumd70fe632015-08-05 12:11:06 +02002184 __slots__ = ()
2185
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002186 @abstractmethod
2187 def write(self, s: Union[bytes, bytearray]) -> int:
2188 pass
2189
2190 @abstractmethod
2191 def __enter__(self) -> 'BinaryIO':
2192 pass
2193
2194
2195class TextIO(IO[str]):
2196 """Typed version of the return of open() in text mode."""
2197
Guido van Rossumd70fe632015-08-05 12:11:06 +02002198 __slots__ = ()
2199
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002200 @abstractproperty
2201 def buffer(self) -> BinaryIO:
2202 pass
2203
2204 @abstractproperty
2205 def encoding(self) -> str:
2206 pass
2207
2208 @abstractproperty
Guido van Rossum991d14f2016-11-09 13:12:51 -08002209 def errors(self) -> Optional[str]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002210 pass
2211
2212 @abstractproperty
2213 def line_buffering(self) -> bool:
2214 pass
2215
2216 @abstractproperty
2217 def newlines(self) -> Any:
2218 pass
2219
2220 @abstractmethod
2221 def __enter__(self) -> 'TextIO':
2222 pass
2223
2224
2225class io:
2226 """Wrapper namespace for IO generic classes."""
2227
2228 __all__ = ['IO', 'TextIO', 'BinaryIO']
2229 IO = IO
2230 TextIO = TextIO
2231 BinaryIO = BinaryIO
2232
Guido van Rossumd7adfe12017-01-22 17:43:53 -08002233
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002234io.__name__ = __name__ + '.io'
2235sys.modules[io.__name__] = io
2236
2237
2238Pattern = _TypeAlias('Pattern', AnyStr, type(stdlib_re.compile('')),
2239 lambda p: p.pattern)
2240Match = _TypeAlias('Match', AnyStr, type(stdlib_re.match('', '')),
2241 lambda m: m.re.pattern)
2242
2243
2244class re:
2245 """Wrapper namespace for re type aliases."""
2246
2247 __all__ = ['Pattern', 'Match']
2248 Pattern = Pattern
2249 Match = Match
2250
Guido van Rossumd7adfe12017-01-22 17:43:53 -08002251
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002252re.__name__ = __name__ + '.re'
2253sys.modules[re.__name__] = re