blob: 00ef440101fa5477e8c9fb5a9172ec61f90125c1 [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):
100 if nm.startswith('_') and nm not in ('_TypeAlias',
101 '_ForwardRef', '_TypingBase', '_FinalTypingBase'):
102 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 Rossum5fc25a82016-10-29 08:54:56 -0700358 if (isinstance(arg, _TypingBase) and type(arg).__name__ == '_ClassVar' or
359 not isinstance(arg, (type, _TypingBase)) and not callable(arg)):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700360 raise TypeError(msg + " Got %.100r." % (arg,))
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700361 # Bare Union etc. are not valid as type arguments
362 if (type(arg).__name__ in ('_Union', '_Optional')
363 and not getattr(arg, '__origin__', None)
364 or isinstance(arg, TypingMeta) and _gorg(arg) in (Generic, _Protocol)):
365 raise TypeError("Plain %s is not valid as type argument" % arg)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700366 return arg
367
368
369def _type_repr(obj):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800370 """Return the repr() of an object, special-casing types (internal helper).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700371
372 If obj is a type, we return a shorter version than the default
373 type.__repr__, based on the module and qualified name, which is
374 typically enough to uniquely identify a type. For everything
375 else, we fall back on repr(obj).
376 """
377 if isinstance(obj, type) and not isinstance(obj, TypingMeta):
378 if obj.__module__ == 'builtins':
379 return _qualname(obj)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700380 return '%s.%s' % (obj.__module__, _qualname(obj))
381 if obj is ...:
382 return('...')
383 if isinstance(obj, types.FunctionType):
384 return obj.__name__
385 return repr(obj)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700386
387
Guido van Rossum4cefe742016-09-27 15:20:12 -0700388class _Any(_FinalTypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700389 """Special type indicating an unconstrained type.
390
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700391 - Any is compatible with every type.
392 - Any assumed to have all methods.
393 - All values assumed to be instances of Any.
394
395 Note that all the above statements are true from the point of view of
396 static type checkers. At runtime, Any should not be used with instance
397 or class checks.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700398 """
399
Guido van Rossumd70fe632015-08-05 12:11:06 +0200400 __slots__ = ()
401
Guido van Rossum4cefe742016-09-27 15:20:12 -0700402 def __instancecheck__(self, obj):
403 raise TypeError("Any cannot be used with isinstance().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700404
Guido van Rossum4cefe742016-09-27 15:20:12 -0700405 def __subclasscheck__(self, cls):
406 raise TypeError("Any cannot be used with issubclass().")
407
408
409Any = _Any(_root=True)
410
411
412class TypeVar(_TypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700413 """Type variable.
414
415 Usage::
416
417 T = TypeVar('T') # Can be anything
418 A = TypeVar('A', str, bytes) # Must be str or bytes
419
420 Type variables exist primarily for the benefit of static type
421 checkers. They serve as the parameters for generic types as well
422 as for generic function definitions. See class Generic for more
423 information on generic types. Generic functions work as follows:
424
Guido van Rossumb24569a2016-11-20 18:01:29 -0800425 def repeat(x: T, n: int) -> List[T]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700426 '''Return a list containing n references to x.'''
427 return [x]*n
428
429 def longest(x: A, y: A) -> A:
430 '''Return the longest of two strings.'''
431 return x if len(x) >= len(y) else y
432
433 The latter example's signature is essentially the overloading
434 of (str, str) -> str and (bytes, bytes) -> bytes. Also note
435 that if the arguments are instances of some subclass of str,
436 the return type is still plain str.
437
Guido van Rossumb24569a2016-11-20 18:01:29 -0800438 At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700439
Guido van Rossumefa798d2016-08-23 11:01:50 -0700440 Type variables defined with covariant=True or contravariant=True
441 can be used do declare covariant or contravariant generic types.
442 See PEP 484 for more details. By default generic types are invariant
443 in all type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700444
445 Type variables can be introspected. e.g.:
446
447 T.__name__ == 'T'
448 T.__constraints__ == ()
449 T.__covariant__ == False
450 T.__contravariant__ = False
451 A.__constraints__ == (str, bytes)
452 """
453
Guido van Rossum4cefe742016-09-27 15:20:12 -0700454 __slots__ = ('__name__', '__bound__', '__constraints__',
455 '__covariant__', '__contravariant__')
456
457 def __init__(self, name, *constraints, bound=None,
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700458 covariant=False, contravariant=False):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700459 super().__init__(name, *constraints, bound=bound,
460 covariant=covariant, contravariant=contravariant)
461 self.__name__ = name
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700462 if covariant and contravariant:
Guido van Rossumefa798d2016-08-23 11:01:50 -0700463 raise ValueError("Bivariant types are not supported.")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700464 self.__covariant__ = bool(covariant)
465 self.__contravariant__ = bool(contravariant)
466 if constraints and bound is not None:
467 raise TypeError("Constraints cannot be combined with bound=...")
468 if constraints and len(constraints) == 1:
469 raise TypeError("A single constraint is not allowed")
470 msg = "TypeVar(name, constraint, ...): constraints must be types."
471 self.__constraints__ = tuple(_type_check(t, msg) for t in constraints)
472 if bound:
473 self.__bound__ = _type_check(bound, "Bound must be a type.")
474 else:
475 self.__bound__ = None
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700476
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700477 def _get_type_vars(self, tvars):
478 if self not in tvars:
479 tvars.append(self)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700480
481 def __repr__(self):
482 if self.__covariant__:
483 prefix = '+'
484 elif self.__contravariant__:
485 prefix = '-'
486 else:
487 prefix = '~'
488 return prefix + self.__name__
489
490 def __instancecheck__(self, instance):
491 raise TypeError("Type variables cannot be used with isinstance().")
492
493 def __subclasscheck__(self, cls):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700494 raise TypeError("Type variables cannot be used with issubclass().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700495
496
497# Some unconstrained type variables. These are used by the container types.
Guido van Rossumeb9aca32016-05-24 16:38:22 -0700498# (These are not for export.)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700499T = TypeVar('T') # Any type.
500KT = TypeVar('KT') # Key type.
501VT = TypeVar('VT') # Value type.
502T_co = TypeVar('T_co', covariant=True) # Any type covariant containers.
503V_co = TypeVar('V_co', covariant=True) # Any type covariant containers.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700504VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
505T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
506
507# A useful type variable with constraints. This represents string types.
Guido van Rossumeb9aca32016-05-24 16:38:22 -0700508# (This one *is* for export!)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700509AnyStr = TypeVar('AnyStr', bytes, str)
510
511
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700512def _replace_arg(arg, tvars, args):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800513 """An internal helper function: replace arg if it is a type variable
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700514 found in tvars with corresponding substitution from args or
515 with corresponding substitution sub-tree if arg is a generic type.
516 """
517
518 if tvars is None:
519 tvars = []
Guido van Rossum83ec3022017-01-17 20:43:28 -0800520 if hasattr(arg, '_subs_tree') and isinstance(arg, (GenericMeta, _TypingBase)):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700521 return arg._subs_tree(tvars, args)
522 if isinstance(arg, TypeVar):
523 for i, tvar in enumerate(tvars):
524 if arg == tvar:
525 return args[i]
526 return arg
527
528
Guido van Rossum83ec3022017-01-17 20:43:28 -0800529# Special typing constructs Union, Optional, Generic, Callable and Tuple
530# use three special attributes for internal bookkeeping of generic types:
531# * __parameters__ is a tuple of unique free type parameters of a generic
532# type, for example, Dict[T, T].__parameters__ == (T,);
533# * __origin__ keeps a reference to a type that was subscripted,
534# e.g., Union[T, int].__origin__ == Union;
535# * __args__ is a tuple of all arguments used in subscripting,
536# e.g., Dict[T, int].__args__ == (T, int).
537
538
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700539def _subs_tree(cls, tvars=None, args=None):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800540 """An internal helper function: calculate substitution tree
541 for generic cls after replacing its type parameters with
542 substitutions in tvars -> args (if any).
543 Repeat the same following __origin__'s.
544
545 Return a list of arguments with all possible substitutions
546 performed. Arguments that are generic classes themselves are represented
547 as tuples (so that no new classes are created by this function).
548 For example: _subs_tree(List[Tuple[int, T]][str]) == [(Tuple, int, str)]
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700549 """
550
551 if cls.__origin__ is None:
552 return cls
553 # Make of chain of origins (i.e. cls -> cls.__origin__)
554 current = cls.__origin__
555 orig_chain = []
556 while current.__origin__ is not None:
557 orig_chain.append(current)
558 current = current.__origin__
559 # Replace type variables in __args__ if asked ...
560 tree_args = []
561 for arg in cls.__args__:
562 tree_args.append(_replace_arg(arg, tvars, args))
563 # ... then continue replacing down the origin chain.
564 for ocls in orig_chain:
565 new_tree_args = []
566 for i, arg in enumerate(ocls.__args__):
567 new_tree_args.append(_replace_arg(arg, ocls.__parameters__, tree_args))
568 tree_args = new_tree_args
569 return tree_args
570
571
572def _remove_dups_flatten(parameters):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800573 """An internal helper for Union creation and substitution: flatten Union's
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700574 among parameters, then remove duplicates and strict subclasses.
575 """
576
577 # Flatten out Union[Union[...], ...].
578 params = []
579 for p in parameters:
580 if isinstance(p, _Union) and p.__origin__ is Union:
581 params.extend(p.__args__)
582 elif isinstance(p, tuple) and len(p) > 0 and p[0] is Union:
583 params.extend(p[1:])
584 else:
585 params.append(p)
586 # Weed out strict duplicates, preserving the first of each occurrence.
587 all_params = set(params)
588 if len(all_params) < len(params):
589 new_params = []
590 for t in params:
591 if t in all_params:
592 new_params.append(t)
593 all_params.remove(t)
594 params = new_params
595 assert not all_params, all_params
596 # Weed out subclasses.
597 # E.g. Union[int, Employee, Manager] == Union[int, Employee].
598 # If object is present it will be sole survivor among proper classes.
599 # Never discard type variables.
600 # (In particular, Union[str, AnyStr] != AnyStr.)
601 all_params = set(params)
602 for t1 in params:
603 if not isinstance(t1, type):
604 continue
605 if any(isinstance(t2, type) and issubclass(t1, t2)
606 for t2 in all_params - {t1}
607 if not (isinstance(t2, GenericMeta) and
608 t2.__origin__ is not None)):
609 all_params.remove(t1)
610 return tuple(t for t in params if t in all_params)
611
612
613def _check_generic(cls, parameters):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800614 # Check correct count for parameters of a generic cls (internal helper).
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700615 if not cls.__parameters__:
616 raise TypeError("%s is not a generic class" % repr(cls))
617 alen = len(parameters)
618 elen = len(cls.__parameters__)
619 if alen != elen:
620 raise TypeError("Too %s parameters for %s; actual %s, expected %s" %
621 ("many" if alen > elen else "few", repr(cls), alen, elen))
622
623
Guido van Rossum9b107562016-11-09 13:23:04 -0800624_cleanups = []
625
626
Guido van Rossum4cefe742016-09-27 15:20:12 -0700627def _tp_cache(func):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800628 """Internal wrapper caching __getitem__ of generic types with a fallback to
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700629 original function for non-hashable arguments.
630 """
631
Guido van Rossum4cefe742016-09-27 15:20:12 -0700632 cached = functools.lru_cache()(func)
Guido van Rossum9b107562016-11-09 13:23:04 -0800633 _cleanups.append(cached.cache_clear)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700634 @functools.wraps(func)
635 def inner(*args, **kwds):
636 try:
637 return cached(*args, **kwds)
638 except TypeError:
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700639 pass # All real errors (not unhashable args) are raised below.
Guido van Rossum4cefe742016-09-27 15:20:12 -0700640 return func(*args, **kwds)
641 return inner
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700642
643
Guido van Rossum4cefe742016-09-27 15:20:12 -0700644class _Union(_FinalTypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700645 """Union type; Union[X, Y] means either X or Y.
646
647 To define a union, use e.g. Union[int, str]. Details:
648
649 - The arguments must be types and there must be at least one.
650
651 - None as an argument is a special case and is replaced by
652 type(None).
653
654 - Unions of unions are flattened, e.g.::
655
656 Union[Union[int, str], float] == Union[int, str, float]
657
658 - Unions of a single argument vanish, e.g.::
659
660 Union[int] == int # The constructor actually returns int
661
662 - Redundant arguments are skipped, e.g.::
663
664 Union[int, str, int] == Union[int, str]
665
666 - When comparing unions, the argument order is ignored, e.g.::
667
668 Union[int, str] == Union[str, int]
669
670 - When two arguments have a subclass relationship, the least
671 derived argument is kept, e.g.::
672
673 class Employee: pass
674 class Manager(Employee): pass
675 Union[int, Employee, Manager] == Union[int, Employee]
676 Union[Manager, int, Employee] == Union[int, Employee]
677 Union[Employee, Manager] == Employee
678
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700679 - Similar for object::
680
681 Union[int, object] == object
682
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700683 - You cannot subclass or instantiate a union.
684
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700685 - You can use Optional[X] as a shorthand for Union[X, None].
686 """
687
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700688 __slots__ = ('__parameters__', '__args__', '__origin__', '__tree_hash__')
Guido van Rossum4cefe742016-09-27 15:20:12 -0700689
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700690 def __new__(cls, parameters=None, origin=None, *args, _root=False):
691 self = super().__new__(cls, parameters, origin, *args, _root=_root)
692 if origin is None:
693 self.__parameters__ = None
694 self.__args__ = None
695 self.__origin__ = None
696 self.__tree_hash__ = hash(frozenset(('Union',)))
Guido van Rossum4cefe742016-09-27 15:20:12 -0700697 return self
698 if not isinstance(parameters, tuple):
699 raise TypeError("Expected parameters=<tuple>")
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700700 if origin is Union:
701 parameters = _remove_dups_flatten(parameters)
702 # It's not a union if there's only one type left.
703 if len(parameters) == 1:
704 return parameters[0]
705 self.__parameters__ = _type_vars(parameters)
706 self.__args__ = parameters
707 self.__origin__ = origin
708 # Pre-calculate the __hash__ on instantiation.
709 # This improves speed for complex substitutions.
710 subs_tree = self._subs_tree()
711 if isinstance(subs_tree, tuple):
712 self.__tree_hash__ = hash(frozenset(subs_tree))
713 else:
714 self.__tree_hash__ = hash(subs_tree)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700715 return self
716
717 def _eval_type(self, globalns, localns):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700718 if self.__args__ is None:
Guido van Rossum4cefe742016-09-27 15:20:12 -0700719 return self
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700720 ev_args = tuple(_eval_type(t, globalns, localns) for t in self.__args__)
721 ev_origin = _eval_type(self.__origin__, globalns, localns)
722 if ev_args == self.__args__ and ev_origin == self.__origin__:
723 # Everything is already evaluated.
724 return self
725 return self.__class__(ev_args, ev_origin, _root=True)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700726
727 def _get_type_vars(self, tvars):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700728 if self.__origin__ and self.__parameters__:
729 _get_type_vars(self.__parameters__, tvars)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700730
731 def __repr__(self):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700732 if self.__origin__ is None:
733 return super().__repr__()
734 tree = self._subs_tree()
735 if not isinstance(tree, tuple):
736 return repr(tree)
737 return tree[0]._tree_repr(tree)
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700738
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700739 def _tree_repr(self, tree):
740 arg_list = []
741 for arg in tree[1:]:
742 if not isinstance(arg, tuple):
743 arg_list.append(_type_repr(arg))
744 else:
745 arg_list.append(arg[0]._tree_repr(arg))
746 return super().__repr__() + '[%s]' % ', '.join(arg_list)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700747
748 @_tp_cache
749 def __getitem__(self, parameters):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700750 if parameters == ():
751 raise TypeError("Cannot take a Union of no types.")
752 if not isinstance(parameters, tuple):
753 parameters = (parameters,)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700754 if self.__origin__ is None:
755 msg = "Union[arg, ...]: each arg must be a type."
756 else:
757 msg = "Parameters to generic types must be types."
758 parameters = tuple(_type_check(p, msg) for p in parameters)
759 if self is not Union:
760 _check_generic(self, parameters)
761 return self.__class__(parameters, origin=self, _root=True)
762
763 def _subs_tree(self, tvars=None, args=None):
764 if self is Union:
765 return Union # Nothing to substitute
766 tree_args = _subs_tree(self, tvars, args)
767 tree_args = _remove_dups_flatten(tree_args)
768 if len(tree_args) == 1:
769 return tree_args[0] # Union of a single type is that type
770 return (Union,) + tree_args
Guido van Rossum4cefe742016-09-27 15:20:12 -0700771
772 def __eq__(self, other):
Guido van Rossum83ec3022017-01-17 20:43:28 -0800773 if isinstance(other, _Union):
774 return self.__tree_hash__ == other.__tree_hash__
775 elif self is not Union:
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700776 return self._subs_tree() == other
Guido van Rossum83ec3022017-01-17 20:43:28 -0800777 else:
778 return self is other
Guido van Rossum4cefe742016-09-27 15:20:12 -0700779
780 def __hash__(self):
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700781 return self.__tree_hash__
Guido van Rossum4cefe742016-09-27 15:20:12 -0700782
783 def __instancecheck__(self, obj):
784 raise TypeError("Unions cannot be used with isinstance().")
785
786 def __subclasscheck__(self, cls):
787 raise TypeError("Unions cannot be used with issubclass().")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700788
789
Guido van Rossum4cefe742016-09-27 15:20:12 -0700790Union = _Union(_root=True)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700791
792
Guido van Rossum4cefe742016-09-27 15:20:12 -0700793class _Optional(_FinalTypingBase, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700794 """Optional type.
795
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700796 Optional[X] is equivalent to Union[X, None].
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700797 """
798
Guido van Rossumd70fe632015-08-05 12:11:06 +0200799 __slots__ = ()
800
Guido van Rossum4cefe742016-09-27 15:20:12 -0700801 @_tp_cache
802 def __getitem__(self, arg):
803 arg = _type_check(arg, "Optional[t] requires a single type.")
804 return Union[arg, type(None)]
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700805
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700806
Guido van Rossum4cefe742016-09-27 15:20:12 -0700807Optional = _Optional(_root=True)
808
809
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700810def _gorg(a):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800811 """Return the farthest origin of a generic class (internal helper)."""
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700812 assert isinstance(a, GenericMeta)
813 while a.__origin__ is not None:
814 a = a.__origin__
815 return a
816
817
818def _geqv(a, b):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800819 """Return whether two generic classes are equivalent (internal helper).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700820
821 The intention is to consider generic class X and any of its
Guido van Rossumb24569a2016-11-20 18:01:29 -0800822 parameterized forms (X[T], X[int], etc.) as equivalent.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700823
824 However, X is not equivalent to a subclass of X.
825
826 The relation is reflexive, symmetric and transitive.
827 """
828 assert isinstance(a, GenericMeta) and isinstance(b, GenericMeta)
829 # Reduce each to its origin.
830 return _gorg(a) is _gorg(b)
831
832
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700833def _next_in_mro(cls):
834 """Helper for Generic.__new__.
835
836 Returns the class after the last occurrence of Generic or
837 Generic[...] in cls.__mro__.
838 """
839 next_in_mro = object
840 # Look for the last occurrence of Generic or Generic[...].
841 for i, c in enumerate(cls.__mro__[:-1]):
842 if isinstance(c, GenericMeta) and _gorg(c) is Generic:
843 next_in_mro = cls.__mro__[i+1]
844 return next_in_mro
845
846
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700847def _valid_for_check(cls):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800848 """An internal helper to prohibit isinstance([1], List[str]) etc."""
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700849 if cls is Generic:
850 raise TypeError("Class %r cannot be used with class "
851 "or instance checks" % cls)
852 if (cls.__origin__ is not None and
853 sys._getframe(3).f_globals['__name__'] not in ['abc', 'functools']):
854 raise TypeError("Parameterized generics cannot be used with class "
855 "or instance checks")
856
857
858def _make_subclasshook(cls):
859 """Construct a __subclasshook__ callable that incorporates
860 the associated __extra__ class in subclass checks performed
861 against cls.
862 """
863 if isinstance(cls.__extra__, abc.ABCMeta):
864 # The logic mirrors that of ABCMeta.__subclasscheck__.
865 # Registered classes need not be checked here because
866 # cls and its extra share the same _abc_registry.
867 def __extrahook__(subclass):
868 _valid_for_check(cls)
869 res = cls.__extra__.__subclasshook__(subclass)
870 if res is not NotImplemented:
871 return res
872 if cls.__extra__ in subclass.__mro__:
873 return True
874 for scls in cls.__extra__.__subclasses__():
875 if isinstance(scls, GenericMeta):
876 continue
877 if issubclass(subclass, scls):
878 return True
879 return NotImplemented
880 else:
881 # For non-ABC extras we'll just call issubclass().
882 def __extrahook__(subclass):
883 _valid_for_check(cls)
884 if cls.__extra__ and issubclass(subclass, cls.__extra__):
885 return True
886 return NotImplemented
887 return __extrahook__
888
889
Guido van Rossum61f0a022016-11-29 09:46:21 -0800890def _no_slots_copy(dct):
891 """Internal helper: copy class __dict__ and clean slots class variables.
892 (They will be re-created if necessary by normal class machinery.)
893 """
894 dict_copy = dict(dct)
895 if '__slots__' in dict_copy:
896 for slot in dict_copy['__slots__']:
897 dict_copy.pop(slot, None)
898 return dict_copy
899
900
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700901class GenericMeta(TypingMeta, abc.ABCMeta):
Guido van Rossum83ec3022017-01-17 20:43:28 -0800902 """Metaclass for generic types.
903
904 This is a metaclass for typing.Generic and generic ABCs defined in
905 typing module. User defined subclasses of GenericMeta can override
906 __new__ and invoke super().__new__. Note that GenericMeta.__new__
907 has strict rules on what is allowed in its bases argument:
908 * plain Generic is disallowed in bases;
909 * Generic[...] should appear in bases at most once;
910 * if Generic[...] is present, then it should list all type variables
911 that appear in other bases.
912 In addition, type of all generic bases is erased, e.g., C[int] is
913 stripped to plain C.
914 """
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700915
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700916 def __new__(cls, name, bases, namespace,
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700917 tvars=None, args=None, origin=None, extra=None, orig_bases=None):
Guido van Rossum83ec3022017-01-17 20:43:28 -0800918 """Create a new generic class. GenericMeta.__new__ accepts
919 keyword arguments that are used for internal bookkeeping, therefore
920 an override should pass unused keyword arguments to super().
921 """
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700922 if tvars is not None:
923 # Called from __getitem__() below.
924 assert origin is not None
925 assert all(isinstance(t, TypeVar) for t in tvars), tvars
926 else:
927 # Called from class statement.
928 assert tvars is None, tvars
929 assert args is None, args
930 assert origin is None, origin
931
932 # Get the full set of tvars from the bases.
933 tvars = _type_vars(bases)
934 # Look for Generic[T1, ..., Tn].
935 # If found, tvars must be a subset of it.
936 # If not found, tvars is it.
937 # Also check for and reject plain Generic,
938 # and reject multiple Generic[...].
939 gvars = None
940 for base in bases:
941 if base is Generic:
942 raise TypeError("Cannot inherit from plain Generic")
943 if (isinstance(base, GenericMeta) and
944 base.__origin__ is Generic):
945 if gvars is not None:
946 raise TypeError(
947 "Cannot inherit from Generic[...] multiple types.")
948 gvars = base.__parameters__
949 if gvars is None:
950 gvars = tvars
951 else:
952 tvarset = set(tvars)
953 gvarset = set(gvars)
954 if not tvarset <= gvarset:
955 raise TypeError(
956 "Some type variables (%s) "
957 "are not listed in Generic[%s]" %
958 (", ".join(str(t) for t in tvars if t not in gvarset),
959 ", ".join(str(g) for g in gvars)))
960 tvars = gvars
961
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700962 initial_bases = bases
963 if extra is not None and type(extra) is abc.ABCMeta and extra not in bases:
964 bases = (extra,) + bases
965 bases = tuple(_gorg(b) if isinstance(b, GenericMeta) else b for b in bases)
966
967 # remove bare Generic from bases if there are other generic bases
968 if any(isinstance(b, GenericMeta) and b is not Generic for b in bases):
969 bases = tuple(b for b in bases if b is not Generic)
970 self = super().__new__(cls, name, bases, namespace, _root=True)
971
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700972 self.__parameters__ = tvars
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700973 # Be prepared that GenericMeta will be subclassed by TupleMeta
974 # and CallableMeta, those two allow ..., (), or [] in __args___.
975 self.__args__ = tuple(... if a is _TypingEllipsis else
976 () if a is _TypingEmpty else
977 a for a in args) if args else None
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700978 self.__origin__ = origin
Guido van Rossum1cea70f2016-05-18 08:35:00 -0700979 self.__extra__ = extra
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700980 # Speed hack (https://github.com/python/typing/issues/196).
981 self.__next_in_mro__ = _next_in_mro(self)
Guido van Rossum7ef22d62016-10-21 14:27:58 -0700982 # Preserve base classes on subclassing (__bases__ are type erased now).
983 if orig_bases is None:
984 self.__orig_bases__ = initial_bases
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700985
986 # This allows unparameterized generic collections to be used
987 # with issubclass() and isinstance() in the same way as their
988 # collections.abc counterparts (e.g., isinstance([], Iterable)).
Guido van Rossume2592672016-10-08 20:27:22 -0700989 if ('__subclasshook__' not in namespace and extra # allow overriding
990 or hasattr(self.__subclasshook__, '__name__') and
991 self.__subclasshook__.__name__ == '__extrahook__'):
992 self.__subclasshook__ = _make_subclasshook(self)
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700993 if isinstance(extra, abc.ABCMeta):
994 self._abc_registry = extra._abc_registry
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700995
996 if origin and hasattr(origin, '__qualname__'): # Fix for Python 3.2.
997 self.__qualname__ = origin.__qualname__
998 self.__tree_hash__ = hash(self._subs_tree()) if origin else hash((self.__name__,))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700999 return self
1000
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001001 def _get_type_vars(self, tvars):
1002 if self.__origin__ and self.__parameters__:
1003 _get_type_vars(self.__parameters__, tvars)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001004
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001005 def _eval_type(self, globalns, localns):
1006 ev_origin = (self.__origin__._eval_type(globalns, localns)
1007 if self.__origin__ else None)
1008 ev_args = tuple(_eval_type(a, globalns, localns) for a
1009 in self.__args__) if self.__args__ else None
1010 if ev_origin == self.__origin__ and ev_args == self.__args__:
1011 return self
1012 return self.__class__(self.__name__,
1013 self.__bases__,
Guido van Rossum61f0a022016-11-29 09:46:21 -08001014 _no_slots_copy(self.__dict__),
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001015 tvars=_type_vars(ev_args) if ev_args else None,
1016 args=ev_args,
1017 origin=ev_origin,
1018 extra=self.__extra__,
1019 orig_bases=self.__orig_bases__)
1020
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001021 def __repr__(self):
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001022 if self.__origin__ is None:
1023 return super().__repr__()
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001024 return self._tree_repr(self._subs_tree())
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001025
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001026 def _tree_repr(self, tree):
1027 arg_list = []
1028 for arg in tree[1:]:
1029 if arg == ():
1030 arg_list.append('()')
1031 elif not isinstance(arg, tuple):
1032 arg_list.append(_type_repr(arg))
1033 else:
1034 arg_list.append(arg[0]._tree_repr(arg))
1035 return super().__repr__() + '[%s]' % ', '.join(arg_list)
1036
1037 def _subs_tree(self, tvars=None, args=None):
1038 if self.__origin__ is None:
1039 return self
1040 tree_args = _subs_tree(self, tvars, args)
1041 return (_gorg(self),) + tuple(tree_args)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001042
1043 def __eq__(self, other):
1044 if not isinstance(other, GenericMeta):
1045 return NotImplemented
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001046 if self.__origin__ is None or other.__origin__ is None:
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001047 return self is other
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001048 return self.__tree_hash__ == other.__tree_hash__
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001049
1050 def __hash__(self):
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001051 return self.__tree_hash__
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001052
Guido van Rossum4cefe742016-09-27 15:20:12 -07001053 @_tp_cache
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001054 def __getitem__(self, params):
1055 if not isinstance(params, tuple):
1056 params = (params,)
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001057 if not params and not _gorg(self) is Tuple:
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001058 raise TypeError(
1059 "Parameter list to %s[...] cannot be empty" % _qualname(self))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001060 msg = "Parameters to generic types must be types."
1061 params = tuple(_type_check(p, msg) for p in params)
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001062 if self is Generic:
1063 # Generic can only be subscripted with unique type variables.
1064 if not all(isinstance(p, TypeVar) for p in params):
1065 raise TypeError(
1066 "Parameters to Generic[...] must all be type variables")
Guido van Rossumd70fe632015-08-05 12:11:06 +02001067 if len(set(params)) != len(params):
Guido van Rossum1b669102015-09-04 12:15:54 -07001068 raise TypeError(
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001069 "Parameters to Generic[...] must all be unique")
1070 tvars = params
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001071 args = params
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001072 elif self in (Tuple, Callable):
1073 tvars = _type_vars(params)
1074 args = params
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001075 elif self is _Protocol:
1076 # _Protocol is internal, don't check anything.
1077 tvars = params
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001078 args = params
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001079 elif self.__origin__ in (Generic, _Protocol):
1080 # Can't subscript Generic[...] or _Protocol[...].
1081 raise TypeError("Cannot subscript already-subscripted %s" %
1082 repr(self))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001083 else:
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001084 # Subscripting a regular Generic subclass.
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001085 _check_generic(self, params)
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001086 tvars = _type_vars(params)
1087 args = params
1088 return self.__class__(self.__name__,
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001089 self.__bases__,
Guido van Rossum61f0a022016-11-29 09:46:21 -08001090 _no_slots_copy(self.__dict__),
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001091 tvars=tvars,
1092 args=args,
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001093 origin=self,
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001094 extra=self.__extra__,
1095 orig_bases=self.__orig_bases__)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001096
Guido van Rossum1b669102015-09-04 12:15:54 -07001097 def __instancecheck__(self, instance):
1098 # Since we extend ABC.__subclasscheck__ and
1099 # ABC.__instancecheck__ inlines the cache checking done by the
1100 # latter, we must extend __instancecheck__ too. For simplicity
1101 # we just skip the cache check -- instance checks for generic
1102 # classes are supposed to be rare anyways.
Guido van Rossumb47c9d22016-10-03 08:40:50 -07001103 return issubclass(instance.__class__, self)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001104
Guido van Rossumb7dedc82016-10-29 12:44:29 -07001105 def __copy__(self):
Guido van Rossum61f0a022016-11-29 09:46:21 -08001106 return self.__class__(self.__name__, self.__bases__,
1107 _no_slots_copy(self.__dict__),
Guido van Rossumb7dedc82016-10-29 12:44:29 -07001108 self.__parameters__, self.__args__, self.__origin__,
1109 self.__extra__, self.__orig_bases__)
1110
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001111
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001112# Prevent checks for Generic to crash when defining Generic.
1113Generic = None
1114
1115
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001116def _generic_new(base_cls, cls, *args, **kwds):
1117 # Assure type is erased on instantiation,
1118 # but attempt to store it in __orig_class__
1119 if cls.__origin__ is None:
1120 return base_cls.__new__(cls)
1121 else:
1122 origin = _gorg(cls)
1123 obj = base_cls.__new__(origin)
1124 try:
1125 obj.__orig_class__ = cls
1126 except AttributeError:
1127 pass
1128 obj.__init__(*args, **kwds)
1129 return obj
1130
1131
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001132class Generic(metaclass=GenericMeta):
1133 """Abstract base class for generic types.
1134
Guido van Rossumb24569a2016-11-20 18:01:29 -08001135 A generic type is typically declared by inheriting from
1136 this class parameterized with one or more type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001137 For example, a generic mapping type might be defined as::
1138
1139 class Mapping(Generic[KT, VT]):
1140 def __getitem__(self, key: KT) -> VT:
1141 ...
1142 # Etc.
1143
1144 This class can then be used as follows::
1145
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001146 def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001147 try:
1148 return mapping[key]
1149 except KeyError:
1150 return default
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001151 """
1152
Guido van Rossumd70fe632015-08-05 12:11:06 +02001153 __slots__ = ()
1154
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001155 def __new__(cls, *args, **kwds):
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001156 if _geqv(cls, Generic):
1157 raise TypeError("Type Generic cannot be instantiated; "
1158 "it can be used only as a base class")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001159 return _generic_new(cls.__next_in_mro__, cls, *args, **kwds)
1160
1161
1162class _TypingEmpty:
Guido van Rossumb24569a2016-11-20 18:01:29 -08001163 """Internal placeholder for () or []. Used by TupleMeta and CallableMeta
1164 to allow empty list/tuple in specific places, without allowing them
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001165 to sneak in where prohibited.
1166 """
1167
1168
1169class _TypingEllipsis:
Guido van Rossumb24569a2016-11-20 18:01:29 -08001170 """Internal placeholder for ... (ellipsis)."""
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001171
1172
1173class TupleMeta(GenericMeta):
Guido van Rossumb24569a2016-11-20 18:01:29 -08001174 """Metaclass for Tuple (internal)."""
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001175
1176 @_tp_cache
1177 def __getitem__(self, parameters):
1178 if self.__origin__ is not None or not _geqv(self, Tuple):
1179 # Normal generic rules apply if this is not the first subscription
1180 # or a subscription of a subclass.
1181 return super().__getitem__(parameters)
1182 if parameters == ():
1183 return super().__getitem__((_TypingEmpty,))
1184 if not isinstance(parameters, tuple):
1185 parameters = (parameters,)
1186 if len(parameters) == 2 and parameters[1] is ...:
1187 msg = "Tuple[t, ...]: t must be a type."
1188 p = _type_check(parameters[0], msg)
1189 return super().__getitem__((p, _TypingEllipsis))
1190 msg = "Tuple[t0, t1, ...]: each t must be a type."
1191 parameters = tuple(_type_check(p, msg) for p in parameters)
1192 return super().__getitem__(parameters)
1193
1194 def __instancecheck__(self, obj):
1195 if self.__args__ == None:
1196 return isinstance(obj, tuple)
1197 raise TypeError("Parameterized Tuple cannot be used "
1198 "with isinstance().")
1199
1200 def __subclasscheck__(self, cls):
1201 if self.__args__ == None:
1202 return issubclass(cls, tuple)
1203 raise TypeError("Parameterized Tuple cannot be used "
1204 "with issubclass().")
1205
1206
1207class Tuple(tuple, extra=tuple, metaclass=TupleMeta):
1208 """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
1209
1210 Example: Tuple[T1, T2] is a tuple of two elements corresponding
1211 to type variables T1 and T2. Tuple[int, float, str] is a tuple
1212 of an int, a float and a string.
1213
1214 To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
1215 """
1216
1217 __slots__ = ()
1218
1219 def __new__(cls, *args, **kwds):
1220 if _geqv(cls, Tuple):
1221 raise TypeError("Type Tuple cannot be instantiated; "
1222 "use tuple() instead")
1223 return _generic_new(tuple, cls, *args, **kwds)
1224
1225
1226class CallableMeta(GenericMeta):
Guido van Rossumb24569a2016-11-20 18:01:29 -08001227 """Metaclass for Callable (internal)."""
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001228
1229 def __repr__(self):
1230 if self.__origin__ is None:
1231 return super().__repr__()
1232 return self._tree_repr(self._subs_tree())
1233
1234 def _tree_repr(self, tree):
1235 if _gorg(self) is not Callable:
1236 return super()._tree_repr(tree)
1237 # For actual Callable (not its subclass) we override
1238 # super()._tree_repr() for nice formatting.
1239 arg_list = []
1240 for arg in tree[1:]:
Guido van Rossum991d14f2016-11-09 13:12:51 -08001241 if not isinstance(arg, tuple):
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001242 arg_list.append(_type_repr(arg))
1243 else:
1244 arg_list.append(arg[0]._tree_repr(arg))
Guido van Rossum991d14f2016-11-09 13:12:51 -08001245 if arg_list[0] == '...':
1246 return repr(tree[0]) + '[..., %s]' % arg_list[1]
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001247 return (repr(tree[0]) +
1248 '[[%s], %s]' % (', '.join(arg_list[:-1]), arg_list[-1]))
1249
1250 def __getitem__(self, parameters):
Guido van Rossumb24569a2016-11-20 18:01:29 -08001251 """A thin wrapper around __getitem_inner__ to provide the latter
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001252 with hashable arguments to improve speed.
1253 """
1254
1255 if self.__origin__ is not None or not _geqv(self, Callable):
1256 return super().__getitem__(parameters)
1257 if not isinstance(parameters, tuple) or len(parameters) != 2:
1258 raise TypeError("Callable must be used as "
1259 "Callable[[arg, ...], result].")
1260 args, result = parameters
Guido van Rossum991d14f2016-11-09 13:12:51 -08001261 if args is Ellipsis:
1262 parameters = (Ellipsis, result)
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001263 else:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001264 if not isinstance(args, list):
1265 raise TypeError("Callable[args, result]: args must be a list."
1266 " Got %.100r." % (args,))
Guido van Rossum991d14f2016-11-09 13:12:51 -08001267 parameters = (tuple(args), result)
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001268 return self.__getitem_inner__(parameters)
1269
1270 @_tp_cache
1271 def __getitem_inner__(self, parameters):
Guido van Rossum991d14f2016-11-09 13:12:51 -08001272 args, result = parameters
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001273 msg = "Callable[args, result]: result must be a type."
1274 result = _type_check(result, msg)
Guido van Rossum991d14f2016-11-09 13:12:51 -08001275 if args is Ellipsis:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001276 return super().__getitem__((_TypingEllipsis, result))
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001277 msg = "Callable[[arg, ...], result]: each arg must be a type."
1278 args = tuple(_type_check(arg, msg) for arg in args)
1279 parameters = args + (result,)
1280 return super().__getitem__(parameters)
1281
1282
1283class Callable(extra=collections_abc.Callable, metaclass = CallableMeta):
1284 """Callable type; Callable[[int], str] is a function of (int) -> str.
1285
1286 The subscription syntax must always be used with exactly two
1287 values: the argument list and the return type. The argument list
Guido van Rossumb24569a2016-11-20 18:01:29 -08001288 must be a list of types or ellipsis; the return type must be a single type.
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001289
1290 There is no syntax to indicate optional or keyword arguments,
1291 such function types are rarely used as callback types.
1292 """
1293
1294 __slots__ = ()
1295
1296 def __new__(cls, *args, **kwds):
1297 if _geqv(cls, Callable):
1298 raise TypeError("Type Callable cannot be instantiated; "
1299 "use a non-abstract subclass instead")
1300 return _generic_new(cls.__next_in_mro__, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001301
1302
Guido van Rossum4cefe742016-09-27 15:20:12 -07001303class _ClassVar(_FinalTypingBase, _root=True):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001304 """Special type construct to mark class variables.
1305
1306 An annotation wrapped in ClassVar indicates that a given
1307 attribute is intended to be used as a class variable and
1308 should not be set on instances of that class. Usage::
1309
1310 class Starship:
1311 stats: ClassVar[Dict[str, int]] = {} # class variable
1312 damage: int = 10 # instance variable
1313
1314 ClassVar accepts only types and cannot be further subscribed.
1315
1316 Note that ClassVar is not a class itself, and should not
1317 be used with isinstance() or issubclass().
1318 """
1319
Guido van Rossum4cefe742016-09-27 15:20:12 -07001320 __slots__ = ('__type__',)
1321
1322 def __init__(self, tp=None, **kwds):
1323 self.__type__ = tp
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001324
1325 def __getitem__(self, item):
1326 cls = type(self)
1327 if self.__type__ is None:
1328 return cls(_type_check(item,
Guido van Rossum4cefe742016-09-27 15:20:12 -07001329 '{} accepts only single type.'.format(cls.__name__[1:])),
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001330 _root=True)
1331 raise TypeError('{} cannot be further subscripted'
1332 .format(cls.__name__[1:]))
1333
1334 def _eval_type(self, globalns, localns):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001335 new_tp = _eval_type(self.__type__, globalns, localns)
1336 if new_tp == self.__type__:
1337 return self
1338 return type(self)(new_tp, _root=True)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001339
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001340 def __repr__(self):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001341 r = super().__repr__()
1342 if self.__type__ is not None:
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001343 r += '[{}]'.format(_type_repr(self.__type__))
Guido van Rossum4cefe742016-09-27 15:20:12 -07001344 return r
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001345
1346 def __hash__(self):
1347 return hash((type(self).__name__, self.__type__))
1348
1349 def __eq__(self, other):
1350 if not isinstance(other, _ClassVar):
1351 return NotImplemented
1352 if self.__type__ is not None:
1353 return self.__type__ == other.__type__
1354 return self is other
1355
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001356
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001357ClassVar = _ClassVar(_root=True)
1358
1359
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001360def cast(typ, val):
1361 """Cast a value to a type.
1362
1363 This returns the value unchanged. To the type checker this
1364 signals that the return value has the designated type, but at
1365 runtime we intentionally don't check anything (we want this
1366 to be as fast as possible).
1367 """
1368 return val
1369
1370
1371def _get_defaults(func):
1372 """Internal helper to extract the default arguments, by name."""
Guido van Rossum991d14f2016-11-09 13:12:51 -08001373 try:
1374 code = func.__code__
1375 except AttributeError:
1376 # Some built-in functions don't have __code__, __defaults__, etc.
1377 return {}
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001378 pos_count = code.co_argcount
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001379 arg_names = code.co_varnames
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001380 arg_names = arg_names[:pos_count]
1381 defaults = func.__defaults__ or ()
1382 kwdefaults = func.__kwdefaults__
1383 res = dict(kwdefaults) if kwdefaults else {}
1384 pos_offset = pos_count - len(defaults)
1385 for name, value in zip(arg_names[pos_offset:], defaults):
1386 assert name not in res
1387 res[name] = value
1388 return res
1389
1390
Guido van Rossum991d14f2016-11-09 13:12:51 -08001391def get_type_hints(obj, globalns=None, localns=None):
1392 """Return type hints for an object.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001393
Guido van Rossum991d14f2016-11-09 13:12:51 -08001394 This is often the same as obj.__annotations__, but it handles
1395 forward references encoded as string literals, and if necessary
1396 adds Optional[t] if a default value equal to None is set.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001397
Guido van Rossum991d14f2016-11-09 13:12:51 -08001398 The argument may be a module, class, method, or function. The annotations
1399 are returned as a dictionary. For classes, annotations include also
1400 inherited members.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001401
Guido van Rossum991d14f2016-11-09 13:12:51 -08001402 TypeError is raised if the argument is not of a type that can contain
1403 annotations, and an empty dictionary is returned if no annotations are
1404 present.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001405
Guido van Rossum991d14f2016-11-09 13:12:51 -08001406 BEWARE -- the behavior of globalns and localns is counterintuitive
1407 (unless you are familiar with how eval() and exec() work). The
1408 search order is locals first, then globals.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001409
Guido van Rossum991d14f2016-11-09 13:12:51 -08001410 - If no dict arguments are passed, an attempt is made to use the
1411 globals from obj, and these are also used as the locals. If the
1412 object does not appear to have globals, an exception is raised.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001413
Guido van Rossum991d14f2016-11-09 13:12:51 -08001414 - If one dict argument is passed, it is used for both globals and
1415 locals.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001416
Guido van Rossum991d14f2016-11-09 13:12:51 -08001417 - If two dict arguments are passed, they specify globals and
1418 locals, respectively.
1419 """
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001420
Guido van Rossum991d14f2016-11-09 13:12:51 -08001421 if getattr(obj, '__no_type_check__', None):
1422 return {}
1423 if globalns is None:
1424 globalns = getattr(obj, '__globals__', {})
1425 if localns is None:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001426 localns = globalns
Guido van Rossum991d14f2016-11-09 13:12:51 -08001427 elif localns is None:
1428 localns = globalns
1429 # Classes require a special treatment.
1430 if isinstance(obj, type):
1431 hints = {}
1432 for base in reversed(obj.__mro__):
1433 ann = base.__dict__.get('__annotations__', {})
1434 for name, value in ann.items():
1435 if value is None:
1436 value = type(None)
1437 if isinstance(value, str):
1438 value = _ForwardRef(value)
1439 value = _eval_type(value, globalns, localns)
1440 hints[name] = value
1441 return hints
1442 hints = getattr(obj, '__annotations__', None)
1443 if hints is None:
1444 # Return empty annotations for something that _could_ have them.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001445 if (isinstance(obj, types.FunctionType) or
1446 isinstance(obj, types.BuiltinFunctionType) or
Guido van Rossum991d14f2016-11-09 13:12:51 -08001447 isinstance(obj, types.MethodType) or
1448 isinstance(obj, types.ModuleType)):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001449 return {}
Guido van Rossum991d14f2016-11-09 13:12:51 -08001450 else:
1451 raise TypeError('{!r} is not a module, class, method, '
1452 'or function.'.format(obj))
1453 defaults = _get_defaults(obj)
1454 hints = dict(hints)
1455 for name, value in hints.items():
1456 if value is None:
1457 value = type(None)
1458 if isinstance(value, str):
1459 value = _ForwardRef(value)
1460 value = _eval_type(value, globalns, localns)
1461 if name in defaults and defaults[name] is None:
1462 value = Optional[value]
1463 hints[name] = value
1464 return hints
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001465
1466
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001467def no_type_check(arg):
1468 """Decorator to indicate that annotations are not type hints.
1469
1470 The argument must be a class or function; if it is a class, it
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001471 applies recursively to all methods and classes defined in that class
1472 (but not to methods defined in its superclasses or subclasses).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001473
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001474 This mutates the function(s) or class(es) in place.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001475 """
1476 if isinstance(arg, type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001477 arg_attrs = arg.__dict__.copy()
1478 for attr, val in arg.__dict__.items():
1479 if val in arg.__bases__:
1480 arg_attrs.pop(attr)
1481 for obj in arg_attrs.values():
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001482 if isinstance(obj, types.FunctionType):
1483 obj.__no_type_check__ = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001484 if isinstance(obj, type):
1485 no_type_check(obj)
1486 try:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001487 arg.__no_type_check__ = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001488 except TypeError: # built-in classes
1489 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001490 return arg
1491
1492
1493def no_type_check_decorator(decorator):
1494 """Decorator to give another decorator the @no_type_check effect.
1495
1496 This wraps the decorator with something that wraps the decorated
1497 function in @no_type_check.
1498 """
1499
1500 @functools.wraps(decorator)
1501 def wrapped_decorator(*args, **kwds):
1502 func = decorator(*args, **kwds)
1503 func = no_type_check(func)
1504 return func
1505
1506 return wrapped_decorator
1507
1508
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001509def _overload_dummy(*args, **kwds):
1510 """Helper for @overload to raise when called."""
1511 raise NotImplementedError(
1512 "You should not call an overloaded function. "
1513 "A series of @overload-decorated functions "
1514 "outside a stub module should always be followed "
1515 "by an implementation that is not @overload-ed.")
1516
1517
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001518def overload(func):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001519 """Decorator for overloaded functions/methods.
1520
1521 In a stub file, place two or more stub definitions for the same
1522 function in a row, each decorated with @overload. For example:
1523
1524 @overload
1525 def utf8(value: None) -> None: ...
1526 @overload
1527 def utf8(value: bytes) -> bytes: ...
1528 @overload
1529 def utf8(value: str) -> bytes: ...
1530
1531 In a non-stub file (i.e. a regular .py file), do the same but
1532 follow it with an implementation. The implementation should *not*
1533 be decorated with @overload. For example:
1534
1535 @overload
1536 def utf8(value: None) -> None: ...
1537 @overload
1538 def utf8(value: bytes) -> bytes: ...
1539 @overload
1540 def utf8(value: str) -> bytes: ...
1541 def utf8(value):
1542 # implementation goes here
1543 """
1544 return _overload_dummy
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001545
1546
1547class _ProtocolMeta(GenericMeta):
1548 """Internal metaclass for _Protocol.
1549
1550 This exists so _Protocol classes can be generic without deriving
1551 from Generic.
1552 """
1553
Guido van Rossumd70fe632015-08-05 12:11:06 +02001554 def __instancecheck__(self, obj):
Guido van Rossumca4b2522016-11-19 10:32:41 -08001555 if _Protocol not in self.__bases__:
1556 return super().__instancecheck__(obj)
Guido van Rossumd70fe632015-08-05 12:11:06 +02001557 raise TypeError("Protocols cannot be used with isinstance().")
1558
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001559 def __subclasscheck__(self, cls):
1560 if not self._is_protocol:
1561 # No structural checks since this isn't a protocol.
1562 return NotImplemented
1563
1564 if self is _Protocol:
1565 # Every class is a subclass of the empty protocol.
1566 return True
1567
1568 # Find all attributes defined in the protocol.
1569 attrs = self._get_protocol_attrs()
1570
1571 for attr in attrs:
1572 if not any(attr in d.__dict__ for d in cls.__mro__):
1573 return False
1574 return True
1575
1576 def _get_protocol_attrs(self):
1577 # Get all Protocol base classes.
1578 protocol_bases = []
1579 for c in self.__mro__:
1580 if getattr(c, '_is_protocol', False) and c.__name__ != '_Protocol':
1581 protocol_bases.append(c)
1582
1583 # Get attributes included in protocol.
1584 attrs = set()
1585 for base in protocol_bases:
1586 for attr in base.__dict__.keys():
1587 # Include attributes not defined in any non-protocol bases.
1588 for c in self.__mro__:
1589 if (c is not base and attr in c.__dict__ and
1590 not getattr(c, '_is_protocol', False)):
1591 break
1592 else:
1593 if (not attr.startswith('_abc_') and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001594 attr != '__abstractmethods__' and
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001595 attr != '__annotations__' and
1596 attr != '__weakref__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001597 attr != '_is_protocol' and
1598 attr != '__dict__' and
1599 attr != '__args__' and
1600 attr != '__slots__' and
1601 attr != '_get_protocol_attrs' and
1602 attr != '__next_in_mro__' and
1603 attr != '__parameters__' and
1604 attr != '__origin__' and
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001605 attr != '__orig_bases__' and
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001606 attr != '__extra__' and
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001607 attr != '__tree_hash__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001608 attr != '__module__'):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001609 attrs.add(attr)
1610
1611 return attrs
1612
1613
1614class _Protocol(metaclass=_ProtocolMeta):
1615 """Internal base class for protocol classes.
1616
Guido van Rossumb24569a2016-11-20 18:01:29 -08001617 This implements a simple-minded structural issubclass check
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001618 (similar but more general than the one-offs in collections.abc
1619 such as Hashable).
1620 """
1621
Guido van Rossumd70fe632015-08-05 12:11:06 +02001622 __slots__ = ()
1623
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001624 _is_protocol = True
1625
1626
1627# Various ABCs mimicking those in collections.abc.
1628# A few are simply re-exported for completeness.
1629
1630Hashable = collections_abc.Hashable # Not generic.
1631
1632
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001633if hasattr(collections_abc, 'Awaitable'):
1634 class Awaitable(Generic[T_co], extra=collections_abc.Awaitable):
1635 __slots__ = ()
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001636
1637 __all__.append('Awaitable')
1638
1639
1640if hasattr(collections_abc, 'Coroutine'):
1641 class Coroutine(Awaitable[V_co], Generic[T_co, T_contra, V_co],
1642 extra=collections_abc.Coroutine):
1643 __slots__ = ()
1644
1645 __all__.append('Coroutine')
Guido van Rossumf17c2002015-12-03 17:31:24 -08001646
1647
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001648if hasattr(collections_abc, 'AsyncIterable'):
Guido van Rossumf17c2002015-12-03 17:31:24 -08001649
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001650 class AsyncIterable(Generic[T_co], extra=collections_abc.AsyncIterable):
1651 __slots__ = ()
Guido van Rossumf17c2002015-12-03 17:31:24 -08001652
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001653 class AsyncIterator(AsyncIterable[T_co],
1654 extra=collections_abc.AsyncIterator):
1655 __slots__ = ()
1656
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001657 __all__.append('AsyncIterable')
1658 __all__.append('AsyncIterator')
Guido van Rossumf17c2002015-12-03 17:31:24 -08001659
1660
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001661class Iterable(Generic[T_co], extra=collections_abc.Iterable):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001662 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001663
1664
1665class Iterator(Iterable[T_co], extra=collections_abc.Iterator):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001666 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001667
1668
1669class SupportsInt(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001670 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001671
1672 @abstractmethod
1673 def __int__(self) -> int:
1674 pass
1675
1676
1677class SupportsFloat(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001678 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001679
1680 @abstractmethod
1681 def __float__(self) -> float:
1682 pass
1683
1684
1685class SupportsComplex(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001686 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001687
1688 @abstractmethod
1689 def __complex__(self) -> complex:
1690 pass
1691
1692
1693class SupportsBytes(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001694 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001695
1696 @abstractmethod
1697 def __bytes__(self) -> bytes:
1698 pass
1699
1700
Guido van Rossumd70fe632015-08-05 12:11:06 +02001701class SupportsAbs(_Protocol[T_co]):
1702 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001703
1704 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001705 def __abs__(self) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001706 pass
1707
1708
Guido van Rossumd70fe632015-08-05 12:11:06 +02001709class SupportsRound(_Protocol[T_co]):
1710 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001711
1712 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001713 def __round__(self, ndigits: int = 0) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001714 pass
1715
1716
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001717if hasattr(collections_abc, 'Reversible'):
1718 class Reversible(Iterable[T_co], extra=collections_abc.Reversible):
1719 __slots__ = ()
1720else:
1721 class Reversible(_Protocol[T_co]):
1722 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001723
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001724 @abstractmethod
1725 def __reversed__(self) -> 'Iterator[T_co]':
1726 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001727
1728
1729Sized = collections_abc.Sized # Not generic.
1730
1731
1732class Container(Generic[T_co], extra=collections_abc.Container):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001733 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001734
1735
Guido van Rossumefa798d2016-08-23 11:01:50 -07001736if hasattr(collections_abc, 'Collection'):
1737 class Collection(Sized, Iterable[T_co], Container[T_co],
1738 extra=collections_abc.Collection):
1739 __slots__ = ()
1740
1741 __all__.append('Collection')
1742
1743
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001744# Callable was defined earlier.
1745
Guido van Rossumefa798d2016-08-23 11:01:50 -07001746if hasattr(collections_abc, 'Collection'):
1747 class AbstractSet(Collection[T_co],
1748 extra=collections_abc.Set):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001749 __slots__ = ()
Guido van Rossumefa798d2016-08-23 11:01:50 -07001750else:
1751 class AbstractSet(Sized, Iterable[T_co], Container[T_co],
1752 extra=collections_abc.Set):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001753 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001754
1755
1756class MutableSet(AbstractSet[T], extra=collections_abc.MutableSet):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001757 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001758
1759
Guido van Rossumefa798d2016-08-23 11:01:50 -07001760# NOTE: It is only covariant in the value type.
1761if hasattr(collections_abc, 'Collection'):
1762 class Mapping(Collection[KT], Generic[KT, VT_co],
1763 extra=collections_abc.Mapping):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001764 __slots__ = ()
Guido van Rossumefa798d2016-08-23 11:01:50 -07001765else:
1766 class Mapping(Sized, Iterable[KT], Container[KT], Generic[KT, VT_co],
1767 extra=collections_abc.Mapping):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001768 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001769
1770
1771class MutableMapping(Mapping[KT, VT], extra=collections_abc.MutableMapping):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001772 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001773
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001774if hasattr(collections_abc, 'Reversible'):
Guido van Rossumefa798d2016-08-23 11:01:50 -07001775 if hasattr(collections_abc, 'Collection'):
1776 class Sequence(Reversible[T_co], Collection[T_co],
1777 extra=collections_abc.Sequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001778 __slots__ = ()
Guido van Rossumefa798d2016-08-23 11:01:50 -07001779 else:
1780 class Sequence(Sized, Reversible[T_co], Container[T_co],
1781 extra=collections_abc.Sequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001782 __slots__ = ()
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001783else:
1784 class Sequence(Sized, Iterable[T_co], Container[T_co],
1785 extra=collections_abc.Sequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001786 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001787
1788
1789class MutableSequence(Sequence[T], extra=collections_abc.MutableSequence):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001790 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001791
1792
1793class ByteString(Sequence[int], extra=collections_abc.ByteString):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001794 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001795
1796
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001797class List(list, MutableSequence[T], extra=list):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001798
Guido van Rossum4cefe742016-09-27 15:20:12 -07001799 __slots__ = ()
1800
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001801 def __new__(cls, *args, **kwds):
1802 if _geqv(cls, List):
1803 raise TypeError("Type List cannot be instantiated; "
1804 "use list() instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001805 return _generic_new(list, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001806
Raymond Hettinger80490522017-01-16 22:42:37 -08001807class Deque(collections.deque, MutableSequence[T], extra=collections.deque):
1808
1809 __slots__ = ()
1810
1811 def __new__(cls, *args, **kwds):
1812 if _geqv(cls, Deque):
1813 raise TypeError("Type Deque cannot be instantiated; "
1814 "use deque() instead")
1815 return _generic_new(collections.deque, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001816
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001817class Set(set, MutableSet[T], extra=set):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001818
Guido van Rossum4cefe742016-09-27 15:20:12 -07001819 __slots__ = ()
1820
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001821 def __new__(cls, *args, **kwds):
1822 if _geqv(cls, Set):
1823 raise TypeError("Type Set cannot be instantiated; "
1824 "use set() instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001825 return _generic_new(set, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001826
1827
Guido van Rossum4cefe742016-09-27 15:20:12 -07001828class FrozenSet(frozenset, AbstractSet[T_co], extra=frozenset):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001829 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001830
1831 def __new__(cls, *args, **kwds):
1832 if _geqv(cls, FrozenSet):
1833 raise TypeError("Type FrozenSet cannot be instantiated; "
1834 "use frozenset() instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001835 return _generic_new(frozenset, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001836
1837
1838class MappingView(Sized, Iterable[T_co], extra=collections_abc.MappingView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001839 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001840
1841
Guido van Rossumd70fe632015-08-05 12:11:06 +02001842class KeysView(MappingView[KT], AbstractSet[KT],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001843 extra=collections_abc.KeysView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001844 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001845
1846
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001847class ItemsView(MappingView[Tuple[KT, VT_co]],
Guido van Rossum0e0563c2016-04-05 14:54:25 -07001848 AbstractSet[Tuple[KT, VT_co]],
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001849 Generic[KT, VT_co],
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001850 extra=collections_abc.ItemsView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001851 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001852
1853
1854class ValuesView(MappingView[VT_co], extra=collections_abc.ValuesView):
Guido van Rossum4cefe742016-09-27 15:20:12 -07001855 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001856
1857
Brett Cannonf3ad0422016-04-15 10:51:30 -07001858if hasattr(contextlib, 'AbstractContextManager'):
1859 class ContextManager(Generic[T_co], extra=contextlib.AbstractContextManager):
1860 __slots__ = ()
1861 __all__.append('ContextManager')
1862
1863
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001864class Dict(dict, MutableMapping[KT, VT], extra=dict):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001865
Guido van Rossum4cefe742016-09-27 15:20:12 -07001866 __slots__ = ()
1867
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001868 def __new__(cls, *args, **kwds):
1869 if _geqv(cls, Dict):
1870 raise TypeError("Type Dict cannot be instantiated; "
1871 "use dict() instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001872 return _generic_new(dict, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001873
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001874class DefaultDict(collections.defaultdict, MutableMapping[KT, VT],
1875 extra=collections.defaultdict):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001876
Guido van Rossum4cefe742016-09-27 15:20:12 -07001877 __slots__ = ()
1878
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001879 def __new__(cls, *args, **kwds):
1880 if _geqv(cls, DefaultDict):
1881 raise TypeError("Type DefaultDict cannot be instantiated; "
1882 "use collections.defaultdict() instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001883 return _generic_new(collections.defaultdict, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001884
1885# Determine what base class to use for Generator.
1886if hasattr(collections_abc, 'Generator'):
1887 # Sufficiently recent versions of 3.5 have a Generator ABC.
1888 _G_base = collections_abc.Generator
1889else:
1890 # Fall back on the exact type.
1891 _G_base = types.GeneratorType
1892
1893
1894class Generator(Iterator[T_co], Generic[T_co, T_contra, V_co],
1895 extra=_G_base):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001896 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001897
1898 def __new__(cls, *args, **kwds):
1899 if _geqv(cls, Generator):
1900 raise TypeError("Type Generator cannot be instantiated; "
1901 "create a subclass instead")
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001902 return _generic_new(_G_base, cls, *args, **kwds)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001903
Guido van Rossume9ed5602017-01-18 13:10:31 -08001904if hasattr(collections_abc, 'AsyncGenerator'):
1905 class AsyncGenerator(AsyncIterator[T_co], Generic[T_co, T_contra],
1906 extra=collections_abc.AsyncGenerator):
1907 __slots__ = ()
1908
1909 __all__.append('AsyncGenerator')
1910
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001911
Guido van Rossumeb9aca32016-05-24 16:38:22 -07001912# Internal type variable used for Type[].
Guido van Rossumefa798d2016-08-23 11:01:50 -07001913CT_co = TypeVar('CT_co', covariant=True, bound=type)
Guido van Rossumeb9aca32016-05-24 16:38:22 -07001914
1915
Guido van Rossumb22c7082016-05-26 09:56:19 -07001916# This is not a real generic class. Don't use outside annotations.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001917class Type(Generic[CT_co], extra=type):
Guido van Rossumb22c7082016-05-26 09:56:19 -07001918 """A special construct usable to annotate class objects.
Guido van Rossumeb9aca32016-05-24 16:38:22 -07001919
1920 For example, suppose we have the following classes::
1921
1922 class User: ... # Abstract base for User classes
1923 class BasicUser(User): ...
1924 class ProUser(User): ...
1925 class TeamUser(User): ...
1926
1927 And a function that takes a class argument that's a subclass of
1928 User and returns an instance of the corresponding class::
1929
1930 U = TypeVar('U', bound=User)
1931 def new_user(user_class: Type[U]) -> U:
1932 user = user_class()
1933 # (Here we could write the user object to a database)
1934 return user
1935
1936 joe = new_user(BasicUser)
1937
1938 At this point the type checker knows that joe has type BasicUser.
1939 """
1940
Guido van Rossum4cefe742016-09-27 15:20:12 -07001941 __slots__ = ()
1942
Guido van Rossumeb9aca32016-05-24 16:38:22 -07001943
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001944def _make_nmtuple(name, types):
Guido van Rossum2f841442016-11-15 09:48:06 -08001945 msg = "NamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a type"
1946 types = [(n, _type_check(t, msg)) for n, t in types]
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001947 nm_tpl = collections.namedtuple(name, [n for n, t in types])
Guido van Rossum83ec3022017-01-17 20:43:28 -08001948 # Prior to PEP 526, only _field_types attribute was assigned.
1949 # Now, both __annotations__ and _field_types are used to maintain compatibility.
1950 nm_tpl.__annotations__ = nm_tpl._field_types = collections.OrderedDict(types)
Guido van Rossum557d1eb2015-11-19 08:16:31 -08001951 try:
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001952 nm_tpl.__module__ = sys._getframe(2).f_globals.get('__name__', '__main__')
Guido van Rossum557d1eb2015-11-19 08:16:31 -08001953 except (AttributeError, ValueError):
1954 pass
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001955 return nm_tpl
1956
1957
Guido van Rossum2f841442016-11-15 09:48:06 -08001958_PY36 = sys.version_info[:2] >= (3, 6)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001959
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001960
Guido van Rossum2f841442016-11-15 09:48:06 -08001961class NamedTupleMeta(type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001962
Guido van Rossum2f841442016-11-15 09:48:06 -08001963 def __new__(cls, typename, bases, ns):
1964 if ns.get('_root', False):
1965 return super().__new__(cls, typename, bases, ns)
1966 if not _PY36:
1967 raise TypeError("Class syntax for NamedTuple is only supported"
1968 " in Python 3.6+")
1969 types = ns.get('__annotations__', {})
Guido van Rossum3c268be2017-01-18 08:03:50 -08001970 nm_tpl = _make_nmtuple(typename, types.items())
1971 defaults = []
1972 defaults_dict = {}
1973 for field_name in types:
1974 if field_name in ns:
1975 default_value = ns[field_name]
1976 defaults.append(default_value)
1977 defaults_dict[field_name] = default_value
1978 elif defaults:
1979 raise TypeError("Non-default namedtuple field {field_name} cannot follow default"
1980 " field(s) {default_names}"
1981 .format(field_name=field_name,
1982 default_names=', '.join(defaults_dict.keys())))
1983 nm_tpl.__new__.__defaults__ = tuple(defaults)
1984 nm_tpl._field_defaults = defaults_dict
1985 return nm_tpl
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001986
Guido van Rossum2f841442016-11-15 09:48:06 -08001987class NamedTuple(metaclass=NamedTupleMeta):
1988 """Typed version of namedtuple.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001989
Guido van Rossum2f841442016-11-15 09:48:06 -08001990 Usage in Python versions >= 3.6::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001991
Guido van Rossum2f841442016-11-15 09:48:06 -08001992 class Employee(NamedTuple):
1993 name: str
1994 id: int
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001995
Guido van Rossum2f841442016-11-15 09:48:06 -08001996 This is equivalent to::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001997
Guido van Rossum2f841442016-11-15 09:48:06 -08001998 Employee = collections.namedtuple('Employee', ['name', 'id'])
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001999
Guido van Rossum83ec3022017-01-17 20:43:28 -08002000 The resulting class has extra __annotations__ and _field_types
2001 attributes, giving an ordered dict mapping field names to types.
2002 __annotations__ should be preferred, while _field_types
2003 is kept to maintain pre PEP 526 compatibility. (The field names
Guido van Rossum2f841442016-11-15 09:48:06 -08002004 are in the _fields attribute, which is part of the namedtuple
2005 API.) Alternative equivalent keyword syntax is also accepted::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002006
Guido van Rossum2f841442016-11-15 09:48:06 -08002007 Employee = NamedTuple('Employee', name=str, id=int)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002008
Guido van Rossum2f841442016-11-15 09:48:06 -08002009 In Python versions <= 3.5 use::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002010
Guido van Rossum2f841442016-11-15 09:48:06 -08002011 Employee = NamedTuple('Employee', [('name', str), ('id', int)])
2012 """
2013 _root = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002014
Guido van Rossum2f841442016-11-15 09:48:06 -08002015 def __new__(self, typename, fields=None, **kwargs):
2016 if kwargs and not _PY36:
2017 raise TypeError("Keyword syntax for NamedTuple is only supported"
2018 " in Python 3.6+")
2019 if fields is None:
2020 fields = kwargs.items()
2021 elif kwargs:
2022 raise TypeError("Either list of fields or keywords"
2023 " can be provided to NamedTuple, not both")
Guido van Rossum0a6976d2016-09-11 15:34:56 -07002024 return _make_nmtuple(typename, fields)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002025
2026
Guido van Rossum91185fe2016-06-08 11:19:11 -07002027def NewType(name, tp):
2028 """NewType creates simple unique types with almost zero
2029 runtime overhead. NewType(name, tp) is considered a subtype of tp
2030 by static type checkers. At runtime, NewType(name, tp) returns
2031 a dummy function that simply returns its argument. Usage::
2032
2033 UserId = NewType('UserId', int)
2034
2035 def name_by_id(user_id: UserId) -> str:
2036 ...
2037
2038 UserId('user') # Fails type check
2039
2040 name_by_id(42) # Fails type check
2041 name_by_id(UserId(42)) # OK
2042
2043 num = UserId(5) + 1 # type: int
2044 """
2045
2046 def new_type(x):
2047 return x
2048
2049 new_type.__name__ = name
2050 new_type.__supertype__ = tp
2051 return new_type
2052
2053
Guido van Rossum0e0563c2016-04-05 14:54:25 -07002054# Python-version-specific alias (Python 2: unicode; Python 3: str)
2055Text = str
2056
2057
Guido van Rossum91185fe2016-06-08 11:19:11 -07002058# Constant that's True when type checking, but False here.
2059TYPE_CHECKING = False
2060
2061
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002062class IO(Generic[AnyStr]):
2063 """Generic base class for TextIO and BinaryIO.
2064
2065 This is an abstract, generic version of the return of open().
2066
2067 NOTE: This does not distinguish between the different possible
2068 classes (text vs. binary, read vs. write vs. read/write,
2069 append-only, unbuffered). The TextIO and BinaryIO subclasses
2070 below capture the distinctions between text vs. binary, which is
2071 pervasive in the interface; however we currently do not offer a
2072 way to track the other distinctions in the type system.
2073 """
2074
Guido van Rossumd70fe632015-08-05 12:11:06 +02002075 __slots__ = ()
2076
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002077 @abstractproperty
2078 def mode(self) -> str:
2079 pass
2080
2081 @abstractproperty
2082 def name(self) -> str:
2083 pass
2084
2085 @abstractmethod
2086 def close(self) -> None:
2087 pass
2088
2089 @abstractmethod
2090 def closed(self) -> bool:
2091 pass
2092
2093 @abstractmethod
2094 def fileno(self) -> int:
2095 pass
2096
2097 @abstractmethod
2098 def flush(self) -> None:
2099 pass
2100
2101 @abstractmethod
2102 def isatty(self) -> bool:
2103 pass
2104
2105 @abstractmethod
2106 def read(self, n: int = -1) -> AnyStr:
2107 pass
2108
2109 @abstractmethod
2110 def readable(self) -> bool:
2111 pass
2112
2113 @abstractmethod
2114 def readline(self, limit: int = -1) -> AnyStr:
2115 pass
2116
2117 @abstractmethod
2118 def readlines(self, hint: int = -1) -> List[AnyStr]:
2119 pass
2120
2121 @abstractmethod
2122 def seek(self, offset: int, whence: int = 0) -> int:
2123 pass
2124
2125 @abstractmethod
2126 def seekable(self) -> bool:
2127 pass
2128
2129 @abstractmethod
2130 def tell(self) -> int:
2131 pass
2132
2133 @abstractmethod
2134 def truncate(self, size: int = None) -> int:
2135 pass
2136
2137 @abstractmethod
2138 def writable(self) -> bool:
2139 pass
2140
2141 @abstractmethod
2142 def write(self, s: AnyStr) -> int:
2143 pass
2144
2145 @abstractmethod
2146 def writelines(self, lines: List[AnyStr]) -> None:
2147 pass
2148
2149 @abstractmethod
2150 def __enter__(self) -> 'IO[AnyStr]':
2151 pass
2152
2153 @abstractmethod
2154 def __exit__(self, type, value, traceback) -> None:
2155 pass
2156
2157
2158class BinaryIO(IO[bytes]):
2159 """Typed version of the return of open() in binary mode."""
2160
Guido van Rossumd70fe632015-08-05 12:11:06 +02002161 __slots__ = ()
2162
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002163 @abstractmethod
2164 def write(self, s: Union[bytes, bytearray]) -> int:
2165 pass
2166
2167 @abstractmethod
2168 def __enter__(self) -> 'BinaryIO':
2169 pass
2170
2171
2172class TextIO(IO[str]):
2173 """Typed version of the return of open() in text mode."""
2174
Guido van Rossumd70fe632015-08-05 12:11:06 +02002175 __slots__ = ()
2176
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002177 @abstractproperty
2178 def buffer(self) -> BinaryIO:
2179 pass
2180
2181 @abstractproperty
2182 def encoding(self) -> str:
2183 pass
2184
2185 @abstractproperty
Guido van Rossum991d14f2016-11-09 13:12:51 -08002186 def errors(self) -> Optional[str]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002187 pass
2188
2189 @abstractproperty
2190 def line_buffering(self) -> bool:
2191 pass
2192
2193 @abstractproperty
2194 def newlines(self) -> Any:
2195 pass
2196
2197 @abstractmethod
2198 def __enter__(self) -> 'TextIO':
2199 pass
2200
2201
2202class io:
2203 """Wrapper namespace for IO generic classes."""
2204
2205 __all__ = ['IO', 'TextIO', 'BinaryIO']
2206 IO = IO
2207 TextIO = TextIO
2208 BinaryIO = BinaryIO
2209
2210io.__name__ = __name__ + '.io'
2211sys.modules[io.__name__] = io
2212
2213
2214Pattern = _TypeAlias('Pattern', AnyStr, type(stdlib_re.compile('')),
2215 lambda p: p.pattern)
2216Match = _TypeAlias('Match', AnyStr, type(stdlib_re.match('', '')),
2217 lambda m: m.re.pattern)
2218
2219
2220class re:
2221 """Wrapper namespace for re type aliases."""
2222
2223 __all__ = ['Pattern', 'Match']
2224 Pattern = Pattern
2225 Match = Match
2226
2227re.__name__ = __name__ + '.re'
2228sys.modules[re.__name__] = re