Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1 | import abc |
| 2 | from abc import abstractmethod, abstractproperty |
| 3 | import collections |
Brett Cannon | f3ad042 | 2016-04-15 10:51:30 -0700 | [diff] [blame] | 4 | import contextlib |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 5 | import functools |
| 6 | import re as stdlib_re # Avoid confusion with the re we export. |
| 7 | import sys |
| 8 | import types |
| 9 | try: |
| 10 | import collections.abc as collections_abc |
| 11 | except 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 Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 20 | 'ClassVar', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 21 | 'Generic', |
| 22 | 'Optional', |
Guido van Rossum | eb9aca3 | 2016-05-24 16:38:22 -0700 | [diff] [blame] | 23 | 'Tuple', |
| 24 | 'Type', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 25 | 'TypeVar', |
| 26 | 'Union', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 27 | |
| 28 | # ABCs (from collections.abc). |
| 29 | 'AbstractSet', # collections.abc.Set. |
Guido van Rossum | 83ec302 | 2017-01-17 20:43:28 -0800 | [diff] [blame] | 30 | 'GenericMeta', # subclass of abc.ABCMeta and a metaclass |
| 31 | # for 'Generic' and ABCs below. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 32 | '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 Rossum | 62fe1bb | 2016-10-29 16:05:26 -0700 | [diff] [blame] | 47 | # 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 Rossum | e9ed560 | 2017-01-18 13:10:31 -0800 | [diff] [blame] | 54 | # ContextManager, |
| 55 | # AsyncGenerator, |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 56 | |
| 57 | # Structural checks, a.k.a. protocols. |
| 58 | 'Reversible', |
| 59 | 'SupportsAbs', |
| 60 | 'SupportsFloat', |
| 61 | 'SupportsInt', |
| 62 | 'SupportsRound', |
| 63 | |
| 64 | # Concrete collection types. |
Raymond Hettinger | 8049052 | 2017-01-16 22:42:37 -0800 | [diff] [blame] | 65 | 'Deque', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 66 | 'Dict', |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 67 | 'DefaultDict', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 68 | 'List', |
| 69 | 'Set', |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 70 | 'FrozenSet', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 71 | 'NamedTuple', # Not really a type. |
| 72 | 'Generator', |
| 73 | |
| 74 | # One-off things. |
| 75 | 'AnyStr', |
| 76 | 'cast', |
| 77 | 'get_type_hints', |
Guido van Rossum | 91185fe | 2016-06-08 11:19:11 -0700 | [diff] [blame] | 78 | 'NewType', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 79 | 'no_type_check', |
| 80 | 'no_type_check_decorator', |
| 81 | 'overload', |
Guido van Rossum | 0e0563c | 2016-04-05 14:54:25 -0700 | [diff] [blame] | 82 | 'Text', |
Guido van Rossum | 91185fe | 2016-06-08 11:19:11 -0700 | [diff] [blame] | 83 | 'TYPE_CHECKING', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 84 | ] |
| 85 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 86 | # 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 90 | |
| 91 | def _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 Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 99 | def _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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 106 | class TypingMeta(type): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 107 | """Metaclass for most types defined in typing module |
| 108 | (not a part of public API). |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 109 | |
| 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 Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 113 | derived from TypingMeta must pass _root=True. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 114 | |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 115 | This also defines a dummy constructor (all the work for most typing |
| 116 | constructs is done in __new__) and a nicer repr(). |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 117 | """ |
| 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 Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 133 | For example, List['C'] is internally stored as |
| 134 | List[_ForwardRef('C')], which should evaluate to List[C], |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 135 | where C is an object found in globalns or localns (searching |
| 136 | localns first, of course). |
| 137 | """ |
| 138 | return self |
| 139 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 140 | def _get_type_vars(self, tvars): |
| 141 | pass |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 142 | |
| 143 | def __repr__(self): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 144 | qname = _trim_name(_qualname(self)) |
| 145 | return '%s.%s' % (self.__module__, qname) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 146 | |
| 147 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 148 | class _TypingBase(metaclass=TypingMeta, _root=True): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 149 | """Internal indicator of special typing constructs.""" |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 150 | |
Guido van Rossum | 83ec302 | 2017-01-17 20:43:28 -0800 | [diff] [blame] | 151 | __slots__ = ('__weakref__',) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 152 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 153 | 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 Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 167 | return super().__new__(cls) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 168 | |
| 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 | |
| 185 | class _FinalTypingBase(_TypingBase, _root=True): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 186 | """Internal mix-in class to prevent instantiation. |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 187 | |
| 188 | Prevents instantiation unless _root=True is given in class call. |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 189 | It is used to create pseudo-singleton instances Any, Union, Optional, etc. |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 190 | """ |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 191 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 192 | __slots__ = () |
| 193 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 194 | 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 199 | |
Guido van Rossum | b7dedc8 | 2016-10-29 12:44:29 -0700 | [diff] [blame] | 200 | def __reduce__(self): |
| 201 | return _trim_name(type(self).__name__) |
| 202 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 203 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 204 | class _ForwardRef(_TypingBase, _root=True): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 205 | """Internal wrapper to hold a forward reference.""" |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 206 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 207 | __slots__ = ('__forward_arg__', '__forward_code__', |
Guido van Rossum | c7b9295 | 2016-11-10 08:24:06 -0800 | [diff] [blame] | 208 | '__forward_evaluated__', '__forward_value__') |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 209 | |
| 210 | def __init__(self, arg): |
| 211 | super().__init__(arg) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 212 | if not isinstance(arg, str): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 213 | raise TypeError('Forward reference must be a string -- got %r' % (arg,)) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 214 | try: |
| 215 | code = compile(arg, '<string>', 'eval') |
| 216 | except SyntaxError: |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 217 | raise SyntaxError('Forward reference must be an expression -- got %r' % |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 218 | (arg,)) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 219 | self.__forward_arg__ = arg |
| 220 | self.__forward_code__ = code |
| 221 | self.__forward_evaluated__ = False |
| 222 | self.__forward_value__ = None |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 223 | |
| 224 | def _eval_type(self, globalns, localns): |
Guido van Rossum | dad1790 | 2016-11-10 08:29:18 -0800 | [diff] [blame] | 225 | if not self.__forward_evaluated__ or localns is not globalns: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 226 | 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 Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 238 | def __eq__(self, other): |
| 239 | if not isinstance(other, _ForwardRef): |
| 240 | return NotImplemented |
| 241 | return (self.__forward_arg__ == other.__forward_arg__ and |
Guido van Rossum | c7b9295 | 2016-11-10 08:24:06 -0800 | [diff] [blame] | 242 | self.__forward_value__ == other.__forward_value__) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 243 | |
| 244 | def __hash__(self): |
Guido van Rossum | c7b9295 | 2016-11-10 08:24:06 -0800 | [diff] [blame] | 245 | return hash((self.__forward_arg__, self.__forward_value__)) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 246 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 247 | def __instancecheck__(self, obj): |
| 248 | raise TypeError("Forward references cannot be used with isinstance().") |
| 249 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 250 | def __subclasscheck__(self, cls): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 251 | raise TypeError("Forward references cannot be used with issubclass().") |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 252 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 253 | def __repr__(self): |
| 254 | return '_ForwardRef(%r)' % (self.__forward_arg__,) |
| 255 | |
| 256 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 257 | class _TypeAlias(_TypingBase, _root=True): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 258 | """Internal helper class for defining generic variants of concrete types. |
| 259 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 260 | 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 264 | """ |
| 265 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 266 | __slots__ = ('name', 'type_var', 'impl_type', 'type_checker') |
| 267 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 268 | 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 280 | assert isinstance(impl_type, type), repr(impl_type) |
| 281 | assert not isinstance(impl_type, TypingMeta), repr(impl_type) |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 282 | assert isinstance(type_var, (type, _TypingBase)), repr(type_var) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 283 | 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 292 | if not isinstance(self.type_var, TypeVar): |
| 293 | raise TypeError("%s cannot be further parameterized." % self) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 294 | if self.type_var.__constraints__ and isinstance(parameter, type): |
| 295 | if not issubclass(parameter, self.type_var.__constraints__): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 296 | raise TypeError("%s is not a valid substitution for %s." % |
| 297 | (parameter, self.type_var)) |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 298 | if isinstance(parameter, TypeVar) and parameter is not self.type_var: |
| 299 | raise TypeError("%s cannot be re-parameterized." % self) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 300 | return self.__class__(self.name, parameter, |
| 301 | self.impl_type, self.type_checker) |
| 302 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 303 | 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 311 | def __instancecheck__(self, obj): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 312 | 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 316 | |
| 317 | def __subclasscheck__(self, cls): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 318 | 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 322 | |
| 323 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 324 | def _get_type_vars(types, tvars): |
| 325 | for t in types: |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 326 | if isinstance(t, TypingMeta) or isinstance(t, _TypingBase): |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 327 | t._get_type_vars(tvars) |
| 328 | |
| 329 | |
| 330 | def _type_vars(types): |
| 331 | tvars = [] |
| 332 | _get_type_vars(types, tvars) |
| 333 | return tuple(tvars) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 334 | |
| 335 | |
| 336 | def _eval_type(t, globalns, localns): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 337 | if isinstance(t, TypingMeta) or isinstance(t, _TypingBase): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 338 | return t._eval_type(globalns, localns) |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 339 | return t |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 340 | |
| 341 | |
| 342 | def _type_check(arg, msg): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 343 | """Check that the argument is a type, and return it (internal helper). |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 344 | |
| 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 Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 358 | if (isinstance(arg, _TypingBase) and type(arg).__name__ == '_ClassVar' or |
| 359 | not isinstance(arg, (type, _TypingBase)) and not callable(arg)): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 360 | raise TypeError(msg + " Got %.100r." % (arg,)) |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 361 | # 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 366 | return arg |
| 367 | |
| 368 | |
| 369 | def _type_repr(obj): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 370 | """Return the repr() of an object, special-casing types (internal helper). |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 371 | |
| 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 Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 380 | 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 386 | |
| 387 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 388 | class _Any(_FinalTypingBase, _root=True): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 389 | """Special type indicating an unconstrained type. |
| 390 | |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 391 | - 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 398 | """ |
| 399 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 400 | __slots__ = () |
| 401 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 402 | def __instancecheck__(self, obj): |
| 403 | raise TypeError("Any cannot be used with isinstance().") |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 404 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 405 | def __subclasscheck__(self, cls): |
| 406 | raise TypeError("Any cannot be used with issubclass().") |
| 407 | |
| 408 | |
| 409 | Any = _Any(_root=True) |
| 410 | |
| 411 | |
| 412 | class TypeVar(_TypingBase, _root=True): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 413 | """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 Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 425 | def repeat(x: T, n: int) -> List[T]: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 426 | '''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 Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 438 | At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 439 | |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 440 | 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 444 | |
| 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 Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 454 | __slots__ = ('__name__', '__bound__', '__constraints__', |
| 455 | '__covariant__', '__contravariant__') |
| 456 | |
| 457 | def __init__(self, name, *constraints, bound=None, |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 458 | covariant=False, contravariant=False): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 459 | super().__init__(name, *constraints, bound=bound, |
| 460 | covariant=covariant, contravariant=contravariant) |
| 461 | self.__name__ = name |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 462 | if covariant and contravariant: |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 463 | raise ValueError("Bivariant types are not supported.") |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 464 | 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 476 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 477 | def _get_type_vars(self, tvars): |
| 478 | if self not in tvars: |
| 479 | tvars.append(self) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 480 | |
| 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 Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 494 | raise TypeError("Type variables cannot be used with issubclass().") |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 495 | |
| 496 | |
| 497 | # Some unconstrained type variables. These are used by the container types. |
Guido van Rossum | eb9aca3 | 2016-05-24 16:38:22 -0700 | [diff] [blame] | 498 | # (These are not for export.) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 499 | T = TypeVar('T') # Any type. |
| 500 | KT = TypeVar('KT') # Key type. |
| 501 | VT = TypeVar('VT') # Value type. |
| 502 | T_co = TypeVar('T_co', covariant=True) # Any type covariant containers. |
| 503 | V_co = TypeVar('V_co', covariant=True) # Any type covariant containers. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 504 | VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers. |
| 505 | T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant. |
| 506 | |
| 507 | # A useful type variable with constraints. This represents string types. |
Guido van Rossum | eb9aca3 | 2016-05-24 16:38:22 -0700 | [diff] [blame] | 508 | # (This one *is* for export!) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 509 | AnyStr = TypeVar('AnyStr', bytes, str) |
| 510 | |
| 511 | |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 512 | def _replace_arg(arg, tvars, args): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 513 | """An internal helper function: replace arg if it is a type variable |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 514 | 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 Rossum | 83ec302 | 2017-01-17 20:43:28 -0800 | [diff] [blame] | 520 | if hasattr(arg, '_subs_tree') and isinstance(arg, (GenericMeta, _TypingBase)): |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 521 | 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 Rossum | 83ec302 | 2017-01-17 20:43:28 -0800 | [diff] [blame] | 529 | # 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 Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 539 | def _subs_tree(cls, tvars=None, args=None): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 540 | """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 Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 549 | """ |
| 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 | |
| 572 | def _remove_dups_flatten(parameters): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 573 | """An internal helper for Union creation and substitution: flatten Union's |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 574 | 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 | |
| 613 | def _check_generic(cls, parameters): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 614 | # Check correct count for parameters of a generic cls (internal helper). |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 615 | 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 Rossum | 9b10756 | 2016-11-09 13:23:04 -0800 | [diff] [blame] | 624 | _cleanups = [] |
| 625 | |
| 626 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 627 | def _tp_cache(func): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 628 | """Internal wrapper caching __getitem__ of generic types with a fallback to |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 629 | original function for non-hashable arguments. |
| 630 | """ |
| 631 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 632 | cached = functools.lru_cache()(func) |
Guido van Rossum | 9b10756 | 2016-11-09 13:23:04 -0800 | [diff] [blame] | 633 | _cleanups.append(cached.cache_clear) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 634 | @functools.wraps(func) |
| 635 | def inner(*args, **kwds): |
| 636 | try: |
| 637 | return cached(*args, **kwds) |
| 638 | except TypeError: |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 639 | pass # All real errors (not unhashable args) are raised below. |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 640 | return func(*args, **kwds) |
| 641 | return inner |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 642 | |
| 643 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 644 | class _Union(_FinalTypingBase, _root=True): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 645 | """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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 679 | - Similar for object:: |
| 680 | |
| 681 | Union[int, object] == object |
| 682 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 683 | - You cannot subclass or instantiate a union. |
| 684 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 685 | - You can use Optional[X] as a shorthand for Union[X, None]. |
| 686 | """ |
| 687 | |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 688 | __slots__ = ('__parameters__', '__args__', '__origin__', '__tree_hash__') |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 689 | |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 690 | 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 Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 697 | return self |
| 698 | if not isinstance(parameters, tuple): |
| 699 | raise TypeError("Expected parameters=<tuple>") |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 700 | 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 Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 715 | return self |
| 716 | |
| 717 | def _eval_type(self, globalns, localns): |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 718 | if self.__args__ is None: |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 719 | return self |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 720 | 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 Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 726 | |
| 727 | def _get_type_vars(self, tvars): |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 728 | if self.__origin__ and self.__parameters__: |
| 729 | _get_type_vars(self.__parameters__, tvars) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 730 | |
| 731 | def __repr__(self): |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 732 | 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 Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 738 | |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 739 | 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 Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 747 | |
| 748 | @_tp_cache |
| 749 | def __getitem__(self, parameters): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 750 | if parameters == (): |
| 751 | raise TypeError("Cannot take a Union of no types.") |
| 752 | if not isinstance(parameters, tuple): |
| 753 | parameters = (parameters,) |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 754 | 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 Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 771 | |
| 772 | def __eq__(self, other): |
Guido van Rossum | 83ec302 | 2017-01-17 20:43:28 -0800 | [diff] [blame] | 773 | if isinstance(other, _Union): |
| 774 | return self.__tree_hash__ == other.__tree_hash__ |
| 775 | elif self is not Union: |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 776 | return self._subs_tree() == other |
Guido van Rossum | 83ec302 | 2017-01-17 20:43:28 -0800 | [diff] [blame] | 777 | else: |
| 778 | return self is other |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 779 | |
| 780 | def __hash__(self): |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 781 | return self.__tree_hash__ |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 782 | |
| 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 788 | |
| 789 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 790 | Union = _Union(_root=True) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 791 | |
| 792 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 793 | class _Optional(_FinalTypingBase, _root=True): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 794 | """Optional type. |
| 795 | |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 796 | Optional[X] is equivalent to Union[X, None]. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 797 | """ |
| 798 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 799 | __slots__ = () |
| 800 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 801 | @_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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 805 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 806 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 807 | Optional = _Optional(_root=True) |
| 808 | |
| 809 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 810 | def _gorg(a): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 811 | """Return the farthest origin of a generic class (internal helper).""" |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 812 | assert isinstance(a, GenericMeta) |
| 813 | while a.__origin__ is not None: |
| 814 | a = a.__origin__ |
| 815 | return a |
| 816 | |
| 817 | |
| 818 | def _geqv(a, b): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 819 | """Return whether two generic classes are equivalent (internal helper). |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 820 | |
| 821 | The intention is to consider generic class X and any of its |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 822 | parameterized forms (X[T], X[int], etc.) as equivalent. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 823 | |
| 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 Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 833 | def _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 Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 847 | def _valid_for_check(cls): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 848 | """An internal helper to prohibit isinstance([1], List[str]) etc.""" |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 849 | 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 | |
| 858 | def _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 Rossum | 61f0a02 | 2016-11-29 09:46:21 -0800 | [diff] [blame] | 890 | def _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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 901 | class GenericMeta(TypingMeta, abc.ABCMeta): |
Guido van Rossum | 83ec302 | 2017-01-17 20:43:28 -0800 | [diff] [blame] | 902 | """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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 915 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 916 | def __new__(cls, name, bases, namespace, |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 917 | tvars=None, args=None, origin=None, extra=None, orig_bases=None): |
Guido van Rossum | 83ec302 | 2017-01-17 20:43:28 -0800 | [diff] [blame] | 918 | """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 Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 922 | 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 Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 962 | 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 Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 972 | self.__parameters__ = tvars |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 973 | # 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 Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 978 | self.__origin__ = origin |
Guido van Rossum | 1cea70f | 2016-05-18 08:35:00 -0700 | [diff] [blame] | 979 | self.__extra__ = extra |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 980 | # Speed hack (https://github.com/python/typing/issues/196). |
| 981 | self.__next_in_mro__ = _next_in_mro(self) |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 982 | # Preserve base classes on subclassing (__bases__ are type erased now). |
| 983 | if orig_bases is None: |
| 984 | self.__orig_bases__ = initial_bases |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 985 | |
| 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 Rossum | e259267 | 2016-10-08 20:27:22 -0700 | [diff] [blame] | 989 | 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 Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 993 | if isinstance(extra, abc.ABCMeta): |
| 994 | self._abc_registry = extra._abc_registry |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 995 | |
| 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 999 | return self |
| 1000 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1001 | def _get_type_vars(self, tvars): |
| 1002 | if self.__origin__ and self.__parameters__: |
| 1003 | _get_type_vars(self.__parameters__, tvars) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1004 | |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1005 | 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 Rossum | 61f0a02 | 2016-11-29 09:46:21 -0800 | [diff] [blame] | 1014 | _no_slots_copy(self.__dict__), |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1015 | 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1021 | def __repr__(self): |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 1022 | if self.__origin__ is None: |
| 1023 | return super().__repr__() |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1024 | return self._tree_repr(self._subs_tree()) |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 1025 | |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1026 | 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1042 | |
| 1043 | def __eq__(self, other): |
| 1044 | if not isinstance(other, GenericMeta): |
| 1045 | return NotImplemented |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1046 | if self.__origin__ is None or other.__origin__ is None: |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1047 | return self is other |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1048 | return self.__tree_hash__ == other.__tree_hash__ |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1049 | |
| 1050 | def __hash__(self): |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1051 | return self.__tree_hash__ |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1052 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1053 | @_tp_cache |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1054 | def __getitem__(self, params): |
| 1055 | if not isinstance(params, tuple): |
| 1056 | params = (params,) |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1057 | if not params and not _gorg(self) is Tuple: |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1058 | raise TypeError( |
| 1059 | "Parameter list to %s[...] cannot be empty" % _qualname(self)) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1060 | msg = "Parameters to generic types must be types." |
| 1061 | params = tuple(_type_check(p, msg) for p in params) |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1062 | 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 Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1067 | if len(set(params)) != len(params): |
Guido van Rossum | 1b66910 | 2015-09-04 12:15:54 -0700 | [diff] [blame] | 1068 | raise TypeError( |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1069 | "Parameters to Generic[...] must all be unique") |
| 1070 | tvars = params |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 1071 | args = params |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1072 | elif self in (Tuple, Callable): |
| 1073 | tvars = _type_vars(params) |
| 1074 | args = params |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1075 | elif self is _Protocol: |
| 1076 | # _Protocol is internal, don't check anything. |
| 1077 | tvars = params |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 1078 | args = params |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1079 | 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1083 | else: |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1084 | # Subscripting a regular Generic subclass. |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1085 | _check_generic(self, params) |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1086 | tvars = _type_vars(params) |
| 1087 | args = params |
| 1088 | return self.__class__(self.__name__, |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 1089 | self.__bases__, |
Guido van Rossum | 61f0a02 | 2016-11-29 09:46:21 -0800 | [diff] [blame] | 1090 | _no_slots_copy(self.__dict__), |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1091 | tvars=tvars, |
| 1092 | args=args, |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1093 | origin=self, |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 1094 | extra=self.__extra__, |
| 1095 | orig_bases=self.__orig_bases__) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1096 | |
Guido van Rossum | 1b66910 | 2015-09-04 12:15:54 -0700 | [diff] [blame] | 1097 | 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 Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 1103 | return issubclass(instance.__class__, self) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1104 | |
Guido van Rossum | b7dedc8 | 2016-10-29 12:44:29 -0700 | [diff] [blame] | 1105 | def __copy__(self): |
Guido van Rossum | 61f0a02 | 2016-11-29 09:46:21 -0800 | [diff] [blame] | 1106 | return self.__class__(self.__name__, self.__bases__, |
| 1107 | _no_slots_copy(self.__dict__), |
Guido van Rossum | b7dedc8 | 2016-10-29 12:44:29 -0700 | [diff] [blame] | 1108 | self.__parameters__, self.__args__, self.__origin__, |
| 1109 | self.__extra__, self.__orig_bases__) |
| 1110 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1111 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1112 | # Prevent checks for Generic to crash when defining Generic. |
| 1113 | Generic = None |
| 1114 | |
| 1115 | |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1116 | def _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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1132 | class Generic(metaclass=GenericMeta): |
| 1133 | """Abstract base class for generic types. |
| 1134 | |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 1135 | A generic type is typically declared by inheriting from |
| 1136 | this class parameterized with one or more type variables. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1137 | 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 Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1146 | def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1147 | try: |
| 1148 | return mapping[key] |
| 1149 | except KeyError: |
| 1150 | return default |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1151 | """ |
| 1152 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1153 | __slots__ = () |
| 1154 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1155 | def __new__(cls, *args, **kwds): |
Guido van Rossum | 62fe1bb | 2016-10-29 16:05:26 -0700 | [diff] [blame] | 1156 | if _geqv(cls, Generic): |
| 1157 | raise TypeError("Type Generic cannot be instantiated; " |
| 1158 | "it can be used only as a base class") |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1159 | return _generic_new(cls.__next_in_mro__, cls, *args, **kwds) |
| 1160 | |
| 1161 | |
| 1162 | class _TypingEmpty: |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 1163 | """Internal placeholder for () or []. Used by TupleMeta and CallableMeta |
| 1164 | to allow empty list/tuple in specific places, without allowing them |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1165 | to sneak in where prohibited. |
| 1166 | """ |
| 1167 | |
| 1168 | |
| 1169 | class _TypingEllipsis: |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 1170 | """Internal placeholder for ... (ellipsis).""" |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1171 | |
| 1172 | |
| 1173 | class TupleMeta(GenericMeta): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 1174 | """Metaclass for Tuple (internal).""" |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1175 | |
| 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 | |
| 1207 | class 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 | |
| 1226 | class CallableMeta(GenericMeta): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 1227 | """Metaclass for Callable (internal).""" |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1228 | |
| 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 Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1241 | if not isinstance(arg, tuple): |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1242 | arg_list.append(_type_repr(arg)) |
| 1243 | else: |
| 1244 | arg_list.append(arg[0]._tree_repr(arg)) |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1245 | if arg_list[0] == '...': |
| 1246 | return repr(tree[0]) + '[..., %s]' % arg_list[1] |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1247 | return (repr(tree[0]) + |
| 1248 | '[[%s], %s]' % (', '.join(arg_list[:-1]), arg_list[-1])) |
| 1249 | |
| 1250 | def __getitem__(self, parameters): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 1251 | """A thin wrapper around __getitem_inner__ to provide the latter |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1252 | 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 Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1261 | if args is Ellipsis: |
| 1262 | parameters = (Ellipsis, result) |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1263 | else: |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1264 | if not isinstance(args, list): |
| 1265 | raise TypeError("Callable[args, result]: args must be a list." |
| 1266 | " Got %.100r." % (args,)) |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1267 | parameters = (tuple(args), result) |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1268 | return self.__getitem_inner__(parameters) |
| 1269 | |
| 1270 | @_tp_cache |
| 1271 | def __getitem_inner__(self, parameters): |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1272 | args, result = parameters |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1273 | msg = "Callable[args, result]: result must be a type." |
| 1274 | result = _type_check(result, msg) |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1275 | if args is Ellipsis: |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1276 | return super().__getitem__((_TypingEllipsis, result)) |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1277 | 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 | |
| 1283 | class 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 Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 1288 | must be a list of types or ellipsis; the return type must be a single type. |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1289 | |
| 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1301 | |
| 1302 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1303 | class _ClassVar(_FinalTypingBase, _root=True): |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1304 | """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 Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1320 | __slots__ = ('__type__',) |
| 1321 | |
| 1322 | def __init__(self, tp=None, **kwds): |
| 1323 | self.__type__ = tp |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1324 | |
| 1325 | def __getitem__(self, item): |
| 1326 | cls = type(self) |
| 1327 | if self.__type__ is None: |
| 1328 | return cls(_type_check(item, |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1329 | '{} accepts only single type.'.format(cls.__name__[1:])), |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1330 | _root=True) |
| 1331 | raise TypeError('{} cannot be further subscripted' |
| 1332 | .format(cls.__name__[1:])) |
| 1333 | |
| 1334 | def _eval_type(self, globalns, localns): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1335 | 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 Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1339 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1340 | def __repr__(self): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1341 | r = super().__repr__() |
| 1342 | if self.__type__ is not None: |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1343 | r += '[{}]'.format(_type_repr(self.__type__)) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1344 | return r |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1345 | |
| 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 Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1356 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1357 | ClassVar = _ClassVar(_root=True) |
| 1358 | |
| 1359 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1360 | def 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 | |
| 1371 | def _get_defaults(func): |
| 1372 | """Internal helper to extract the default arguments, by name.""" |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1373 | try: |
| 1374 | code = func.__code__ |
| 1375 | except AttributeError: |
| 1376 | # Some built-in functions don't have __code__, __defaults__, etc. |
| 1377 | return {} |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1378 | pos_count = code.co_argcount |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1379 | arg_names = code.co_varnames |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1380 | 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 Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1391 | def get_type_hints(obj, globalns=None, localns=None): |
| 1392 | """Return type hints for an object. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1393 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1394 | 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1397 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1398 | 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1401 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1402 | 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1405 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1406 | 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1409 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1410 | - 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 Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1413 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1414 | - If one dict argument is passed, it is used for both globals and |
| 1415 | locals. |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1416 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1417 | - If two dict arguments are passed, they specify globals and |
| 1418 | locals, respectively. |
| 1419 | """ |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1420 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1421 | 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1426 | localns = globalns |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1427 | 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 Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1445 | if (isinstance(obj, types.FunctionType) or |
| 1446 | isinstance(obj, types.BuiltinFunctionType) or |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1447 | isinstance(obj, types.MethodType) or |
| 1448 | isinstance(obj, types.ModuleType)): |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1449 | return {} |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1450 | 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1465 | |
| 1466 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1467 | def 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 Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1471 | applies recursively to all methods and classes defined in that class |
| 1472 | (but not to methods defined in its superclasses or subclasses). |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1473 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1474 | This mutates the function(s) or class(es) in place. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1475 | """ |
| 1476 | if isinstance(arg, type): |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1477 | 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1482 | if isinstance(obj, types.FunctionType): |
| 1483 | obj.__no_type_check__ = True |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1484 | if isinstance(obj, type): |
| 1485 | no_type_check(obj) |
| 1486 | try: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1487 | arg.__no_type_check__ = True |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1488 | except TypeError: # built-in classes |
| 1489 | pass |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1490 | return arg |
| 1491 | |
| 1492 | |
| 1493 | def 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 Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1509 | def _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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1518 | def overload(func): |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1519 | """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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1545 | |
| 1546 | |
| 1547 | class _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 Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1554 | def __instancecheck__(self, obj): |
Guido van Rossum | ca4b252 | 2016-11-19 10:32:41 -0800 | [diff] [blame] | 1555 | if _Protocol not in self.__bases__: |
| 1556 | return super().__instancecheck__(obj) |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1557 | raise TypeError("Protocols cannot be used with isinstance().") |
| 1558 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1559 | 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 Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1594 | attr != '__abstractmethods__' and |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1595 | attr != '__annotations__' and |
| 1596 | attr != '__weakref__' and |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1597 | 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 Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 1605 | attr != '__orig_bases__' and |
Guido van Rossum | 1cea70f | 2016-05-18 08:35:00 -0700 | [diff] [blame] | 1606 | attr != '__extra__' and |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1607 | attr != '__tree_hash__' and |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1608 | attr != '__module__'): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1609 | attrs.add(attr) |
| 1610 | |
| 1611 | return attrs |
| 1612 | |
| 1613 | |
| 1614 | class _Protocol(metaclass=_ProtocolMeta): |
| 1615 | """Internal base class for protocol classes. |
| 1616 | |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 1617 | This implements a simple-minded structural issubclass check |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1618 | (similar but more general than the one-offs in collections.abc |
| 1619 | such as Hashable). |
| 1620 | """ |
| 1621 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1622 | __slots__ = () |
| 1623 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1624 | _is_protocol = True |
| 1625 | |
| 1626 | |
| 1627 | # Various ABCs mimicking those in collections.abc. |
| 1628 | # A few are simply re-exported for completeness. |
| 1629 | |
| 1630 | Hashable = collections_abc.Hashable # Not generic. |
| 1631 | |
| 1632 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1633 | if hasattr(collections_abc, 'Awaitable'): |
| 1634 | class Awaitable(Generic[T_co], extra=collections_abc.Awaitable): |
| 1635 | __slots__ = () |
Guido van Rossum | 62fe1bb | 2016-10-29 16:05:26 -0700 | [diff] [blame] | 1636 | |
| 1637 | __all__.append('Awaitable') |
| 1638 | |
| 1639 | |
| 1640 | if 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 Rossum | f17c200 | 2015-12-03 17:31:24 -0800 | [diff] [blame] | 1646 | |
| 1647 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1648 | if hasattr(collections_abc, 'AsyncIterable'): |
Guido van Rossum | f17c200 | 2015-12-03 17:31:24 -0800 | [diff] [blame] | 1649 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1650 | class AsyncIterable(Generic[T_co], extra=collections_abc.AsyncIterable): |
| 1651 | __slots__ = () |
Guido van Rossum | f17c200 | 2015-12-03 17:31:24 -0800 | [diff] [blame] | 1652 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1653 | class AsyncIterator(AsyncIterable[T_co], |
| 1654 | extra=collections_abc.AsyncIterator): |
| 1655 | __slots__ = () |
| 1656 | |
Guido van Rossum | 62fe1bb | 2016-10-29 16:05:26 -0700 | [diff] [blame] | 1657 | __all__.append('AsyncIterable') |
| 1658 | __all__.append('AsyncIterator') |
Guido van Rossum | f17c200 | 2015-12-03 17:31:24 -0800 | [diff] [blame] | 1659 | |
| 1660 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1661 | class Iterable(Generic[T_co], extra=collections_abc.Iterable): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1662 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1663 | |
| 1664 | |
| 1665 | class Iterator(Iterable[T_co], extra=collections_abc.Iterator): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1666 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1667 | |
| 1668 | |
| 1669 | class SupportsInt(_Protocol): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1670 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1671 | |
| 1672 | @abstractmethod |
| 1673 | def __int__(self) -> int: |
| 1674 | pass |
| 1675 | |
| 1676 | |
| 1677 | class SupportsFloat(_Protocol): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1678 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1679 | |
| 1680 | @abstractmethod |
| 1681 | def __float__(self) -> float: |
| 1682 | pass |
| 1683 | |
| 1684 | |
| 1685 | class SupportsComplex(_Protocol): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1686 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1687 | |
| 1688 | @abstractmethod |
| 1689 | def __complex__(self) -> complex: |
| 1690 | pass |
| 1691 | |
| 1692 | |
| 1693 | class SupportsBytes(_Protocol): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1694 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1695 | |
| 1696 | @abstractmethod |
| 1697 | def __bytes__(self) -> bytes: |
| 1698 | pass |
| 1699 | |
| 1700 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1701 | class SupportsAbs(_Protocol[T_co]): |
| 1702 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1703 | |
| 1704 | @abstractmethod |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1705 | def __abs__(self) -> T_co: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1706 | pass |
| 1707 | |
| 1708 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1709 | class SupportsRound(_Protocol[T_co]): |
| 1710 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1711 | |
| 1712 | @abstractmethod |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1713 | def __round__(self, ndigits: int = 0) -> T_co: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1714 | pass |
| 1715 | |
| 1716 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1717 | if hasattr(collections_abc, 'Reversible'): |
| 1718 | class Reversible(Iterable[T_co], extra=collections_abc.Reversible): |
| 1719 | __slots__ = () |
| 1720 | else: |
| 1721 | class Reversible(_Protocol[T_co]): |
| 1722 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1723 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1724 | @abstractmethod |
| 1725 | def __reversed__(self) -> 'Iterator[T_co]': |
| 1726 | pass |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1727 | |
| 1728 | |
| 1729 | Sized = collections_abc.Sized # Not generic. |
| 1730 | |
| 1731 | |
| 1732 | class Container(Generic[T_co], extra=collections_abc.Container): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1733 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1734 | |
| 1735 | |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1736 | if 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1744 | # Callable was defined earlier. |
| 1745 | |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1746 | if hasattr(collections_abc, 'Collection'): |
| 1747 | class AbstractSet(Collection[T_co], |
| 1748 | extra=collections_abc.Set): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1749 | __slots__ = () |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1750 | else: |
| 1751 | class AbstractSet(Sized, Iterable[T_co], Container[T_co], |
| 1752 | extra=collections_abc.Set): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1753 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1754 | |
| 1755 | |
| 1756 | class MutableSet(AbstractSet[T], extra=collections_abc.MutableSet): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1757 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1758 | |
| 1759 | |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1760 | # NOTE: It is only covariant in the value type. |
| 1761 | if hasattr(collections_abc, 'Collection'): |
| 1762 | class Mapping(Collection[KT], Generic[KT, VT_co], |
| 1763 | extra=collections_abc.Mapping): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1764 | __slots__ = () |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1765 | else: |
| 1766 | class Mapping(Sized, Iterable[KT], Container[KT], Generic[KT, VT_co], |
| 1767 | extra=collections_abc.Mapping): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1768 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1769 | |
| 1770 | |
| 1771 | class MutableMapping(Mapping[KT, VT], extra=collections_abc.MutableMapping): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1772 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1773 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1774 | if hasattr(collections_abc, 'Reversible'): |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1775 | if hasattr(collections_abc, 'Collection'): |
| 1776 | class Sequence(Reversible[T_co], Collection[T_co], |
| 1777 | extra=collections_abc.Sequence): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1778 | __slots__ = () |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1779 | else: |
| 1780 | class Sequence(Sized, Reversible[T_co], Container[T_co], |
| 1781 | extra=collections_abc.Sequence): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1782 | __slots__ = () |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1783 | else: |
| 1784 | class Sequence(Sized, Iterable[T_co], Container[T_co], |
| 1785 | extra=collections_abc.Sequence): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1786 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1787 | |
| 1788 | |
| 1789 | class MutableSequence(Sequence[T], extra=collections_abc.MutableSequence): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1790 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1791 | |
| 1792 | |
| 1793 | class ByteString(Sequence[int], extra=collections_abc.ByteString): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1794 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1795 | |
| 1796 | |
Guido van Rossum | 1cea70f | 2016-05-18 08:35:00 -0700 | [diff] [blame] | 1797 | class List(list, MutableSequence[T], extra=list): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1798 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1799 | __slots__ = () |
| 1800 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1801 | def __new__(cls, *args, **kwds): |
| 1802 | if _geqv(cls, List): |
| 1803 | raise TypeError("Type List cannot be instantiated; " |
| 1804 | "use list() instead") |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1805 | return _generic_new(list, cls, *args, **kwds) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1806 | |
Raymond Hettinger | 8049052 | 2017-01-16 22:42:37 -0800 | [diff] [blame] | 1807 | class 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1816 | |
Guido van Rossum | 1cea70f | 2016-05-18 08:35:00 -0700 | [diff] [blame] | 1817 | class Set(set, MutableSet[T], extra=set): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1818 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1819 | __slots__ = () |
| 1820 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1821 | def __new__(cls, *args, **kwds): |
| 1822 | if _geqv(cls, Set): |
| 1823 | raise TypeError("Type Set cannot be instantiated; " |
| 1824 | "use set() instead") |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1825 | return _generic_new(set, cls, *args, **kwds) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1826 | |
| 1827 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1828 | class FrozenSet(frozenset, AbstractSet[T_co], extra=frozenset): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1829 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1830 | |
| 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 Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1835 | return _generic_new(frozenset, cls, *args, **kwds) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1836 | |
| 1837 | |
| 1838 | class MappingView(Sized, Iterable[T_co], extra=collections_abc.MappingView): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1839 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1840 | |
| 1841 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1842 | class KeysView(MappingView[KT], AbstractSet[KT], |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1843 | extra=collections_abc.KeysView): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1844 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1845 | |
| 1846 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1847 | class ItemsView(MappingView[Tuple[KT, VT_co]], |
Guido van Rossum | 0e0563c | 2016-04-05 14:54:25 -0700 | [diff] [blame] | 1848 | AbstractSet[Tuple[KT, VT_co]], |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1849 | Generic[KT, VT_co], |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1850 | extra=collections_abc.ItemsView): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1851 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1852 | |
| 1853 | |
| 1854 | class ValuesView(MappingView[VT_co], extra=collections_abc.ValuesView): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1855 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1856 | |
| 1857 | |
Brett Cannon | f3ad042 | 2016-04-15 10:51:30 -0700 | [diff] [blame] | 1858 | if hasattr(contextlib, 'AbstractContextManager'): |
| 1859 | class ContextManager(Generic[T_co], extra=contextlib.AbstractContextManager): |
| 1860 | __slots__ = () |
| 1861 | __all__.append('ContextManager') |
| 1862 | |
| 1863 | |
Guido van Rossum | 1cea70f | 2016-05-18 08:35:00 -0700 | [diff] [blame] | 1864 | class Dict(dict, MutableMapping[KT, VT], extra=dict): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1865 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1866 | __slots__ = () |
| 1867 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1868 | def __new__(cls, *args, **kwds): |
| 1869 | if _geqv(cls, Dict): |
| 1870 | raise TypeError("Type Dict cannot be instantiated; " |
| 1871 | "use dict() instead") |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1872 | return _generic_new(dict, cls, *args, **kwds) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1873 | |
Guido van Rossum | 1cea70f | 2016-05-18 08:35:00 -0700 | [diff] [blame] | 1874 | class DefaultDict(collections.defaultdict, MutableMapping[KT, VT], |
| 1875 | extra=collections.defaultdict): |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1876 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1877 | __slots__ = () |
| 1878 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1879 | 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 Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1883 | return _generic_new(collections.defaultdict, cls, *args, **kwds) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1884 | |
| 1885 | # Determine what base class to use for Generator. |
| 1886 | if hasattr(collections_abc, 'Generator'): |
| 1887 | # Sufficiently recent versions of 3.5 have a Generator ABC. |
| 1888 | _G_base = collections_abc.Generator |
| 1889 | else: |
| 1890 | # Fall back on the exact type. |
| 1891 | _G_base = types.GeneratorType |
| 1892 | |
| 1893 | |
| 1894 | class Generator(Iterator[T_co], Generic[T_co, T_contra, V_co], |
| 1895 | extra=_G_base): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1896 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1897 | |
| 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 Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1902 | return _generic_new(_G_base, cls, *args, **kwds) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1903 | |
Guido van Rossum | e9ed560 | 2017-01-18 13:10:31 -0800 | [diff] [blame] | 1904 | if 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 Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1911 | |
Guido van Rossum | eb9aca3 | 2016-05-24 16:38:22 -0700 | [diff] [blame] | 1912 | # Internal type variable used for Type[]. |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1913 | CT_co = TypeVar('CT_co', covariant=True, bound=type) |
Guido van Rossum | eb9aca3 | 2016-05-24 16:38:22 -0700 | [diff] [blame] | 1914 | |
| 1915 | |
Guido van Rossum | b22c708 | 2016-05-26 09:56:19 -0700 | [diff] [blame] | 1916 | # This is not a real generic class. Don't use outside annotations. |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1917 | class Type(Generic[CT_co], extra=type): |
Guido van Rossum | b22c708 | 2016-05-26 09:56:19 -0700 | [diff] [blame] | 1918 | """A special construct usable to annotate class objects. |
Guido van Rossum | eb9aca3 | 2016-05-24 16:38:22 -0700 | [diff] [blame] | 1919 | |
| 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 Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1941 | __slots__ = () |
| 1942 | |
Guido van Rossum | eb9aca3 | 2016-05-24 16:38:22 -0700 | [diff] [blame] | 1943 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1944 | def _make_nmtuple(name, types): |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 1945 | 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 Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1947 | nm_tpl = collections.namedtuple(name, [n for n, t in types]) |
Guido van Rossum | 83ec302 | 2017-01-17 20:43:28 -0800 | [diff] [blame] | 1948 | # 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 Rossum | 557d1eb | 2015-11-19 08:16:31 -0800 | [diff] [blame] | 1951 | try: |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1952 | nm_tpl.__module__ = sys._getframe(2).f_globals.get('__name__', '__main__') |
Guido van Rossum | 557d1eb | 2015-11-19 08:16:31 -0800 | [diff] [blame] | 1953 | except (AttributeError, ValueError): |
| 1954 | pass |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1955 | return nm_tpl |
| 1956 | |
| 1957 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 1958 | _PY36 = sys.version_info[:2] >= (3, 6) |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1959 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1960 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 1961 | class NamedTupleMeta(type): |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1962 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 1963 | 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 Rossum | 3c268be | 2017-01-18 08:03:50 -0800 | [diff] [blame] | 1970 | 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 Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1986 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 1987 | class NamedTuple(metaclass=NamedTupleMeta): |
| 1988 | """Typed version of namedtuple. |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1989 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 1990 | Usage in Python versions >= 3.6:: |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1991 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 1992 | class Employee(NamedTuple): |
| 1993 | name: str |
| 1994 | id: int |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1995 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 1996 | This is equivalent to:: |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1997 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 1998 | Employee = collections.namedtuple('Employee', ['name', 'id']) |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1999 | |
Guido van Rossum | 83ec302 | 2017-01-17 20:43:28 -0800 | [diff] [blame] | 2000 | 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 Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2004 | are in the _fields attribute, which is part of the namedtuple |
| 2005 | API.) Alternative equivalent keyword syntax is also accepted:: |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2006 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2007 | Employee = NamedTuple('Employee', name=str, id=int) |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2008 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2009 | In Python versions <= 3.5 use:: |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2010 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2011 | Employee = NamedTuple('Employee', [('name', str), ('id', int)]) |
| 2012 | """ |
| 2013 | _root = True |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2014 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2015 | 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 Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2024 | return _make_nmtuple(typename, fields) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2025 | |
| 2026 | |
Guido van Rossum | 91185fe | 2016-06-08 11:19:11 -0700 | [diff] [blame] | 2027 | def 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 Rossum | 0e0563c | 2016-04-05 14:54:25 -0700 | [diff] [blame] | 2054 | # Python-version-specific alias (Python 2: unicode; Python 3: str) |
| 2055 | Text = str |
| 2056 | |
| 2057 | |
Guido van Rossum | 91185fe | 2016-06-08 11:19:11 -0700 | [diff] [blame] | 2058 | # Constant that's True when type checking, but False here. |
| 2059 | TYPE_CHECKING = False |
| 2060 | |
| 2061 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2062 | class 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 Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 2075 | __slots__ = () |
| 2076 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2077 | @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 | |
| 2158 | class BinaryIO(IO[bytes]): |
| 2159 | """Typed version of the return of open() in binary mode.""" |
| 2160 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 2161 | __slots__ = () |
| 2162 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2163 | @abstractmethod |
| 2164 | def write(self, s: Union[bytes, bytearray]) -> int: |
| 2165 | pass |
| 2166 | |
| 2167 | @abstractmethod |
| 2168 | def __enter__(self) -> 'BinaryIO': |
| 2169 | pass |
| 2170 | |
| 2171 | |
| 2172 | class TextIO(IO[str]): |
| 2173 | """Typed version of the return of open() in text mode.""" |
| 2174 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 2175 | __slots__ = () |
| 2176 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2177 | @abstractproperty |
| 2178 | def buffer(self) -> BinaryIO: |
| 2179 | pass |
| 2180 | |
| 2181 | @abstractproperty |
| 2182 | def encoding(self) -> str: |
| 2183 | pass |
| 2184 | |
| 2185 | @abstractproperty |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 2186 | def errors(self) -> Optional[str]: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2187 | 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 | |
| 2202 | class io: |
| 2203 | """Wrapper namespace for IO generic classes.""" |
| 2204 | |
| 2205 | __all__ = ['IO', 'TextIO', 'BinaryIO'] |
| 2206 | IO = IO |
| 2207 | TextIO = TextIO |
| 2208 | BinaryIO = BinaryIO |
| 2209 | |
| 2210 | io.__name__ = __name__ + '.io' |
| 2211 | sys.modules[io.__name__] = io |
| 2212 | |
| 2213 | |
| 2214 | Pattern = _TypeAlias('Pattern', AnyStr, type(stdlib_re.compile('')), |
| 2215 | lambda p: p.pattern) |
| 2216 | Match = _TypeAlias('Match', AnyStr, type(stdlib_re.match('', '')), |
| 2217 | lambda m: m.re.pattern) |
| 2218 | |
| 2219 | |
| 2220 | class re: |
| 2221 | """Wrapper namespace for re type aliases.""" |
| 2222 | |
| 2223 | __all__ = ['Pattern', 'Match'] |
| 2224 | Pattern = Pattern |
| 2225 | Match = Match |
| 2226 | |
| 2227 | re.__name__ = __name__ + '.re' |
| 2228 | sys.modules[re.__name__] = re |