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. |
Mariatta | 0230e64 | 2017-02-14 06:11:12 -0800 | [diff] [blame] | 13 | try: |
| 14 | from types import SlotWrapperType, MethodWrapperType, MethodDescriptorType |
| 15 | except ImportError: |
| 16 | SlotWrapperType = type(object.__init__) |
| 17 | MethodWrapperType = type(object().__str__) |
| 18 | MethodDescriptorType = type(str.join) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 19 | |
| 20 | |
| 21 | # Please keep __all__ alphabetized within each category. |
| 22 | __all__ = [ |
| 23 | # Super-special typing primitives. |
| 24 | 'Any', |
| 25 | 'Callable', |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 26 | 'ClassVar', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 27 | 'Generic', |
| 28 | 'Optional', |
Guido van Rossum | eb9aca3 | 2016-05-24 16:38:22 -0700 | [diff] [blame] | 29 | 'Tuple', |
| 30 | 'Type', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 31 | 'TypeVar', |
| 32 | 'Union', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 33 | |
| 34 | # ABCs (from collections.abc). |
| 35 | 'AbstractSet', # collections.abc.Set. |
Guido van Rossum | 83ec302 | 2017-01-17 20:43:28 -0800 | [diff] [blame] | 36 | 'GenericMeta', # subclass of abc.ABCMeta and a metaclass |
| 37 | # for 'Generic' and ABCs below. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 38 | 'ByteString', |
| 39 | 'Container', |
| 40 | 'Hashable', |
| 41 | 'ItemsView', |
| 42 | 'Iterable', |
| 43 | 'Iterator', |
| 44 | 'KeysView', |
| 45 | 'Mapping', |
| 46 | 'MappingView', |
| 47 | 'MutableMapping', |
| 48 | 'MutableSequence', |
| 49 | 'MutableSet', |
| 50 | 'Sequence', |
| 51 | 'Sized', |
| 52 | 'ValuesView', |
Guido van Rossum | 62fe1bb | 2016-10-29 16:05:26 -0700 | [diff] [blame] | 53 | # The following are added depending on presence |
| 54 | # of their non-generic counterparts in stdlib: |
| 55 | # Awaitable, |
| 56 | # AsyncIterator, |
| 57 | # AsyncIterable, |
| 58 | # Coroutine, |
| 59 | # Collection, |
Guido van Rossum | e9ed560 | 2017-01-18 13:10:31 -0800 | [diff] [blame] | 60 | # ContextManager, |
| 61 | # AsyncGenerator, |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 62 | |
| 63 | # Structural checks, a.k.a. protocols. |
| 64 | 'Reversible', |
| 65 | 'SupportsAbs', |
| 66 | 'SupportsFloat', |
| 67 | 'SupportsInt', |
| 68 | 'SupportsRound', |
| 69 | |
| 70 | # Concrete collection types. |
Mariatta | 0230e64 | 2017-02-14 06:11:12 -0800 | [diff] [blame] | 71 | 'Counter', |
Raymond Hettinger | 8049052 | 2017-01-16 22:42:37 -0800 | [diff] [blame] | 72 | 'Deque', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 73 | 'Dict', |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 74 | 'DefaultDict', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 75 | 'List', |
| 76 | 'Set', |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 77 | 'FrozenSet', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 78 | 'NamedTuple', # Not really a type. |
| 79 | 'Generator', |
| 80 | |
| 81 | # One-off things. |
| 82 | 'AnyStr', |
| 83 | 'cast', |
| 84 | 'get_type_hints', |
Guido van Rossum | 91185fe | 2016-06-08 11:19:11 -0700 | [diff] [blame] | 85 | 'NewType', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 86 | 'no_type_check', |
| 87 | 'no_type_check_decorator', |
| 88 | 'overload', |
Guido van Rossum | 0e0563c | 2016-04-05 14:54:25 -0700 | [diff] [blame] | 89 | 'Text', |
Guido van Rossum | 91185fe | 2016-06-08 11:19:11 -0700 | [diff] [blame] | 90 | 'TYPE_CHECKING', |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 91 | ] |
| 92 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 93 | # The pseudo-submodules 're' and 'io' are part of the public |
| 94 | # namespace, but excluded from __all__ because they might stomp on |
| 95 | # legitimate imports of those modules. |
| 96 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 97 | |
| 98 | def _qualname(x): |
| 99 | if sys.version_info[:2] >= (3, 3): |
| 100 | return x.__qualname__ |
| 101 | else: |
| 102 | # Fall back to just name. |
| 103 | return x.__name__ |
| 104 | |
| 105 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 106 | def _trim_name(nm): |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 107 | whitelist = ('_TypeAlias', '_ForwardRef', '_TypingBase', '_FinalTypingBase') |
| 108 | if nm.startswith('_') and nm not in whitelist: |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 109 | nm = nm[1:] |
| 110 | return nm |
| 111 | |
| 112 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 113 | class TypingMeta(type): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 114 | """Metaclass for most types defined in typing module |
| 115 | (not a part of public API). |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 116 | |
| 117 | This overrides __new__() to require an extra keyword parameter |
| 118 | '_root', which serves as a guard against naive subclassing of the |
| 119 | typing classes. Any legitimate class defined using a metaclass |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 120 | derived from TypingMeta must pass _root=True. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 121 | |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 122 | This also defines a dummy constructor (all the work for most typing |
| 123 | constructs is done in __new__) and a nicer repr(). |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 124 | """ |
| 125 | |
| 126 | _is_protocol = False |
| 127 | |
| 128 | def __new__(cls, name, bases, namespace, *, _root=False): |
| 129 | if not _root: |
| 130 | raise TypeError("Cannot subclass %s" % |
| 131 | (', '.join(map(_type_repr, bases)) or '()')) |
| 132 | return super().__new__(cls, name, bases, namespace) |
| 133 | |
| 134 | def __init__(self, *args, **kwds): |
| 135 | pass |
| 136 | |
| 137 | def _eval_type(self, globalns, localns): |
| 138 | """Override this in subclasses to interpret forward references. |
| 139 | |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 140 | For example, List['C'] is internally stored as |
| 141 | List[_ForwardRef('C')], which should evaluate to List[C], |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 142 | where C is an object found in globalns or localns (searching |
| 143 | localns first, of course). |
| 144 | """ |
| 145 | return self |
| 146 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 147 | def _get_type_vars(self, tvars): |
| 148 | pass |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 149 | |
| 150 | def __repr__(self): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 151 | qname = _trim_name(_qualname(self)) |
| 152 | return '%s.%s' % (self.__module__, qname) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 153 | |
| 154 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 155 | class _TypingBase(metaclass=TypingMeta, _root=True): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 156 | """Internal indicator of special typing constructs.""" |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 157 | |
Guido van Rossum | 83ec302 | 2017-01-17 20:43:28 -0800 | [diff] [blame] | 158 | __slots__ = ('__weakref__',) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 159 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 160 | def __init__(self, *args, **kwds): |
| 161 | pass |
| 162 | |
| 163 | def __new__(cls, *args, **kwds): |
| 164 | """Constructor. |
| 165 | |
| 166 | This only exists to give a better error message in case |
| 167 | someone tries to subclass a special typing object (not a good idea). |
| 168 | """ |
| 169 | if (len(args) == 3 and |
| 170 | isinstance(args[0], str) and |
| 171 | isinstance(args[1], tuple)): |
| 172 | # Close enough. |
| 173 | raise TypeError("Cannot subclass %r" % cls) |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 174 | return super().__new__(cls) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 175 | |
| 176 | # Things that are not classes also need these. |
| 177 | def _eval_type(self, globalns, localns): |
| 178 | return self |
| 179 | |
| 180 | def _get_type_vars(self, tvars): |
| 181 | pass |
| 182 | |
| 183 | def __repr__(self): |
| 184 | cls = type(self) |
| 185 | qname = _trim_name(_qualname(cls)) |
| 186 | return '%s.%s' % (cls.__module__, qname) |
| 187 | |
| 188 | def __call__(self, *args, **kwds): |
| 189 | raise TypeError("Cannot instantiate %r" % type(self)) |
| 190 | |
| 191 | |
| 192 | class _FinalTypingBase(_TypingBase, _root=True): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 193 | """Internal mix-in class to prevent instantiation. |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 194 | |
| 195 | Prevents instantiation unless _root=True is given in class call. |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 196 | 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] | 197 | """ |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 198 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 199 | __slots__ = () |
| 200 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 201 | def __new__(cls, *args, _root=False, **kwds): |
| 202 | self = super().__new__(cls, *args, **kwds) |
| 203 | if _root is True: |
| 204 | return self |
| 205 | raise TypeError("Cannot instantiate %r" % cls) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 206 | |
Guido van Rossum | b7dedc8 | 2016-10-29 12:44:29 -0700 | [diff] [blame] | 207 | def __reduce__(self): |
| 208 | return _trim_name(type(self).__name__) |
| 209 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 210 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 211 | class _ForwardRef(_TypingBase, _root=True): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 212 | """Internal wrapper to hold a forward reference.""" |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 213 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 214 | __slots__ = ('__forward_arg__', '__forward_code__', |
Guido van Rossum | c7b9295 | 2016-11-10 08:24:06 -0800 | [diff] [blame] | 215 | '__forward_evaluated__', '__forward_value__') |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 216 | |
| 217 | def __init__(self, arg): |
| 218 | super().__init__(arg) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 219 | if not isinstance(arg, str): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 220 | raise TypeError('Forward reference must be a string -- got %r' % (arg,)) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 221 | try: |
| 222 | code = compile(arg, '<string>', 'eval') |
| 223 | except SyntaxError: |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 224 | raise SyntaxError('Forward reference must be an expression -- got %r' % |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 225 | (arg,)) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 226 | self.__forward_arg__ = arg |
| 227 | self.__forward_code__ = code |
| 228 | self.__forward_evaluated__ = False |
| 229 | self.__forward_value__ = None |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 230 | |
| 231 | def _eval_type(self, globalns, localns): |
Guido van Rossum | dad1790 | 2016-11-10 08:29:18 -0800 | [diff] [blame] | 232 | if not self.__forward_evaluated__ or localns is not globalns: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 233 | if globalns is None and localns is None: |
| 234 | globalns = localns = {} |
| 235 | elif globalns is None: |
| 236 | globalns = localns |
| 237 | elif localns is None: |
| 238 | localns = globalns |
| 239 | self.__forward_value__ = _type_check( |
| 240 | eval(self.__forward_code__, globalns, localns), |
| 241 | "Forward references must evaluate to types.") |
| 242 | self.__forward_evaluated__ = True |
| 243 | return self.__forward_value__ |
| 244 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 245 | def __eq__(self, other): |
| 246 | if not isinstance(other, _ForwardRef): |
| 247 | return NotImplemented |
| 248 | return (self.__forward_arg__ == other.__forward_arg__ and |
Guido van Rossum | c7b9295 | 2016-11-10 08:24:06 -0800 | [diff] [blame] | 249 | self.__forward_value__ == other.__forward_value__) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 250 | |
| 251 | def __hash__(self): |
Guido van Rossum | c7b9295 | 2016-11-10 08:24:06 -0800 | [diff] [blame] | 252 | return hash((self.__forward_arg__, self.__forward_value__)) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 253 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 254 | def __instancecheck__(self, obj): |
| 255 | raise TypeError("Forward references cannot be used with isinstance().") |
| 256 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 257 | def __subclasscheck__(self, cls): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 258 | raise TypeError("Forward references cannot be used with issubclass().") |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 259 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 260 | def __repr__(self): |
| 261 | return '_ForwardRef(%r)' % (self.__forward_arg__,) |
| 262 | |
| 263 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 264 | class _TypeAlias(_TypingBase, _root=True): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 265 | """Internal helper class for defining generic variants of concrete types. |
| 266 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 267 | Note that this is not a type; let's call it a pseudo-type. It cannot |
| 268 | be used in instance and subclass checks in parameterized form, i.e. |
| 269 | ``isinstance(42, Match[str])`` raises ``TypeError`` instead of returning |
| 270 | ``False``. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 271 | """ |
| 272 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 273 | __slots__ = ('name', 'type_var', 'impl_type', 'type_checker') |
| 274 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 275 | def __init__(self, name, type_var, impl_type, type_checker): |
| 276 | """Initializer. |
| 277 | |
| 278 | Args: |
| 279 | name: The name, e.g. 'Pattern'. |
| 280 | type_var: The type parameter, e.g. AnyStr, or the |
| 281 | specific type, e.g. str. |
| 282 | impl_type: The implementation type. |
| 283 | type_checker: Function that takes an impl_type instance. |
| 284 | and returns a value that should be a type_var instance. |
| 285 | """ |
| 286 | assert isinstance(name, str), repr(name) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 287 | assert isinstance(impl_type, type), repr(impl_type) |
| 288 | assert not isinstance(impl_type, TypingMeta), repr(impl_type) |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 289 | assert isinstance(type_var, (type, _TypingBase)), repr(type_var) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 290 | self.name = name |
| 291 | self.type_var = type_var |
| 292 | self.impl_type = impl_type |
| 293 | self.type_checker = type_checker |
| 294 | |
| 295 | def __repr__(self): |
| 296 | return "%s[%s]" % (self.name, _type_repr(self.type_var)) |
| 297 | |
| 298 | def __getitem__(self, parameter): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 299 | if not isinstance(self.type_var, TypeVar): |
| 300 | raise TypeError("%s cannot be further parameterized." % self) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 301 | if self.type_var.__constraints__ and isinstance(parameter, type): |
| 302 | if not issubclass(parameter, self.type_var.__constraints__): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 303 | raise TypeError("%s is not a valid substitution for %s." % |
| 304 | (parameter, self.type_var)) |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 305 | if isinstance(parameter, TypeVar) and parameter is not self.type_var: |
| 306 | raise TypeError("%s cannot be re-parameterized." % self) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 307 | return self.__class__(self.name, parameter, |
| 308 | self.impl_type, self.type_checker) |
| 309 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 310 | def __eq__(self, other): |
| 311 | if not isinstance(other, _TypeAlias): |
| 312 | return NotImplemented |
| 313 | return self.name == other.name and self.type_var == other.type_var |
| 314 | |
| 315 | def __hash__(self): |
| 316 | return hash((self.name, self.type_var)) |
| 317 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 318 | def __instancecheck__(self, obj): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 319 | if not isinstance(self.type_var, TypeVar): |
| 320 | raise TypeError("Parameterized type aliases cannot be used " |
| 321 | "with isinstance().") |
| 322 | return isinstance(obj, self.impl_type) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 323 | |
| 324 | def __subclasscheck__(self, cls): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 325 | if not isinstance(self.type_var, TypeVar): |
| 326 | raise TypeError("Parameterized type aliases cannot be used " |
| 327 | "with issubclass().") |
| 328 | return issubclass(cls, self.impl_type) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 329 | |
| 330 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 331 | def _get_type_vars(types, tvars): |
| 332 | for t in types: |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 333 | if isinstance(t, TypingMeta) or isinstance(t, _TypingBase): |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 334 | t._get_type_vars(tvars) |
| 335 | |
| 336 | |
| 337 | def _type_vars(types): |
| 338 | tvars = [] |
| 339 | _get_type_vars(types, tvars) |
| 340 | return tuple(tvars) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 341 | |
| 342 | |
| 343 | def _eval_type(t, globalns, localns): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 344 | if isinstance(t, TypingMeta) or isinstance(t, _TypingBase): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 345 | return t._eval_type(globalns, localns) |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 346 | return t |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 347 | |
| 348 | |
| 349 | def _type_check(arg, msg): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 350 | """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] | 351 | |
| 352 | As a special case, accept None and return type(None) instead. |
| 353 | Also, _TypeAlias instances (e.g. Match, Pattern) are acceptable. |
| 354 | |
| 355 | The msg argument is a human-readable error message, e.g. |
| 356 | |
| 357 | "Union[arg, ...]: arg should be a type." |
| 358 | |
| 359 | We append the repr() of the actual value (truncated to 100 chars). |
| 360 | """ |
| 361 | if arg is None: |
| 362 | return type(None) |
| 363 | if isinstance(arg, str): |
| 364 | arg = _ForwardRef(arg) |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 365 | if ( |
| 366 | isinstance(arg, _TypingBase) and type(arg).__name__ == '_ClassVar' or |
| 367 | not isinstance(arg, (type, _TypingBase)) and not callable(arg) |
| 368 | ): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 369 | raise TypeError(msg + " Got %.100r." % (arg,)) |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 370 | # Bare Union etc. are not valid as type arguments |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 371 | if ( |
| 372 | type(arg).__name__ in ('_Union', '_Optional') and |
| 373 | not getattr(arg, '__origin__', None) or |
| 374 | isinstance(arg, TypingMeta) and _gorg(arg) in (Generic, _Protocol) |
| 375 | ): |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 376 | raise TypeError("Plain %s is not valid as type argument" % arg) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 377 | return arg |
| 378 | |
| 379 | |
| 380 | def _type_repr(obj): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 381 | """Return the repr() of an object, special-casing types (internal helper). |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 382 | |
| 383 | If obj is a type, we return a shorter version than the default |
| 384 | type.__repr__, based on the module and qualified name, which is |
| 385 | typically enough to uniquely identify a type. For everything |
| 386 | else, we fall back on repr(obj). |
| 387 | """ |
| 388 | if isinstance(obj, type) and not isinstance(obj, TypingMeta): |
| 389 | if obj.__module__ == 'builtins': |
| 390 | return _qualname(obj) |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 391 | return '%s.%s' % (obj.__module__, _qualname(obj)) |
| 392 | if obj is ...: |
| 393 | return('...') |
| 394 | if isinstance(obj, types.FunctionType): |
| 395 | return obj.__name__ |
| 396 | return repr(obj) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 397 | |
| 398 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 399 | class _Any(_FinalTypingBase, _root=True): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 400 | """Special type indicating an unconstrained type. |
| 401 | |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 402 | - Any is compatible with every type. |
| 403 | - Any assumed to have all methods. |
| 404 | - All values assumed to be instances of Any. |
| 405 | |
| 406 | Note that all the above statements are true from the point of view of |
| 407 | static type checkers. At runtime, Any should not be used with instance |
| 408 | or class checks. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 409 | """ |
| 410 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 411 | __slots__ = () |
| 412 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 413 | def __instancecheck__(self, obj): |
| 414 | raise TypeError("Any cannot be used with isinstance().") |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 415 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 416 | def __subclasscheck__(self, cls): |
| 417 | raise TypeError("Any cannot be used with issubclass().") |
| 418 | |
| 419 | |
| 420 | Any = _Any(_root=True) |
| 421 | |
| 422 | |
| 423 | class TypeVar(_TypingBase, _root=True): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 424 | """Type variable. |
| 425 | |
| 426 | Usage:: |
| 427 | |
| 428 | T = TypeVar('T') # Can be anything |
| 429 | A = TypeVar('A', str, bytes) # Must be str or bytes |
| 430 | |
| 431 | Type variables exist primarily for the benefit of static type |
| 432 | checkers. They serve as the parameters for generic types as well |
| 433 | as for generic function definitions. See class Generic for more |
| 434 | information on generic types. Generic functions work as follows: |
| 435 | |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 436 | def repeat(x: T, n: int) -> List[T]: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 437 | '''Return a list containing n references to x.''' |
| 438 | return [x]*n |
| 439 | |
| 440 | def longest(x: A, y: A) -> A: |
| 441 | '''Return the longest of two strings.''' |
| 442 | return x if len(x) >= len(y) else y |
| 443 | |
| 444 | The latter example's signature is essentially the overloading |
| 445 | of (str, str) -> str and (bytes, bytes) -> bytes. Also note |
| 446 | that if the arguments are instances of some subclass of str, |
| 447 | the return type is still plain str. |
| 448 | |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 449 | 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] | 450 | |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 451 | Type variables defined with covariant=True or contravariant=True |
| 452 | can be used do declare covariant or contravariant generic types. |
| 453 | See PEP 484 for more details. By default generic types are invariant |
| 454 | in all type variables. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 455 | |
| 456 | Type variables can be introspected. e.g.: |
| 457 | |
| 458 | T.__name__ == 'T' |
| 459 | T.__constraints__ == () |
| 460 | T.__covariant__ == False |
| 461 | T.__contravariant__ = False |
| 462 | A.__constraints__ == (str, bytes) |
| 463 | """ |
| 464 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 465 | __slots__ = ('__name__', '__bound__', '__constraints__', |
| 466 | '__covariant__', '__contravariant__') |
| 467 | |
| 468 | def __init__(self, name, *constraints, bound=None, |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 469 | covariant=False, contravariant=False): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 470 | super().__init__(name, *constraints, bound=bound, |
| 471 | covariant=covariant, contravariant=contravariant) |
| 472 | self.__name__ = name |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 473 | if covariant and contravariant: |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 474 | raise ValueError("Bivariant types are not supported.") |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 475 | self.__covariant__ = bool(covariant) |
| 476 | self.__contravariant__ = bool(contravariant) |
| 477 | if constraints and bound is not None: |
| 478 | raise TypeError("Constraints cannot be combined with bound=...") |
| 479 | if constraints and len(constraints) == 1: |
| 480 | raise TypeError("A single constraint is not allowed") |
| 481 | msg = "TypeVar(name, constraint, ...): constraints must be types." |
| 482 | self.__constraints__ = tuple(_type_check(t, msg) for t in constraints) |
| 483 | if bound: |
| 484 | self.__bound__ = _type_check(bound, "Bound must be a type.") |
| 485 | else: |
| 486 | self.__bound__ = None |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 487 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 488 | def _get_type_vars(self, tvars): |
| 489 | if self not in tvars: |
| 490 | tvars.append(self) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 491 | |
| 492 | def __repr__(self): |
| 493 | if self.__covariant__: |
| 494 | prefix = '+' |
| 495 | elif self.__contravariant__: |
| 496 | prefix = '-' |
| 497 | else: |
| 498 | prefix = '~' |
| 499 | return prefix + self.__name__ |
| 500 | |
| 501 | def __instancecheck__(self, instance): |
| 502 | raise TypeError("Type variables cannot be used with isinstance().") |
| 503 | |
| 504 | def __subclasscheck__(self, cls): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 505 | raise TypeError("Type variables cannot be used with issubclass().") |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 506 | |
| 507 | |
| 508 | # Some unconstrained type variables. These are used by the container types. |
Guido van Rossum | eb9aca3 | 2016-05-24 16:38:22 -0700 | [diff] [blame] | 509 | # (These are not for export.) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 510 | T = TypeVar('T') # Any type. |
| 511 | KT = TypeVar('KT') # Key type. |
| 512 | VT = TypeVar('VT') # Value type. |
| 513 | T_co = TypeVar('T_co', covariant=True) # Any type covariant containers. |
| 514 | V_co = TypeVar('V_co', covariant=True) # Any type covariant containers. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 515 | VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers. |
| 516 | T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant. |
| 517 | |
| 518 | # A useful type variable with constraints. This represents string types. |
Guido van Rossum | eb9aca3 | 2016-05-24 16:38:22 -0700 | [diff] [blame] | 519 | # (This one *is* for export!) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 520 | AnyStr = TypeVar('AnyStr', bytes, str) |
| 521 | |
| 522 | |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 523 | def _replace_arg(arg, tvars, args): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 524 | """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] | 525 | found in tvars with corresponding substitution from args or |
| 526 | with corresponding substitution sub-tree if arg is a generic type. |
| 527 | """ |
| 528 | |
| 529 | if tvars is None: |
| 530 | tvars = [] |
Guido van Rossum | 83ec302 | 2017-01-17 20:43:28 -0800 | [diff] [blame] | 531 | if hasattr(arg, '_subs_tree') and isinstance(arg, (GenericMeta, _TypingBase)): |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 532 | return arg._subs_tree(tvars, args) |
| 533 | if isinstance(arg, TypeVar): |
| 534 | for i, tvar in enumerate(tvars): |
| 535 | if arg == tvar: |
| 536 | return args[i] |
| 537 | return arg |
| 538 | |
| 539 | |
Guido van Rossum | 83ec302 | 2017-01-17 20:43:28 -0800 | [diff] [blame] | 540 | # Special typing constructs Union, Optional, Generic, Callable and Tuple |
| 541 | # use three special attributes for internal bookkeeping of generic types: |
| 542 | # * __parameters__ is a tuple of unique free type parameters of a generic |
| 543 | # type, for example, Dict[T, T].__parameters__ == (T,); |
| 544 | # * __origin__ keeps a reference to a type that was subscripted, |
| 545 | # e.g., Union[T, int].__origin__ == Union; |
| 546 | # * __args__ is a tuple of all arguments used in subscripting, |
| 547 | # e.g., Dict[T, int].__args__ == (T, int). |
| 548 | |
| 549 | |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 550 | def _subs_tree(cls, tvars=None, args=None): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 551 | """An internal helper function: calculate substitution tree |
| 552 | for generic cls after replacing its type parameters with |
| 553 | substitutions in tvars -> args (if any). |
| 554 | Repeat the same following __origin__'s. |
| 555 | |
| 556 | Return a list of arguments with all possible substitutions |
| 557 | performed. Arguments that are generic classes themselves are represented |
| 558 | as tuples (so that no new classes are created by this function). |
| 559 | For example: _subs_tree(List[Tuple[int, T]][str]) == [(Tuple, int, str)] |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 560 | """ |
| 561 | |
| 562 | if cls.__origin__ is None: |
| 563 | return cls |
| 564 | # Make of chain of origins (i.e. cls -> cls.__origin__) |
| 565 | current = cls.__origin__ |
| 566 | orig_chain = [] |
| 567 | while current.__origin__ is not None: |
| 568 | orig_chain.append(current) |
| 569 | current = current.__origin__ |
| 570 | # Replace type variables in __args__ if asked ... |
| 571 | tree_args = [] |
| 572 | for arg in cls.__args__: |
| 573 | tree_args.append(_replace_arg(arg, tvars, args)) |
| 574 | # ... then continue replacing down the origin chain. |
| 575 | for ocls in orig_chain: |
| 576 | new_tree_args = [] |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 577 | for arg in ocls.__args__: |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 578 | new_tree_args.append(_replace_arg(arg, ocls.__parameters__, tree_args)) |
| 579 | tree_args = new_tree_args |
| 580 | return tree_args |
| 581 | |
| 582 | |
| 583 | def _remove_dups_flatten(parameters): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 584 | """An internal helper for Union creation and substitution: flatten Union's |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 585 | among parameters, then remove duplicates and strict subclasses. |
| 586 | """ |
| 587 | |
| 588 | # Flatten out Union[Union[...], ...]. |
| 589 | params = [] |
| 590 | for p in parameters: |
| 591 | if isinstance(p, _Union) and p.__origin__ is Union: |
| 592 | params.extend(p.__args__) |
| 593 | elif isinstance(p, tuple) and len(p) > 0 and p[0] is Union: |
| 594 | params.extend(p[1:]) |
| 595 | else: |
| 596 | params.append(p) |
| 597 | # Weed out strict duplicates, preserving the first of each occurrence. |
| 598 | all_params = set(params) |
| 599 | if len(all_params) < len(params): |
| 600 | new_params = [] |
| 601 | for t in params: |
| 602 | if t in all_params: |
| 603 | new_params.append(t) |
| 604 | all_params.remove(t) |
| 605 | params = new_params |
| 606 | assert not all_params, all_params |
| 607 | # Weed out subclasses. |
| 608 | # E.g. Union[int, Employee, Manager] == Union[int, Employee]. |
| 609 | # If object is present it will be sole survivor among proper classes. |
| 610 | # Never discard type variables. |
| 611 | # (In particular, Union[str, AnyStr] != AnyStr.) |
| 612 | all_params = set(params) |
| 613 | for t1 in params: |
| 614 | if not isinstance(t1, type): |
| 615 | continue |
| 616 | if any(isinstance(t2, type) and issubclass(t1, t2) |
| 617 | for t2 in all_params - {t1} |
| 618 | if not (isinstance(t2, GenericMeta) and |
| 619 | t2.__origin__ is not None)): |
| 620 | all_params.remove(t1) |
| 621 | return tuple(t for t in params if t in all_params) |
| 622 | |
| 623 | |
| 624 | def _check_generic(cls, parameters): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 625 | # Check correct count for parameters of a generic cls (internal helper). |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 626 | if not cls.__parameters__: |
| 627 | raise TypeError("%s is not a generic class" % repr(cls)) |
| 628 | alen = len(parameters) |
| 629 | elen = len(cls.__parameters__) |
| 630 | if alen != elen: |
| 631 | raise TypeError("Too %s parameters for %s; actual %s, expected %s" % |
| 632 | ("many" if alen > elen else "few", repr(cls), alen, elen)) |
| 633 | |
| 634 | |
Guido van Rossum | 9b10756 | 2016-11-09 13:23:04 -0800 | [diff] [blame] | 635 | _cleanups = [] |
| 636 | |
| 637 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 638 | def _tp_cache(func): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 639 | """Internal wrapper caching __getitem__ of generic types with a fallback to |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 640 | original function for non-hashable arguments. |
| 641 | """ |
| 642 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 643 | cached = functools.lru_cache()(func) |
Guido van Rossum | 9b10756 | 2016-11-09 13:23:04 -0800 | [diff] [blame] | 644 | _cleanups.append(cached.cache_clear) |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 645 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 646 | @functools.wraps(func) |
| 647 | def inner(*args, **kwds): |
| 648 | try: |
| 649 | return cached(*args, **kwds) |
| 650 | except TypeError: |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 651 | pass # All real errors (not unhashable args) are raised below. |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 652 | return func(*args, **kwds) |
| 653 | return inner |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 654 | |
| 655 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 656 | class _Union(_FinalTypingBase, _root=True): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 657 | """Union type; Union[X, Y] means either X or Y. |
| 658 | |
| 659 | To define a union, use e.g. Union[int, str]. Details: |
| 660 | |
| 661 | - The arguments must be types and there must be at least one. |
| 662 | |
| 663 | - None as an argument is a special case and is replaced by |
| 664 | type(None). |
| 665 | |
| 666 | - Unions of unions are flattened, e.g.:: |
| 667 | |
| 668 | Union[Union[int, str], float] == Union[int, str, float] |
| 669 | |
| 670 | - Unions of a single argument vanish, e.g.:: |
| 671 | |
| 672 | Union[int] == int # The constructor actually returns int |
| 673 | |
| 674 | - Redundant arguments are skipped, e.g.:: |
| 675 | |
| 676 | Union[int, str, int] == Union[int, str] |
| 677 | |
| 678 | - When comparing unions, the argument order is ignored, e.g.:: |
| 679 | |
| 680 | Union[int, str] == Union[str, int] |
| 681 | |
| 682 | - When two arguments have a subclass relationship, the least |
| 683 | derived argument is kept, e.g.:: |
| 684 | |
| 685 | class Employee: pass |
| 686 | class Manager(Employee): pass |
| 687 | Union[int, Employee, Manager] == Union[int, Employee] |
| 688 | Union[Manager, int, Employee] == Union[int, Employee] |
| 689 | Union[Employee, Manager] == Employee |
| 690 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 691 | - Similar for object:: |
| 692 | |
| 693 | Union[int, object] == object |
| 694 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 695 | - You cannot subclass or instantiate a union. |
| 696 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 697 | - You can use Optional[X] as a shorthand for Union[X, None]. |
| 698 | """ |
| 699 | |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 700 | __slots__ = ('__parameters__', '__args__', '__origin__', '__tree_hash__') |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 701 | |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 702 | def __new__(cls, parameters=None, origin=None, *args, _root=False): |
| 703 | self = super().__new__(cls, parameters, origin, *args, _root=_root) |
| 704 | if origin is None: |
| 705 | self.__parameters__ = None |
| 706 | self.__args__ = None |
| 707 | self.__origin__ = None |
| 708 | self.__tree_hash__ = hash(frozenset(('Union',))) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 709 | return self |
| 710 | if not isinstance(parameters, tuple): |
| 711 | raise TypeError("Expected parameters=<tuple>") |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 712 | if origin is Union: |
| 713 | parameters = _remove_dups_flatten(parameters) |
| 714 | # It's not a union if there's only one type left. |
| 715 | if len(parameters) == 1: |
| 716 | return parameters[0] |
| 717 | self.__parameters__ = _type_vars(parameters) |
| 718 | self.__args__ = parameters |
| 719 | self.__origin__ = origin |
| 720 | # Pre-calculate the __hash__ on instantiation. |
| 721 | # This improves speed for complex substitutions. |
| 722 | subs_tree = self._subs_tree() |
| 723 | if isinstance(subs_tree, tuple): |
| 724 | self.__tree_hash__ = hash(frozenset(subs_tree)) |
| 725 | else: |
| 726 | self.__tree_hash__ = hash(subs_tree) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 727 | return self |
| 728 | |
| 729 | def _eval_type(self, globalns, localns): |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 730 | if self.__args__ is None: |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 731 | return self |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 732 | ev_args = tuple(_eval_type(t, globalns, localns) for t in self.__args__) |
| 733 | ev_origin = _eval_type(self.__origin__, globalns, localns) |
| 734 | if ev_args == self.__args__ and ev_origin == self.__origin__: |
| 735 | # Everything is already evaluated. |
| 736 | return self |
| 737 | return self.__class__(ev_args, ev_origin, _root=True) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 738 | |
| 739 | def _get_type_vars(self, tvars): |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 740 | if self.__origin__ and self.__parameters__: |
| 741 | _get_type_vars(self.__parameters__, tvars) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 742 | |
| 743 | def __repr__(self): |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 744 | if self.__origin__ is None: |
| 745 | return super().__repr__() |
| 746 | tree = self._subs_tree() |
| 747 | if not isinstance(tree, tuple): |
| 748 | return repr(tree) |
| 749 | return tree[0]._tree_repr(tree) |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 750 | |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 751 | def _tree_repr(self, tree): |
| 752 | arg_list = [] |
| 753 | for arg in tree[1:]: |
| 754 | if not isinstance(arg, tuple): |
| 755 | arg_list.append(_type_repr(arg)) |
| 756 | else: |
| 757 | arg_list.append(arg[0]._tree_repr(arg)) |
| 758 | return super().__repr__() + '[%s]' % ', '.join(arg_list) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 759 | |
| 760 | @_tp_cache |
| 761 | def __getitem__(self, parameters): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 762 | if parameters == (): |
| 763 | raise TypeError("Cannot take a Union of no types.") |
| 764 | if not isinstance(parameters, tuple): |
| 765 | parameters = (parameters,) |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 766 | if self.__origin__ is None: |
| 767 | msg = "Union[arg, ...]: each arg must be a type." |
| 768 | else: |
| 769 | msg = "Parameters to generic types must be types." |
| 770 | parameters = tuple(_type_check(p, msg) for p in parameters) |
| 771 | if self is not Union: |
| 772 | _check_generic(self, parameters) |
| 773 | return self.__class__(parameters, origin=self, _root=True) |
| 774 | |
| 775 | def _subs_tree(self, tvars=None, args=None): |
| 776 | if self is Union: |
| 777 | return Union # Nothing to substitute |
| 778 | tree_args = _subs_tree(self, tvars, args) |
| 779 | tree_args = _remove_dups_flatten(tree_args) |
| 780 | if len(tree_args) == 1: |
| 781 | return tree_args[0] # Union of a single type is that type |
| 782 | return (Union,) + tree_args |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 783 | |
| 784 | def __eq__(self, other): |
Guido van Rossum | 83ec302 | 2017-01-17 20:43:28 -0800 | [diff] [blame] | 785 | if isinstance(other, _Union): |
| 786 | return self.__tree_hash__ == other.__tree_hash__ |
| 787 | elif self is not Union: |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 788 | return self._subs_tree() == other |
Guido van Rossum | 83ec302 | 2017-01-17 20:43:28 -0800 | [diff] [blame] | 789 | else: |
| 790 | return self is other |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 791 | |
| 792 | def __hash__(self): |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 793 | return self.__tree_hash__ |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 794 | |
| 795 | def __instancecheck__(self, obj): |
| 796 | raise TypeError("Unions cannot be used with isinstance().") |
| 797 | |
| 798 | def __subclasscheck__(self, cls): |
| 799 | raise TypeError("Unions cannot be used with issubclass().") |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 800 | |
| 801 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 802 | Union = _Union(_root=True) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 803 | |
| 804 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 805 | class _Optional(_FinalTypingBase, _root=True): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 806 | """Optional type. |
| 807 | |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 808 | Optional[X] is equivalent to Union[X, None]. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 809 | """ |
| 810 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 811 | __slots__ = () |
| 812 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 813 | @_tp_cache |
| 814 | def __getitem__(self, arg): |
| 815 | arg = _type_check(arg, "Optional[t] requires a single type.") |
| 816 | return Union[arg, type(None)] |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 817 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 818 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 819 | Optional = _Optional(_root=True) |
| 820 | |
| 821 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 822 | def _gorg(a): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 823 | """Return the farthest origin of a generic class (internal helper).""" |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 824 | assert isinstance(a, GenericMeta) |
| 825 | while a.__origin__ is not None: |
| 826 | a = a.__origin__ |
| 827 | return a |
| 828 | |
| 829 | |
| 830 | def _geqv(a, b): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 831 | """Return whether two generic classes are equivalent (internal helper). |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 832 | |
| 833 | 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] | 834 | parameterized forms (X[T], X[int], etc.) as equivalent. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 835 | |
| 836 | However, X is not equivalent to a subclass of X. |
| 837 | |
| 838 | The relation is reflexive, symmetric and transitive. |
| 839 | """ |
| 840 | assert isinstance(a, GenericMeta) and isinstance(b, GenericMeta) |
| 841 | # Reduce each to its origin. |
| 842 | return _gorg(a) is _gorg(b) |
| 843 | |
| 844 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 845 | def _next_in_mro(cls): |
| 846 | """Helper for Generic.__new__. |
| 847 | |
| 848 | Returns the class after the last occurrence of Generic or |
| 849 | Generic[...] in cls.__mro__. |
| 850 | """ |
| 851 | next_in_mro = object |
| 852 | # Look for the last occurrence of Generic or Generic[...]. |
| 853 | for i, c in enumerate(cls.__mro__[:-1]): |
| 854 | if isinstance(c, GenericMeta) and _gorg(c) is Generic: |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 855 | next_in_mro = cls.__mro__[i + 1] |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 856 | return next_in_mro |
| 857 | |
| 858 | |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 859 | def _make_subclasshook(cls): |
| 860 | """Construct a __subclasshook__ callable that incorporates |
| 861 | the associated __extra__ class in subclass checks performed |
| 862 | against cls. |
| 863 | """ |
| 864 | if isinstance(cls.__extra__, abc.ABCMeta): |
| 865 | # The logic mirrors that of ABCMeta.__subclasscheck__. |
| 866 | # Registered classes need not be checked here because |
| 867 | # cls and its extra share the same _abc_registry. |
| 868 | def __extrahook__(subclass): |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 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): |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 883 | if cls.__extra__ and issubclass(subclass, cls.__extra__): |
| 884 | return True |
| 885 | return NotImplemented |
| 886 | return __extrahook__ |
| 887 | |
| 888 | |
Guido van Rossum | 61f0a02 | 2016-11-29 09:46:21 -0800 | [diff] [blame] | 889 | def _no_slots_copy(dct): |
| 890 | """Internal helper: copy class __dict__ and clean slots class variables. |
| 891 | (They will be re-created if necessary by normal class machinery.) |
| 892 | """ |
| 893 | dict_copy = dict(dct) |
| 894 | if '__slots__' in dict_copy: |
| 895 | for slot in dict_copy['__slots__']: |
| 896 | dict_copy.pop(slot, None) |
| 897 | return dict_copy |
| 898 | |
| 899 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 900 | class GenericMeta(TypingMeta, abc.ABCMeta): |
Guido van Rossum | 83ec302 | 2017-01-17 20:43:28 -0800 | [diff] [blame] | 901 | """Metaclass for generic types. |
| 902 | |
| 903 | This is a metaclass for typing.Generic and generic ABCs defined in |
| 904 | typing module. User defined subclasses of GenericMeta can override |
| 905 | __new__ and invoke super().__new__. Note that GenericMeta.__new__ |
| 906 | has strict rules on what is allowed in its bases argument: |
| 907 | * plain Generic is disallowed in bases; |
| 908 | * Generic[...] should appear in bases at most once; |
| 909 | * if Generic[...] is present, then it should list all type variables |
| 910 | that appear in other bases. |
| 911 | In addition, type of all generic bases is erased, e.g., C[int] is |
| 912 | stripped to plain C. |
| 913 | """ |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 914 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 915 | def __new__(cls, name, bases, namespace, |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 916 | tvars=None, args=None, origin=None, extra=None, orig_bases=None): |
Guido van Rossum | 83ec302 | 2017-01-17 20:43:28 -0800 | [diff] [blame] | 917 | """Create a new generic class. GenericMeta.__new__ accepts |
| 918 | keyword arguments that are used for internal bookkeeping, therefore |
| 919 | an override should pass unused keyword arguments to super(). |
| 920 | """ |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 921 | if tvars is not None: |
| 922 | # Called from __getitem__() below. |
| 923 | assert origin is not None |
| 924 | assert all(isinstance(t, TypeVar) for t in tvars), tvars |
| 925 | else: |
| 926 | # Called from class statement. |
| 927 | assert tvars is None, tvars |
| 928 | assert args is None, args |
| 929 | assert origin is None, origin |
| 930 | |
| 931 | # Get the full set of tvars from the bases. |
| 932 | tvars = _type_vars(bases) |
| 933 | # Look for Generic[T1, ..., Tn]. |
| 934 | # If found, tvars must be a subset of it. |
| 935 | # If not found, tvars is it. |
| 936 | # Also check for and reject plain Generic, |
| 937 | # and reject multiple Generic[...]. |
| 938 | gvars = None |
| 939 | for base in bases: |
| 940 | if base is Generic: |
| 941 | raise TypeError("Cannot inherit from plain Generic") |
| 942 | if (isinstance(base, GenericMeta) and |
| 943 | base.__origin__ is Generic): |
| 944 | if gvars is not None: |
| 945 | raise TypeError( |
| 946 | "Cannot inherit from Generic[...] multiple types.") |
| 947 | gvars = base.__parameters__ |
| 948 | if gvars is None: |
| 949 | gvars = tvars |
| 950 | else: |
| 951 | tvarset = set(tvars) |
| 952 | gvarset = set(gvars) |
| 953 | if not tvarset <= gvarset: |
| 954 | raise TypeError( |
| 955 | "Some type variables (%s) " |
| 956 | "are not listed in Generic[%s]" % |
| 957 | (", ".join(str(t) for t in tvars if t not in gvarset), |
| 958 | ", ".join(str(g) for g in gvars))) |
| 959 | tvars = gvars |
| 960 | |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 961 | initial_bases = bases |
| 962 | if extra is not None and type(extra) is abc.ABCMeta and extra not in bases: |
| 963 | bases = (extra,) + bases |
| 964 | bases = tuple(_gorg(b) if isinstance(b, GenericMeta) else b for b in bases) |
| 965 | |
| 966 | # remove bare Generic from bases if there are other generic bases |
| 967 | if any(isinstance(b, GenericMeta) and b is not Generic for b in bases): |
| 968 | bases = tuple(b for b in bases if b is not Generic) |
Mariatta | 0230e64 | 2017-02-14 06:11:12 -0800 | [diff] [blame] | 969 | namespace.update({'__origin__': origin, '__extra__': extra}) |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 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 | # Speed hack (https://github.com/python/typing/issues/196). |
| 979 | self.__next_in_mro__ = _next_in_mro(self) |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 980 | # Preserve base classes on subclassing (__bases__ are type erased now). |
| 981 | if orig_bases is None: |
| 982 | self.__orig_bases__ = initial_bases |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 983 | |
| 984 | # This allows unparameterized generic collections to be used |
| 985 | # with issubclass() and isinstance() in the same way as their |
| 986 | # collections.abc counterparts (e.g., isinstance([], Iterable)). |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 987 | if ( |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 988 | '__subclasshook__' not in namespace and extra or |
Mariatta | 0230e64 | 2017-02-14 06:11:12 -0800 | [diff] [blame] | 989 | # allow overriding |
| 990 | getattr(self.__subclasshook__, '__name__', '') == '__extrahook__' |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 991 | ): |
Guido van Rossum | e259267 | 2016-10-08 20:27:22 -0700 | [diff] [blame] | 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 |
Mariatta | 0230e64 | 2017-02-14 06:11:12 -0800 | [diff] [blame] | 995 | self._abc_cache = extra._abc_cache |
| 996 | elif origin is not None: |
| 997 | self._abc_registry = origin._abc_registry |
| 998 | self._abc_cache = origin._abc_cache |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 999 | |
| 1000 | if origin and hasattr(origin, '__qualname__'): # Fix for Python 3.2. |
| 1001 | self.__qualname__ = origin.__qualname__ |
Mariatta | 0230e64 | 2017-02-14 06:11:12 -0800 | [diff] [blame] | 1002 | self.__tree_hash__ = (hash(self._subs_tree()) if origin else |
| 1003 | super(GenericMeta, self).__hash__()) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1004 | return self |
| 1005 | |
Mariatta | 0230e64 | 2017-02-14 06:11:12 -0800 | [diff] [blame] | 1006 | # _abc_negative_cache and _abc_negative_cache_version |
| 1007 | # realised as descriptors, since GenClass[t1, t2, ...] always |
| 1008 | # share subclass info with GenClass. |
| 1009 | # This is an important memory optimization. |
| 1010 | @property |
| 1011 | def _abc_negative_cache(self): |
| 1012 | if isinstance(self.__extra__, abc.ABCMeta): |
| 1013 | return self.__extra__._abc_negative_cache |
| 1014 | return _gorg(self)._abc_generic_negative_cache |
| 1015 | |
| 1016 | @_abc_negative_cache.setter |
| 1017 | def _abc_negative_cache(self, value): |
| 1018 | if self.__origin__ is None: |
| 1019 | if isinstance(self.__extra__, abc.ABCMeta): |
| 1020 | self.__extra__._abc_negative_cache = value |
| 1021 | else: |
| 1022 | self._abc_generic_negative_cache = value |
| 1023 | |
| 1024 | @property |
| 1025 | def _abc_negative_cache_version(self): |
| 1026 | if isinstance(self.__extra__, abc.ABCMeta): |
| 1027 | return self.__extra__._abc_negative_cache_version |
| 1028 | return _gorg(self)._abc_generic_negative_cache_version |
| 1029 | |
| 1030 | @_abc_negative_cache_version.setter |
| 1031 | def _abc_negative_cache_version(self, value): |
| 1032 | if self.__origin__ is None: |
| 1033 | if isinstance(self.__extra__, abc.ABCMeta): |
| 1034 | self.__extra__._abc_negative_cache_version = value |
| 1035 | else: |
| 1036 | self._abc_generic_negative_cache_version = value |
| 1037 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1038 | def _get_type_vars(self, tvars): |
| 1039 | if self.__origin__ and self.__parameters__: |
| 1040 | _get_type_vars(self.__parameters__, tvars) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1041 | |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1042 | def _eval_type(self, globalns, localns): |
| 1043 | ev_origin = (self.__origin__._eval_type(globalns, localns) |
| 1044 | if self.__origin__ else None) |
| 1045 | ev_args = tuple(_eval_type(a, globalns, localns) for a |
| 1046 | in self.__args__) if self.__args__ else None |
| 1047 | if ev_origin == self.__origin__ and ev_args == self.__args__: |
| 1048 | return self |
| 1049 | return self.__class__(self.__name__, |
| 1050 | self.__bases__, |
Guido van Rossum | 61f0a02 | 2016-11-29 09:46:21 -0800 | [diff] [blame] | 1051 | _no_slots_copy(self.__dict__), |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1052 | tvars=_type_vars(ev_args) if ev_args else None, |
| 1053 | args=ev_args, |
| 1054 | origin=ev_origin, |
| 1055 | extra=self.__extra__, |
| 1056 | orig_bases=self.__orig_bases__) |
| 1057 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1058 | def __repr__(self): |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 1059 | if self.__origin__ is None: |
| 1060 | return super().__repr__() |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1061 | return self._tree_repr(self._subs_tree()) |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 1062 | |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1063 | def _tree_repr(self, tree): |
| 1064 | arg_list = [] |
| 1065 | for arg in tree[1:]: |
| 1066 | if arg == (): |
| 1067 | arg_list.append('()') |
| 1068 | elif not isinstance(arg, tuple): |
| 1069 | arg_list.append(_type_repr(arg)) |
| 1070 | else: |
| 1071 | arg_list.append(arg[0]._tree_repr(arg)) |
| 1072 | return super().__repr__() + '[%s]' % ', '.join(arg_list) |
| 1073 | |
| 1074 | def _subs_tree(self, tvars=None, args=None): |
| 1075 | if self.__origin__ is None: |
| 1076 | return self |
| 1077 | tree_args = _subs_tree(self, tvars, args) |
| 1078 | return (_gorg(self),) + tuple(tree_args) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1079 | |
| 1080 | def __eq__(self, other): |
| 1081 | if not isinstance(other, GenericMeta): |
| 1082 | return NotImplemented |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1083 | if self.__origin__ is None or other.__origin__ is None: |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1084 | return self is other |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1085 | return self.__tree_hash__ == other.__tree_hash__ |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1086 | |
| 1087 | def __hash__(self): |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1088 | return self.__tree_hash__ |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1089 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1090 | @_tp_cache |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1091 | def __getitem__(self, params): |
| 1092 | if not isinstance(params, tuple): |
| 1093 | params = (params,) |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1094 | if not params and not _gorg(self) is Tuple: |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1095 | raise TypeError( |
| 1096 | "Parameter list to %s[...] cannot be empty" % _qualname(self)) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1097 | msg = "Parameters to generic types must be types." |
| 1098 | params = tuple(_type_check(p, msg) for p in params) |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1099 | if self is Generic: |
| 1100 | # Generic can only be subscripted with unique type variables. |
| 1101 | if not all(isinstance(p, TypeVar) for p in params): |
| 1102 | raise TypeError( |
| 1103 | "Parameters to Generic[...] must all be type variables") |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1104 | if len(set(params)) != len(params): |
Guido van Rossum | 1b66910 | 2015-09-04 12:15:54 -0700 | [diff] [blame] | 1105 | raise TypeError( |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1106 | "Parameters to Generic[...] must all be unique") |
| 1107 | tvars = params |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 1108 | args = params |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1109 | elif self in (Tuple, Callable): |
| 1110 | tvars = _type_vars(params) |
| 1111 | args = params |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1112 | elif self is _Protocol: |
| 1113 | # _Protocol is internal, don't check anything. |
| 1114 | tvars = params |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 1115 | args = params |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1116 | elif self.__origin__ in (Generic, _Protocol): |
| 1117 | # Can't subscript Generic[...] or _Protocol[...]. |
| 1118 | raise TypeError("Cannot subscript already-subscripted %s" % |
| 1119 | repr(self)) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1120 | else: |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1121 | # Subscripting a regular Generic subclass. |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1122 | _check_generic(self, params) |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1123 | tvars = _type_vars(params) |
| 1124 | args = params |
Mariatta | 0230e64 | 2017-02-14 06:11:12 -0800 | [diff] [blame] | 1125 | |
| 1126 | prepend = (self,) if self.__origin__ is None else () |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1127 | return self.__class__(self.__name__, |
Mariatta | 0230e64 | 2017-02-14 06:11:12 -0800 | [diff] [blame] | 1128 | prepend + self.__bases__, |
Guido van Rossum | 61f0a02 | 2016-11-29 09:46:21 -0800 | [diff] [blame] | 1129 | _no_slots_copy(self.__dict__), |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1130 | tvars=tvars, |
| 1131 | args=args, |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1132 | origin=self, |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 1133 | extra=self.__extra__, |
| 1134 | orig_bases=self.__orig_bases__) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1135 | |
Mariatta | 0230e64 | 2017-02-14 06:11:12 -0800 | [diff] [blame] | 1136 | def __subclasscheck__(self, cls): |
| 1137 | if self.__origin__ is not None: |
| 1138 | if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools']: |
| 1139 | raise TypeError("Parameterized generics cannot be used with class " |
| 1140 | "or instance checks") |
| 1141 | return False |
| 1142 | if self is Generic: |
| 1143 | raise TypeError("Class %r cannot be used with class " |
| 1144 | "or instance checks" % self) |
| 1145 | return super().__subclasscheck__(cls) |
| 1146 | |
Guido van Rossum | 1b66910 | 2015-09-04 12:15:54 -0700 | [diff] [blame] | 1147 | def __instancecheck__(self, instance): |
| 1148 | # Since we extend ABC.__subclasscheck__ and |
| 1149 | # ABC.__instancecheck__ inlines the cache checking done by the |
| 1150 | # latter, we must extend __instancecheck__ too. For simplicity |
| 1151 | # we just skip the cache check -- instance checks for generic |
| 1152 | # classes are supposed to be rare anyways. |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 1153 | return issubclass(instance.__class__, self) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1154 | |
Guido van Rossum | b7dedc8 | 2016-10-29 12:44:29 -0700 | [diff] [blame] | 1155 | def __copy__(self): |
Guido van Rossum | 61f0a02 | 2016-11-29 09:46:21 -0800 | [diff] [blame] | 1156 | return self.__class__(self.__name__, self.__bases__, |
| 1157 | _no_slots_copy(self.__dict__), |
Guido van Rossum | b7dedc8 | 2016-10-29 12:44:29 -0700 | [diff] [blame] | 1158 | self.__parameters__, self.__args__, self.__origin__, |
| 1159 | self.__extra__, self.__orig_bases__) |
| 1160 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1161 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1162 | # Prevent checks for Generic to crash when defining Generic. |
| 1163 | Generic = None |
| 1164 | |
| 1165 | |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1166 | def _generic_new(base_cls, cls, *args, **kwds): |
| 1167 | # Assure type is erased on instantiation, |
| 1168 | # but attempt to store it in __orig_class__ |
| 1169 | if cls.__origin__ is None: |
| 1170 | return base_cls.__new__(cls) |
| 1171 | else: |
| 1172 | origin = _gorg(cls) |
| 1173 | obj = base_cls.__new__(origin) |
| 1174 | try: |
| 1175 | obj.__orig_class__ = cls |
| 1176 | except AttributeError: |
| 1177 | pass |
| 1178 | obj.__init__(*args, **kwds) |
| 1179 | return obj |
| 1180 | |
| 1181 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1182 | class Generic(metaclass=GenericMeta): |
| 1183 | """Abstract base class for generic types. |
| 1184 | |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 1185 | A generic type is typically declared by inheriting from |
| 1186 | this class parameterized with one or more type variables. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1187 | For example, a generic mapping type might be defined as:: |
| 1188 | |
| 1189 | class Mapping(Generic[KT, VT]): |
| 1190 | def __getitem__(self, key: KT) -> VT: |
| 1191 | ... |
| 1192 | # Etc. |
| 1193 | |
| 1194 | This class can then be used as follows:: |
| 1195 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1196 | 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] | 1197 | try: |
| 1198 | return mapping[key] |
| 1199 | except KeyError: |
| 1200 | return default |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1201 | """ |
| 1202 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1203 | __slots__ = () |
| 1204 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1205 | def __new__(cls, *args, **kwds): |
Guido van Rossum | 62fe1bb | 2016-10-29 16:05:26 -0700 | [diff] [blame] | 1206 | if _geqv(cls, Generic): |
| 1207 | raise TypeError("Type Generic cannot be instantiated; " |
| 1208 | "it can be used only as a base class") |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1209 | return _generic_new(cls.__next_in_mro__, cls, *args, **kwds) |
| 1210 | |
| 1211 | |
| 1212 | class _TypingEmpty: |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 1213 | """Internal placeholder for () or []. Used by TupleMeta and CallableMeta |
| 1214 | to allow empty list/tuple in specific places, without allowing them |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1215 | to sneak in where prohibited. |
| 1216 | """ |
| 1217 | |
| 1218 | |
| 1219 | class _TypingEllipsis: |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 1220 | """Internal placeholder for ... (ellipsis).""" |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1221 | |
| 1222 | |
| 1223 | class TupleMeta(GenericMeta): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 1224 | """Metaclass for Tuple (internal).""" |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1225 | |
| 1226 | @_tp_cache |
| 1227 | def __getitem__(self, parameters): |
| 1228 | if self.__origin__ is not None or not _geqv(self, Tuple): |
| 1229 | # Normal generic rules apply if this is not the first subscription |
| 1230 | # or a subscription of a subclass. |
| 1231 | return super().__getitem__(parameters) |
| 1232 | if parameters == (): |
| 1233 | return super().__getitem__((_TypingEmpty,)) |
| 1234 | if not isinstance(parameters, tuple): |
| 1235 | parameters = (parameters,) |
| 1236 | if len(parameters) == 2 and parameters[1] is ...: |
| 1237 | msg = "Tuple[t, ...]: t must be a type." |
| 1238 | p = _type_check(parameters[0], msg) |
| 1239 | return super().__getitem__((p, _TypingEllipsis)) |
| 1240 | msg = "Tuple[t0, t1, ...]: each t must be a type." |
| 1241 | parameters = tuple(_type_check(p, msg) for p in parameters) |
| 1242 | return super().__getitem__(parameters) |
| 1243 | |
| 1244 | def __instancecheck__(self, obj): |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 1245 | if self.__args__ is None: |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1246 | return isinstance(obj, tuple) |
| 1247 | raise TypeError("Parameterized Tuple cannot be used " |
| 1248 | "with isinstance().") |
| 1249 | |
| 1250 | def __subclasscheck__(self, cls): |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 1251 | if self.__args__ is None: |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1252 | return issubclass(cls, tuple) |
| 1253 | raise TypeError("Parameterized Tuple cannot be used " |
| 1254 | "with issubclass().") |
| 1255 | |
| 1256 | |
| 1257 | class Tuple(tuple, extra=tuple, metaclass=TupleMeta): |
| 1258 | """Tuple type; Tuple[X, Y] is the cross-product type of X and Y. |
| 1259 | |
| 1260 | Example: Tuple[T1, T2] is a tuple of two elements corresponding |
| 1261 | to type variables T1 and T2. Tuple[int, float, str] is a tuple |
| 1262 | of an int, a float and a string. |
| 1263 | |
| 1264 | To specify a variable-length tuple of homogeneous type, use Tuple[T, ...]. |
| 1265 | """ |
| 1266 | |
| 1267 | __slots__ = () |
| 1268 | |
| 1269 | def __new__(cls, *args, **kwds): |
| 1270 | if _geqv(cls, Tuple): |
| 1271 | raise TypeError("Type Tuple cannot be instantiated; " |
| 1272 | "use tuple() instead") |
| 1273 | return _generic_new(tuple, cls, *args, **kwds) |
| 1274 | |
| 1275 | |
| 1276 | class CallableMeta(GenericMeta): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 1277 | """Metaclass for Callable (internal).""" |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1278 | |
| 1279 | def __repr__(self): |
| 1280 | if self.__origin__ is None: |
| 1281 | return super().__repr__() |
| 1282 | return self._tree_repr(self._subs_tree()) |
| 1283 | |
| 1284 | def _tree_repr(self, tree): |
| 1285 | if _gorg(self) is not Callable: |
| 1286 | return super()._tree_repr(tree) |
| 1287 | # For actual Callable (not its subclass) we override |
| 1288 | # super()._tree_repr() for nice formatting. |
| 1289 | arg_list = [] |
| 1290 | for arg in tree[1:]: |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1291 | if not isinstance(arg, tuple): |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1292 | arg_list.append(_type_repr(arg)) |
| 1293 | else: |
| 1294 | arg_list.append(arg[0]._tree_repr(arg)) |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1295 | if arg_list[0] == '...': |
| 1296 | return repr(tree[0]) + '[..., %s]' % arg_list[1] |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1297 | return (repr(tree[0]) + |
| 1298 | '[[%s], %s]' % (', '.join(arg_list[:-1]), arg_list[-1])) |
| 1299 | |
| 1300 | def __getitem__(self, parameters): |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 1301 | """A thin wrapper around __getitem_inner__ to provide the latter |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1302 | with hashable arguments to improve speed. |
| 1303 | """ |
| 1304 | |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 1305 | if self.__origin__ is not None or not _geqv(self, Callable): |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1306 | return super().__getitem__(parameters) |
| 1307 | if not isinstance(parameters, tuple) or len(parameters) != 2: |
| 1308 | raise TypeError("Callable must be used as " |
| 1309 | "Callable[[arg, ...], result].") |
| 1310 | args, result = parameters |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1311 | if args is Ellipsis: |
| 1312 | parameters = (Ellipsis, result) |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1313 | else: |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1314 | if not isinstance(args, list): |
| 1315 | raise TypeError("Callable[args, result]: args must be a list." |
| 1316 | " Got %.100r." % (args,)) |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1317 | parameters = (tuple(args), result) |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1318 | return self.__getitem_inner__(parameters) |
| 1319 | |
| 1320 | @_tp_cache |
| 1321 | def __getitem_inner__(self, parameters): |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1322 | args, result = parameters |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1323 | msg = "Callable[args, result]: result must be a type." |
| 1324 | result = _type_check(result, msg) |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1325 | if args is Ellipsis: |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1326 | return super().__getitem__((_TypingEllipsis, result)) |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1327 | msg = "Callable[[arg, ...], result]: each arg must be a type." |
| 1328 | args = tuple(_type_check(arg, msg) for arg in args) |
| 1329 | parameters = args + (result,) |
| 1330 | return super().__getitem__(parameters) |
| 1331 | |
| 1332 | |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 1333 | class Callable(extra=collections_abc.Callable, metaclass=CallableMeta): |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1334 | """Callable type; Callable[[int], str] is a function of (int) -> str. |
| 1335 | |
| 1336 | The subscription syntax must always be used with exactly two |
| 1337 | values: the argument list and the return type. The argument list |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 1338 | 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] | 1339 | |
| 1340 | There is no syntax to indicate optional or keyword arguments, |
| 1341 | such function types are rarely used as callback types. |
| 1342 | """ |
| 1343 | |
| 1344 | __slots__ = () |
| 1345 | |
| 1346 | def __new__(cls, *args, **kwds): |
| 1347 | if _geqv(cls, Callable): |
| 1348 | raise TypeError("Type Callable cannot be instantiated; " |
| 1349 | "use a non-abstract subclass instead") |
| 1350 | return _generic_new(cls.__next_in_mro__, cls, *args, **kwds) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1351 | |
| 1352 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1353 | class _ClassVar(_FinalTypingBase, _root=True): |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1354 | """Special type construct to mark class variables. |
| 1355 | |
| 1356 | An annotation wrapped in ClassVar indicates that a given |
| 1357 | attribute is intended to be used as a class variable and |
| 1358 | should not be set on instances of that class. Usage:: |
| 1359 | |
| 1360 | class Starship: |
| 1361 | stats: ClassVar[Dict[str, int]] = {} # class variable |
| 1362 | damage: int = 10 # instance variable |
| 1363 | |
| 1364 | ClassVar accepts only types and cannot be further subscribed. |
| 1365 | |
| 1366 | Note that ClassVar is not a class itself, and should not |
| 1367 | be used with isinstance() or issubclass(). |
| 1368 | """ |
| 1369 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1370 | __slots__ = ('__type__',) |
| 1371 | |
| 1372 | def __init__(self, tp=None, **kwds): |
| 1373 | self.__type__ = tp |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1374 | |
| 1375 | def __getitem__(self, item): |
| 1376 | cls = type(self) |
| 1377 | if self.__type__ is None: |
| 1378 | return cls(_type_check(item, |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1379 | '{} accepts only single type.'.format(cls.__name__[1:])), |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1380 | _root=True) |
| 1381 | raise TypeError('{} cannot be further subscripted' |
| 1382 | .format(cls.__name__[1:])) |
| 1383 | |
| 1384 | def _eval_type(self, globalns, localns): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1385 | new_tp = _eval_type(self.__type__, globalns, localns) |
| 1386 | if new_tp == self.__type__: |
| 1387 | return self |
| 1388 | return type(self)(new_tp, _root=True) |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1389 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1390 | def __repr__(self): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1391 | r = super().__repr__() |
| 1392 | if self.__type__ is not None: |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1393 | r += '[{}]'.format(_type_repr(self.__type__)) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1394 | return r |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1395 | |
| 1396 | def __hash__(self): |
| 1397 | return hash((type(self).__name__, self.__type__)) |
| 1398 | |
| 1399 | def __eq__(self, other): |
| 1400 | if not isinstance(other, _ClassVar): |
| 1401 | return NotImplemented |
| 1402 | if self.__type__ is not None: |
| 1403 | return self.__type__ == other.__type__ |
| 1404 | return self is other |
| 1405 | |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1406 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1407 | ClassVar = _ClassVar(_root=True) |
| 1408 | |
| 1409 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1410 | def cast(typ, val): |
| 1411 | """Cast a value to a type. |
| 1412 | |
| 1413 | This returns the value unchanged. To the type checker this |
| 1414 | signals that the return value has the designated type, but at |
| 1415 | runtime we intentionally don't check anything (we want this |
| 1416 | to be as fast as possible). |
| 1417 | """ |
| 1418 | return val |
| 1419 | |
| 1420 | |
| 1421 | def _get_defaults(func): |
| 1422 | """Internal helper to extract the default arguments, by name.""" |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1423 | try: |
| 1424 | code = func.__code__ |
| 1425 | except AttributeError: |
| 1426 | # Some built-in functions don't have __code__, __defaults__, etc. |
| 1427 | return {} |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1428 | pos_count = code.co_argcount |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1429 | arg_names = code.co_varnames |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1430 | arg_names = arg_names[:pos_count] |
| 1431 | defaults = func.__defaults__ or () |
| 1432 | kwdefaults = func.__kwdefaults__ |
| 1433 | res = dict(kwdefaults) if kwdefaults else {} |
| 1434 | pos_offset = pos_count - len(defaults) |
| 1435 | for name, value in zip(arg_names[pos_offset:], defaults): |
| 1436 | assert name not in res |
| 1437 | res[name] = value |
| 1438 | return res |
| 1439 | |
| 1440 | |
Mariatta | 0230e64 | 2017-02-14 06:11:12 -0800 | [diff] [blame] | 1441 | _allowed_types = (types.FunctionType, types.BuiltinFunctionType, |
| 1442 | types.MethodType, types.ModuleType, |
| 1443 | SlotWrapperType, MethodWrapperType, MethodDescriptorType) |
| 1444 | |
| 1445 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1446 | def get_type_hints(obj, globalns=None, localns=None): |
| 1447 | """Return type hints for an object. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1448 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1449 | This is often the same as obj.__annotations__, but it handles |
| 1450 | forward references encoded as string literals, and if necessary |
| 1451 | adds Optional[t] if a default value equal to None is set. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1452 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1453 | The argument may be a module, class, method, or function. The annotations |
| 1454 | are returned as a dictionary. For classes, annotations include also |
| 1455 | inherited members. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1456 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1457 | TypeError is raised if the argument is not of a type that can contain |
| 1458 | annotations, and an empty dictionary is returned if no annotations are |
| 1459 | present. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1460 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1461 | BEWARE -- the behavior of globalns and localns is counterintuitive |
| 1462 | (unless you are familiar with how eval() and exec() work). The |
| 1463 | search order is locals first, then globals. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1464 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1465 | - If no dict arguments are passed, an attempt is made to use the |
| 1466 | globals from obj, and these are also used as the locals. If the |
| 1467 | object does not appear to have globals, an exception is raised. |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1468 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1469 | - If one dict argument is passed, it is used for both globals and |
| 1470 | locals. |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1471 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1472 | - If two dict arguments are passed, they specify globals and |
| 1473 | locals, respectively. |
| 1474 | """ |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1475 | |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1476 | if getattr(obj, '__no_type_check__', None): |
| 1477 | return {} |
| 1478 | if globalns is None: |
| 1479 | globalns = getattr(obj, '__globals__', {}) |
| 1480 | if localns is None: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1481 | localns = globalns |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1482 | elif localns is None: |
| 1483 | localns = globalns |
| 1484 | # Classes require a special treatment. |
| 1485 | if isinstance(obj, type): |
| 1486 | hints = {} |
| 1487 | for base in reversed(obj.__mro__): |
| 1488 | ann = base.__dict__.get('__annotations__', {}) |
| 1489 | for name, value in ann.items(): |
| 1490 | if value is None: |
| 1491 | value = type(None) |
| 1492 | if isinstance(value, str): |
| 1493 | value = _ForwardRef(value) |
| 1494 | value = _eval_type(value, globalns, localns) |
| 1495 | hints[name] = value |
| 1496 | return hints |
| 1497 | hints = getattr(obj, '__annotations__', None) |
| 1498 | if hints is None: |
| 1499 | # Return empty annotations for something that _could_ have them. |
Mariatta | 0230e64 | 2017-02-14 06:11:12 -0800 | [diff] [blame] | 1500 | if isinstance(obj, _allowed_types): |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1501 | return {} |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 1502 | else: |
| 1503 | raise TypeError('{!r} is not a module, class, method, ' |
| 1504 | 'or function.'.format(obj)) |
| 1505 | defaults = _get_defaults(obj) |
| 1506 | hints = dict(hints) |
| 1507 | for name, value in hints.items(): |
| 1508 | if value is None: |
| 1509 | value = type(None) |
| 1510 | if isinstance(value, str): |
| 1511 | value = _ForwardRef(value) |
| 1512 | value = _eval_type(value, globalns, localns) |
| 1513 | if name in defaults and defaults[name] is None: |
| 1514 | value = Optional[value] |
| 1515 | hints[name] = value |
| 1516 | return hints |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1517 | |
| 1518 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1519 | def no_type_check(arg): |
| 1520 | """Decorator to indicate that annotations are not type hints. |
| 1521 | |
| 1522 | The argument must be a class or function; if it is a class, it |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1523 | applies recursively to all methods and classes defined in that class |
| 1524 | (but not to methods defined in its superclasses or subclasses). |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1525 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1526 | This mutates the function(s) or class(es) in place. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1527 | """ |
| 1528 | if isinstance(arg, type): |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1529 | arg_attrs = arg.__dict__.copy() |
| 1530 | for attr, val in arg.__dict__.items(): |
| 1531 | if val in arg.__bases__: |
| 1532 | arg_attrs.pop(attr) |
| 1533 | for obj in arg_attrs.values(): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1534 | if isinstance(obj, types.FunctionType): |
| 1535 | obj.__no_type_check__ = True |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1536 | if isinstance(obj, type): |
| 1537 | no_type_check(obj) |
| 1538 | try: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1539 | arg.__no_type_check__ = True |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 1540 | except TypeError: # built-in classes |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1541 | pass |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1542 | return arg |
| 1543 | |
| 1544 | |
| 1545 | def no_type_check_decorator(decorator): |
| 1546 | """Decorator to give another decorator the @no_type_check effect. |
| 1547 | |
| 1548 | This wraps the decorator with something that wraps the decorated |
| 1549 | function in @no_type_check. |
| 1550 | """ |
| 1551 | |
| 1552 | @functools.wraps(decorator) |
| 1553 | def wrapped_decorator(*args, **kwds): |
| 1554 | func = decorator(*args, **kwds) |
| 1555 | func = no_type_check(func) |
| 1556 | return func |
| 1557 | |
| 1558 | return wrapped_decorator |
| 1559 | |
| 1560 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1561 | def _overload_dummy(*args, **kwds): |
| 1562 | """Helper for @overload to raise when called.""" |
| 1563 | raise NotImplementedError( |
| 1564 | "You should not call an overloaded function. " |
| 1565 | "A series of @overload-decorated functions " |
| 1566 | "outside a stub module should always be followed " |
| 1567 | "by an implementation that is not @overload-ed.") |
| 1568 | |
| 1569 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1570 | def overload(func): |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1571 | """Decorator for overloaded functions/methods. |
| 1572 | |
| 1573 | In a stub file, place two or more stub definitions for the same |
| 1574 | function in a row, each decorated with @overload. For example: |
| 1575 | |
| 1576 | @overload |
| 1577 | def utf8(value: None) -> None: ... |
| 1578 | @overload |
| 1579 | def utf8(value: bytes) -> bytes: ... |
| 1580 | @overload |
| 1581 | def utf8(value: str) -> bytes: ... |
| 1582 | |
| 1583 | In a non-stub file (i.e. a regular .py file), do the same but |
| 1584 | follow it with an implementation. The implementation should *not* |
| 1585 | be decorated with @overload. For example: |
| 1586 | |
| 1587 | @overload |
| 1588 | def utf8(value: None) -> None: ... |
| 1589 | @overload |
| 1590 | def utf8(value: bytes) -> bytes: ... |
| 1591 | @overload |
| 1592 | def utf8(value: str) -> bytes: ... |
| 1593 | def utf8(value): |
| 1594 | # implementation goes here |
| 1595 | """ |
| 1596 | return _overload_dummy |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1597 | |
| 1598 | |
| 1599 | class _ProtocolMeta(GenericMeta): |
| 1600 | """Internal metaclass for _Protocol. |
| 1601 | |
| 1602 | This exists so _Protocol classes can be generic without deriving |
| 1603 | from Generic. |
| 1604 | """ |
| 1605 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1606 | def __instancecheck__(self, obj): |
Guido van Rossum | ca4b252 | 2016-11-19 10:32:41 -0800 | [diff] [blame] | 1607 | if _Protocol not in self.__bases__: |
| 1608 | return super().__instancecheck__(obj) |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1609 | raise TypeError("Protocols cannot be used with isinstance().") |
| 1610 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1611 | def __subclasscheck__(self, cls): |
| 1612 | if not self._is_protocol: |
| 1613 | # No structural checks since this isn't a protocol. |
| 1614 | return NotImplemented |
| 1615 | |
| 1616 | if self is _Protocol: |
| 1617 | # Every class is a subclass of the empty protocol. |
| 1618 | return True |
| 1619 | |
| 1620 | # Find all attributes defined in the protocol. |
| 1621 | attrs = self._get_protocol_attrs() |
| 1622 | |
| 1623 | for attr in attrs: |
| 1624 | if not any(attr in d.__dict__ for d in cls.__mro__): |
| 1625 | return False |
| 1626 | return True |
| 1627 | |
| 1628 | def _get_protocol_attrs(self): |
| 1629 | # Get all Protocol base classes. |
| 1630 | protocol_bases = [] |
| 1631 | for c in self.__mro__: |
| 1632 | if getattr(c, '_is_protocol', False) and c.__name__ != '_Protocol': |
| 1633 | protocol_bases.append(c) |
| 1634 | |
| 1635 | # Get attributes included in protocol. |
| 1636 | attrs = set() |
| 1637 | for base in protocol_bases: |
| 1638 | for attr in base.__dict__.keys(): |
| 1639 | # Include attributes not defined in any non-protocol bases. |
| 1640 | for c in self.__mro__: |
| 1641 | if (c is not base and attr in c.__dict__ and |
| 1642 | not getattr(c, '_is_protocol', False)): |
| 1643 | break |
| 1644 | else: |
| 1645 | if (not attr.startswith('_abc_') and |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1646 | attr != '__abstractmethods__' and |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1647 | attr != '__annotations__' and |
| 1648 | attr != '__weakref__' and |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1649 | attr != '_is_protocol' and |
| 1650 | attr != '__dict__' and |
| 1651 | attr != '__args__' and |
| 1652 | attr != '__slots__' and |
| 1653 | attr != '_get_protocol_attrs' and |
| 1654 | attr != '__next_in_mro__' and |
| 1655 | attr != '__parameters__' and |
| 1656 | attr != '__origin__' and |
Guido van Rossum | 7ef22d6 | 2016-10-21 14:27:58 -0700 | [diff] [blame] | 1657 | attr != '__orig_bases__' and |
Guido van Rossum | 1cea70f | 2016-05-18 08:35:00 -0700 | [diff] [blame] | 1658 | attr != '__extra__' and |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1659 | attr != '__tree_hash__' and |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1660 | attr != '__module__'): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1661 | attrs.add(attr) |
| 1662 | |
| 1663 | return attrs |
| 1664 | |
| 1665 | |
| 1666 | class _Protocol(metaclass=_ProtocolMeta): |
| 1667 | """Internal base class for protocol classes. |
| 1668 | |
Guido van Rossum | b24569a | 2016-11-20 18:01:29 -0800 | [diff] [blame] | 1669 | This implements a simple-minded structural issubclass check |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1670 | (similar but more general than the one-offs in collections.abc |
| 1671 | such as Hashable). |
| 1672 | """ |
| 1673 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1674 | __slots__ = () |
| 1675 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1676 | _is_protocol = True |
| 1677 | |
| 1678 | |
| 1679 | # Various ABCs mimicking those in collections.abc. |
| 1680 | # A few are simply re-exported for completeness. |
| 1681 | |
| 1682 | Hashable = collections_abc.Hashable # Not generic. |
| 1683 | |
| 1684 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1685 | if hasattr(collections_abc, 'Awaitable'): |
| 1686 | class Awaitable(Generic[T_co], extra=collections_abc.Awaitable): |
| 1687 | __slots__ = () |
Guido van Rossum | 62fe1bb | 2016-10-29 16:05:26 -0700 | [diff] [blame] | 1688 | |
| 1689 | __all__.append('Awaitable') |
| 1690 | |
| 1691 | |
| 1692 | if hasattr(collections_abc, 'Coroutine'): |
| 1693 | class Coroutine(Awaitable[V_co], Generic[T_co, T_contra, V_co], |
| 1694 | extra=collections_abc.Coroutine): |
| 1695 | __slots__ = () |
| 1696 | |
| 1697 | __all__.append('Coroutine') |
Guido van Rossum | f17c200 | 2015-12-03 17:31:24 -0800 | [diff] [blame] | 1698 | |
| 1699 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1700 | if hasattr(collections_abc, 'AsyncIterable'): |
Guido van Rossum | f17c200 | 2015-12-03 17:31:24 -0800 | [diff] [blame] | 1701 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1702 | class AsyncIterable(Generic[T_co], extra=collections_abc.AsyncIterable): |
| 1703 | __slots__ = () |
Guido van Rossum | f17c200 | 2015-12-03 17:31:24 -0800 | [diff] [blame] | 1704 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1705 | class AsyncIterator(AsyncIterable[T_co], |
| 1706 | extra=collections_abc.AsyncIterator): |
| 1707 | __slots__ = () |
| 1708 | |
Guido van Rossum | 62fe1bb | 2016-10-29 16:05:26 -0700 | [diff] [blame] | 1709 | __all__.append('AsyncIterable') |
| 1710 | __all__.append('AsyncIterator') |
Guido van Rossum | f17c200 | 2015-12-03 17:31:24 -0800 | [diff] [blame] | 1711 | |
| 1712 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1713 | class Iterable(Generic[T_co], extra=collections_abc.Iterable): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1714 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1715 | |
| 1716 | |
| 1717 | class Iterator(Iterable[T_co], extra=collections_abc.Iterator): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1718 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1719 | |
| 1720 | |
| 1721 | class SupportsInt(_Protocol): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1722 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1723 | |
| 1724 | @abstractmethod |
| 1725 | def __int__(self) -> int: |
| 1726 | pass |
| 1727 | |
| 1728 | |
| 1729 | class SupportsFloat(_Protocol): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1730 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1731 | |
| 1732 | @abstractmethod |
| 1733 | def __float__(self) -> float: |
| 1734 | pass |
| 1735 | |
| 1736 | |
| 1737 | class SupportsComplex(_Protocol): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1738 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1739 | |
| 1740 | @abstractmethod |
| 1741 | def __complex__(self) -> complex: |
| 1742 | pass |
| 1743 | |
| 1744 | |
| 1745 | class SupportsBytes(_Protocol): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1746 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1747 | |
| 1748 | @abstractmethod |
| 1749 | def __bytes__(self) -> bytes: |
| 1750 | pass |
| 1751 | |
| 1752 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1753 | class SupportsAbs(_Protocol[T_co]): |
| 1754 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1755 | |
| 1756 | @abstractmethod |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1757 | def __abs__(self) -> T_co: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1758 | pass |
| 1759 | |
| 1760 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1761 | class SupportsRound(_Protocol[T_co]): |
| 1762 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1763 | |
| 1764 | @abstractmethod |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1765 | def __round__(self, ndigits: int = 0) -> T_co: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1766 | pass |
| 1767 | |
| 1768 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1769 | if hasattr(collections_abc, 'Reversible'): |
| 1770 | class Reversible(Iterable[T_co], extra=collections_abc.Reversible): |
| 1771 | __slots__ = () |
| 1772 | else: |
| 1773 | class Reversible(_Protocol[T_co]): |
| 1774 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1775 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1776 | @abstractmethod |
| 1777 | def __reversed__(self) -> 'Iterator[T_co]': |
| 1778 | pass |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1779 | |
| 1780 | |
| 1781 | Sized = collections_abc.Sized # Not generic. |
| 1782 | |
| 1783 | |
| 1784 | class Container(Generic[T_co], extra=collections_abc.Container): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1785 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1786 | |
| 1787 | |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1788 | if hasattr(collections_abc, 'Collection'): |
| 1789 | class Collection(Sized, Iterable[T_co], Container[T_co], |
| 1790 | extra=collections_abc.Collection): |
| 1791 | __slots__ = () |
| 1792 | |
| 1793 | __all__.append('Collection') |
| 1794 | |
| 1795 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1796 | # Callable was defined earlier. |
| 1797 | |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1798 | if hasattr(collections_abc, 'Collection'): |
| 1799 | class AbstractSet(Collection[T_co], |
| 1800 | extra=collections_abc.Set): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1801 | __slots__ = () |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1802 | else: |
| 1803 | class AbstractSet(Sized, Iterable[T_co], Container[T_co], |
| 1804 | extra=collections_abc.Set): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1805 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1806 | |
| 1807 | |
| 1808 | class MutableSet(AbstractSet[T], extra=collections_abc.MutableSet): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1809 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1810 | |
| 1811 | |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1812 | # NOTE: It is only covariant in the value type. |
| 1813 | if hasattr(collections_abc, 'Collection'): |
| 1814 | class Mapping(Collection[KT], Generic[KT, VT_co], |
| 1815 | extra=collections_abc.Mapping): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1816 | __slots__ = () |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1817 | else: |
| 1818 | class Mapping(Sized, Iterable[KT], Container[KT], Generic[KT, VT_co], |
| 1819 | extra=collections_abc.Mapping): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1820 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1821 | |
| 1822 | |
| 1823 | class MutableMapping(Mapping[KT, VT], extra=collections_abc.MutableMapping): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1824 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1825 | |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 1826 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1827 | if hasattr(collections_abc, 'Reversible'): |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1828 | if hasattr(collections_abc, 'Collection'): |
| 1829 | class Sequence(Reversible[T_co], Collection[T_co], |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 1830 | extra=collections_abc.Sequence): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1831 | __slots__ = () |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1832 | else: |
| 1833 | class Sequence(Sized, Reversible[T_co], Container[T_co], |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 1834 | extra=collections_abc.Sequence): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1835 | __slots__ = () |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1836 | else: |
| 1837 | class Sequence(Sized, Iterable[T_co], Container[T_co], |
| 1838 | extra=collections_abc.Sequence): |
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 | |
| 1842 | class MutableSequence(Sequence[T], extra=collections_abc.MutableSequence): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1843 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1844 | |
| 1845 | |
| 1846 | class ByteString(Sequence[int], extra=collections_abc.ByteString): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1847 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1848 | |
| 1849 | |
Guido van Rossum | 1cea70f | 2016-05-18 08:35:00 -0700 | [diff] [blame] | 1850 | class List(list, MutableSequence[T], extra=list): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1851 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1852 | __slots__ = () |
| 1853 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1854 | def __new__(cls, *args, **kwds): |
| 1855 | if _geqv(cls, List): |
| 1856 | raise TypeError("Type List cannot be instantiated; " |
| 1857 | "use list() instead") |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1858 | return _generic_new(list, cls, *args, **kwds) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1859 | |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 1860 | |
Raymond Hettinger | 8049052 | 2017-01-16 22:42:37 -0800 | [diff] [blame] | 1861 | class Deque(collections.deque, MutableSequence[T], extra=collections.deque): |
| 1862 | |
| 1863 | __slots__ = () |
| 1864 | |
| 1865 | def __new__(cls, *args, **kwds): |
| 1866 | if _geqv(cls, Deque): |
Mariatta | 0230e64 | 2017-02-14 06:11:12 -0800 | [diff] [blame] | 1867 | return collections.deque(*args, **kwds) |
Raymond Hettinger | 8049052 | 2017-01-16 22:42:37 -0800 | [diff] [blame] | 1868 | return _generic_new(collections.deque, cls, *args, **kwds) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1869 | |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 1870 | |
Guido van Rossum | 1cea70f | 2016-05-18 08:35:00 -0700 | [diff] [blame] | 1871 | class Set(set, MutableSet[T], extra=set): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1872 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1873 | __slots__ = () |
| 1874 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1875 | def __new__(cls, *args, **kwds): |
| 1876 | if _geqv(cls, Set): |
| 1877 | raise TypeError("Type Set cannot be instantiated; " |
| 1878 | "use set() instead") |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1879 | return _generic_new(set, cls, *args, **kwds) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1880 | |
| 1881 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1882 | class FrozenSet(frozenset, AbstractSet[T_co], extra=frozenset): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1883 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1884 | |
| 1885 | def __new__(cls, *args, **kwds): |
| 1886 | if _geqv(cls, FrozenSet): |
| 1887 | raise TypeError("Type FrozenSet cannot be instantiated; " |
| 1888 | "use frozenset() instead") |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1889 | return _generic_new(frozenset, cls, *args, **kwds) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1890 | |
| 1891 | |
| 1892 | class MappingView(Sized, Iterable[T_co], extra=collections_abc.MappingView): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1893 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1894 | |
| 1895 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1896 | class KeysView(MappingView[KT], AbstractSet[KT], |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1897 | extra=collections_abc.KeysView): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1898 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1899 | |
| 1900 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1901 | class ItemsView(MappingView[Tuple[KT, VT_co]], |
Guido van Rossum | 0e0563c | 2016-04-05 14:54:25 -0700 | [diff] [blame] | 1902 | AbstractSet[Tuple[KT, VT_co]], |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1903 | Generic[KT, VT_co], |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1904 | extra=collections_abc.ItemsView): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1905 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1906 | |
| 1907 | |
| 1908 | class ValuesView(MappingView[VT_co], extra=collections_abc.ValuesView): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1909 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1910 | |
| 1911 | |
Brett Cannon | f3ad042 | 2016-04-15 10:51:30 -0700 | [diff] [blame] | 1912 | if hasattr(contextlib, 'AbstractContextManager'): |
| 1913 | class ContextManager(Generic[T_co], extra=contextlib.AbstractContextManager): |
| 1914 | __slots__ = () |
| 1915 | __all__.append('ContextManager') |
| 1916 | |
| 1917 | |
Guido van Rossum | 1cea70f | 2016-05-18 08:35:00 -0700 | [diff] [blame] | 1918 | class Dict(dict, MutableMapping[KT, VT], extra=dict): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1919 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1920 | __slots__ = () |
| 1921 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1922 | def __new__(cls, *args, **kwds): |
| 1923 | if _geqv(cls, Dict): |
| 1924 | raise TypeError("Type Dict cannot be instantiated; " |
| 1925 | "use dict() instead") |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1926 | return _generic_new(dict, cls, *args, **kwds) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1927 | |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 1928 | |
Guido van Rossum | 1cea70f | 2016-05-18 08:35:00 -0700 | [diff] [blame] | 1929 | class DefaultDict(collections.defaultdict, MutableMapping[KT, VT], |
| 1930 | extra=collections.defaultdict): |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1931 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1932 | __slots__ = () |
| 1933 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1934 | def __new__(cls, *args, **kwds): |
| 1935 | if _geqv(cls, DefaultDict): |
Mariatta | 0230e64 | 2017-02-14 06:11:12 -0800 | [diff] [blame] | 1936 | return collections.defaultdict(*args, **kwds) |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1937 | return _generic_new(collections.defaultdict, cls, *args, **kwds) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1938 | |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 1939 | |
Mariatta | 0230e64 | 2017-02-14 06:11:12 -0800 | [diff] [blame] | 1940 | class Counter(collections.Counter, Dict[T, int], extra=collections.Counter): |
| 1941 | |
| 1942 | __slots__ = () |
| 1943 | |
| 1944 | def __new__(cls, *args, **kwds): |
| 1945 | if _geqv(cls, Counter): |
| 1946 | return collections.Counter(*args, **kwds) |
| 1947 | return _generic_new(collections.Counter, cls, *args, **kwds) |
| 1948 | |
| 1949 | |
| 1950 | if hasattr(collections, 'ChainMap'): |
| 1951 | # ChainMap only exists in 3.3+ |
| 1952 | __all__.append('ChainMap') |
| 1953 | |
| 1954 | class ChainMap(collections.ChainMap, MutableMapping[KT, VT], |
| 1955 | extra=collections.ChainMap): |
| 1956 | |
| 1957 | __slots__ = () |
| 1958 | |
| 1959 | def __new__(cls, *args, **kwds): |
| 1960 | if _geqv(cls, ChainMap): |
| 1961 | return collections.ChainMap(*args, **kwds) |
| 1962 | return _generic_new(collections.ChainMap, cls, *args, **kwds) |
| 1963 | |
| 1964 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1965 | # Determine what base class to use for Generator. |
| 1966 | if hasattr(collections_abc, 'Generator'): |
| 1967 | # Sufficiently recent versions of 3.5 have a Generator ABC. |
| 1968 | _G_base = collections_abc.Generator |
| 1969 | else: |
| 1970 | # Fall back on the exact type. |
| 1971 | _G_base = types.GeneratorType |
| 1972 | |
| 1973 | |
| 1974 | class Generator(Iterator[T_co], Generic[T_co, T_contra, V_co], |
| 1975 | extra=_G_base): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1976 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1977 | |
| 1978 | def __new__(cls, *args, **kwds): |
| 1979 | if _geqv(cls, Generator): |
| 1980 | raise TypeError("Type Generator cannot be instantiated; " |
| 1981 | "create a subclass instead") |
Guido van Rossum | 5fc25a8 | 2016-10-29 08:54:56 -0700 | [diff] [blame] | 1982 | return _generic_new(_G_base, cls, *args, **kwds) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1983 | |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 1984 | |
Guido van Rossum | e9ed560 | 2017-01-18 13:10:31 -0800 | [diff] [blame] | 1985 | if hasattr(collections_abc, 'AsyncGenerator'): |
| 1986 | class AsyncGenerator(AsyncIterator[T_co], Generic[T_co, T_contra], |
| 1987 | extra=collections_abc.AsyncGenerator): |
| 1988 | __slots__ = () |
| 1989 | |
| 1990 | __all__.append('AsyncGenerator') |
| 1991 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1992 | |
Guido van Rossum | eb9aca3 | 2016-05-24 16:38:22 -0700 | [diff] [blame] | 1993 | # Internal type variable used for Type[]. |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1994 | CT_co = TypeVar('CT_co', covariant=True, bound=type) |
Guido van Rossum | eb9aca3 | 2016-05-24 16:38:22 -0700 | [diff] [blame] | 1995 | |
| 1996 | |
Guido van Rossum | b22c708 | 2016-05-26 09:56:19 -0700 | [diff] [blame] | 1997 | # 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] | 1998 | class Type(Generic[CT_co], extra=type): |
Guido van Rossum | b22c708 | 2016-05-26 09:56:19 -0700 | [diff] [blame] | 1999 | """A special construct usable to annotate class objects. |
Guido van Rossum | eb9aca3 | 2016-05-24 16:38:22 -0700 | [diff] [blame] | 2000 | |
| 2001 | For example, suppose we have the following classes:: |
| 2002 | |
| 2003 | class User: ... # Abstract base for User classes |
| 2004 | class BasicUser(User): ... |
| 2005 | class ProUser(User): ... |
| 2006 | class TeamUser(User): ... |
| 2007 | |
| 2008 | And a function that takes a class argument that's a subclass of |
| 2009 | User and returns an instance of the corresponding class:: |
| 2010 | |
| 2011 | U = TypeVar('U', bound=User) |
| 2012 | def new_user(user_class: Type[U]) -> U: |
| 2013 | user = user_class() |
| 2014 | # (Here we could write the user object to a database) |
| 2015 | return user |
| 2016 | |
| 2017 | joe = new_user(BasicUser) |
| 2018 | |
| 2019 | At this point the type checker knows that joe has type BasicUser. |
| 2020 | """ |
| 2021 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 2022 | __slots__ = () |
| 2023 | |
Guido van Rossum | eb9aca3 | 2016-05-24 16:38:22 -0700 | [diff] [blame] | 2024 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2025 | def _make_nmtuple(name, types): |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2026 | msg = "NamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a type" |
| 2027 | types = [(n, _type_check(t, msg)) for n, t in types] |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2028 | nm_tpl = collections.namedtuple(name, [n for n, t in types]) |
Guido van Rossum | 83ec302 | 2017-01-17 20:43:28 -0800 | [diff] [blame] | 2029 | # Prior to PEP 526, only _field_types attribute was assigned. |
| 2030 | # Now, both __annotations__ and _field_types are used to maintain compatibility. |
| 2031 | nm_tpl.__annotations__ = nm_tpl._field_types = collections.OrderedDict(types) |
Guido van Rossum | 557d1eb | 2015-11-19 08:16:31 -0800 | [diff] [blame] | 2032 | try: |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2033 | nm_tpl.__module__ = sys._getframe(2).f_globals.get('__name__', '__main__') |
Guido van Rossum | 557d1eb | 2015-11-19 08:16:31 -0800 | [diff] [blame] | 2034 | except (AttributeError, ValueError): |
| 2035 | pass |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2036 | return nm_tpl |
| 2037 | |
| 2038 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2039 | _PY36 = sys.version_info[:2] >= (3, 6) |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2040 | |
Mariatta | 0230e64 | 2017-02-14 06:11:12 -0800 | [diff] [blame] | 2041 | # attributes prohibited to set in NamedTuple class syntax |
| 2042 | _prohibited = ('__new__', '__init__', '__slots__', '__getnewargs__', |
| 2043 | '_fields', '_field_defaults', '_field_types', |
| 2044 | '_make', '_replace', '_asdict') |
| 2045 | |
| 2046 | _special = ('__module__', '__name__', '__qualname__', '__annotations__') |
| 2047 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2048 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2049 | class NamedTupleMeta(type): |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2050 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2051 | def __new__(cls, typename, bases, ns): |
| 2052 | if ns.get('_root', False): |
| 2053 | return super().__new__(cls, typename, bases, ns) |
| 2054 | if not _PY36: |
| 2055 | raise TypeError("Class syntax for NamedTuple is only supported" |
| 2056 | " in Python 3.6+") |
| 2057 | types = ns.get('__annotations__', {}) |
Guido van Rossum | 3c268be | 2017-01-18 08:03:50 -0800 | [diff] [blame] | 2058 | nm_tpl = _make_nmtuple(typename, types.items()) |
| 2059 | defaults = [] |
| 2060 | defaults_dict = {} |
| 2061 | for field_name in types: |
| 2062 | if field_name in ns: |
| 2063 | default_value = ns[field_name] |
| 2064 | defaults.append(default_value) |
| 2065 | defaults_dict[field_name] = default_value |
| 2066 | elif defaults: |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 2067 | raise TypeError("Non-default namedtuple field {field_name} cannot " |
| 2068 | "follow default field(s) {default_names}" |
Guido van Rossum | 3c268be | 2017-01-18 08:03:50 -0800 | [diff] [blame] | 2069 | .format(field_name=field_name, |
| 2070 | default_names=', '.join(defaults_dict.keys()))) |
| 2071 | nm_tpl.__new__.__defaults__ = tuple(defaults) |
| 2072 | nm_tpl._field_defaults = defaults_dict |
Guido van Rossum | 95919c0 | 2017-01-22 17:47:20 -0800 | [diff] [blame] | 2073 | # update from user namespace without overriding special namedtuple attributes |
| 2074 | for key in ns: |
Mariatta | 0230e64 | 2017-02-14 06:11:12 -0800 | [diff] [blame] | 2075 | if key in _prohibited: |
| 2076 | raise AttributeError("Cannot overwrite NamedTuple attribute " + key) |
| 2077 | elif key not in _special and key not in nm_tpl._fields: |
Guido van Rossum | 95919c0 | 2017-01-22 17:47:20 -0800 | [diff] [blame] | 2078 | setattr(nm_tpl, key, ns[key]) |
Guido van Rossum | 3c268be | 2017-01-18 08:03:50 -0800 | [diff] [blame] | 2079 | return nm_tpl |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2080 | |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 2081 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2082 | class NamedTuple(metaclass=NamedTupleMeta): |
| 2083 | """Typed version of namedtuple. |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2084 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2085 | Usage in Python versions >= 3.6:: |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2086 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2087 | class Employee(NamedTuple): |
| 2088 | name: str |
| 2089 | id: int |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2090 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2091 | This is equivalent to:: |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2092 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2093 | Employee = collections.namedtuple('Employee', ['name', 'id']) |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2094 | |
Guido van Rossum | 83ec302 | 2017-01-17 20:43:28 -0800 | [diff] [blame] | 2095 | The resulting class has extra __annotations__ and _field_types |
| 2096 | attributes, giving an ordered dict mapping field names to types. |
| 2097 | __annotations__ should be preferred, while _field_types |
| 2098 | is kept to maintain pre PEP 526 compatibility. (The field names |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2099 | are in the _fields attribute, which is part of the namedtuple |
| 2100 | API.) Alternative equivalent keyword syntax is also accepted:: |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2101 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2102 | Employee = NamedTuple('Employee', name=str, id=int) |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2103 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2104 | In Python versions <= 3.5 use:: |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2105 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2106 | Employee = NamedTuple('Employee', [('name', str), ('id', int)]) |
| 2107 | """ |
| 2108 | _root = True |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2109 | |
Guido van Rossum | 2f84144 | 2016-11-15 09:48:06 -0800 | [diff] [blame] | 2110 | def __new__(self, typename, fields=None, **kwargs): |
| 2111 | if kwargs and not _PY36: |
| 2112 | raise TypeError("Keyword syntax for NamedTuple is only supported" |
| 2113 | " in Python 3.6+") |
| 2114 | if fields is None: |
| 2115 | fields = kwargs.items() |
| 2116 | elif kwargs: |
| 2117 | raise TypeError("Either list of fields or keywords" |
| 2118 | " can be provided to NamedTuple, not both") |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 2119 | return _make_nmtuple(typename, fields) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2120 | |
| 2121 | |
Guido van Rossum | 91185fe | 2016-06-08 11:19:11 -0700 | [diff] [blame] | 2122 | def NewType(name, tp): |
| 2123 | """NewType creates simple unique types with almost zero |
| 2124 | runtime overhead. NewType(name, tp) is considered a subtype of tp |
| 2125 | by static type checkers. At runtime, NewType(name, tp) returns |
| 2126 | a dummy function that simply returns its argument. Usage:: |
| 2127 | |
| 2128 | UserId = NewType('UserId', int) |
| 2129 | |
| 2130 | def name_by_id(user_id: UserId) -> str: |
| 2131 | ... |
| 2132 | |
| 2133 | UserId('user') # Fails type check |
| 2134 | |
| 2135 | name_by_id(42) # Fails type check |
| 2136 | name_by_id(UserId(42)) # OK |
| 2137 | |
| 2138 | num = UserId(5) + 1 # type: int |
| 2139 | """ |
| 2140 | |
| 2141 | def new_type(x): |
| 2142 | return x |
| 2143 | |
| 2144 | new_type.__name__ = name |
| 2145 | new_type.__supertype__ = tp |
| 2146 | return new_type |
| 2147 | |
| 2148 | |
Guido van Rossum | 0e0563c | 2016-04-05 14:54:25 -0700 | [diff] [blame] | 2149 | # Python-version-specific alias (Python 2: unicode; Python 3: str) |
| 2150 | Text = str |
| 2151 | |
| 2152 | |
Guido van Rossum | 91185fe | 2016-06-08 11:19:11 -0700 | [diff] [blame] | 2153 | # Constant that's True when type checking, but False here. |
| 2154 | TYPE_CHECKING = False |
| 2155 | |
| 2156 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2157 | class IO(Generic[AnyStr]): |
| 2158 | """Generic base class for TextIO and BinaryIO. |
| 2159 | |
| 2160 | This is an abstract, generic version of the return of open(). |
| 2161 | |
| 2162 | NOTE: This does not distinguish between the different possible |
| 2163 | classes (text vs. binary, read vs. write vs. read/write, |
| 2164 | append-only, unbuffered). The TextIO and BinaryIO subclasses |
| 2165 | below capture the distinctions between text vs. binary, which is |
| 2166 | pervasive in the interface; however we currently do not offer a |
| 2167 | way to track the other distinctions in the type system. |
| 2168 | """ |
| 2169 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 2170 | __slots__ = () |
| 2171 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2172 | @abstractproperty |
| 2173 | def mode(self) -> str: |
| 2174 | pass |
| 2175 | |
| 2176 | @abstractproperty |
| 2177 | def name(self) -> str: |
| 2178 | pass |
| 2179 | |
| 2180 | @abstractmethod |
| 2181 | def close(self) -> None: |
| 2182 | pass |
| 2183 | |
| 2184 | @abstractmethod |
| 2185 | def closed(self) -> bool: |
| 2186 | pass |
| 2187 | |
| 2188 | @abstractmethod |
| 2189 | def fileno(self) -> int: |
| 2190 | pass |
| 2191 | |
| 2192 | @abstractmethod |
| 2193 | def flush(self) -> None: |
| 2194 | pass |
| 2195 | |
| 2196 | @abstractmethod |
| 2197 | def isatty(self) -> bool: |
| 2198 | pass |
| 2199 | |
| 2200 | @abstractmethod |
| 2201 | def read(self, n: int = -1) -> AnyStr: |
| 2202 | pass |
| 2203 | |
| 2204 | @abstractmethod |
| 2205 | def readable(self) -> bool: |
| 2206 | pass |
| 2207 | |
| 2208 | @abstractmethod |
| 2209 | def readline(self, limit: int = -1) -> AnyStr: |
| 2210 | pass |
| 2211 | |
| 2212 | @abstractmethod |
| 2213 | def readlines(self, hint: int = -1) -> List[AnyStr]: |
| 2214 | pass |
| 2215 | |
| 2216 | @abstractmethod |
| 2217 | def seek(self, offset: int, whence: int = 0) -> int: |
| 2218 | pass |
| 2219 | |
| 2220 | @abstractmethod |
| 2221 | def seekable(self) -> bool: |
| 2222 | pass |
| 2223 | |
| 2224 | @abstractmethod |
| 2225 | def tell(self) -> int: |
| 2226 | pass |
| 2227 | |
| 2228 | @abstractmethod |
| 2229 | def truncate(self, size: int = None) -> int: |
| 2230 | pass |
| 2231 | |
| 2232 | @abstractmethod |
| 2233 | def writable(self) -> bool: |
| 2234 | pass |
| 2235 | |
| 2236 | @abstractmethod |
| 2237 | def write(self, s: AnyStr) -> int: |
| 2238 | pass |
| 2239 | |
| 2240 | @abstractmethod |
| 2241 | def writelines(self, lines: List[AnyStr]) -> None: |
| 2242 | pass |
| 2243 | |
| 2244 | @abstractmethod |
| 2245 | def __enter__(self) -> 'IO[AnyStr]': |
| 2246 | pass |
| 2247 | |
| 2248 | @abstractmethod |
| 2249 | def __exit__(self, type, value, traceback) -> None: |
| 2250 | pass |
| 2251 | |
| 2252 | |
| 2253 | class BinaryIO(IO[bytes]): |
| 2254 | """Typed version of the return of open() in binary mode.""" |
| 2255 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 2256 | __slots__ = () |
| 2257 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2258 | @abstractmethod |
| 2259 | def write(self, s: Union[bytes, bytearray]) -> int: |
| 2260 | pass |
| 2261 | |
| 2262 | @abstractmethod |
| 2263 | def __enter__(self) -> 'BinaryIO': |
| 2264 | pass |
| 2265 | |
| 2266 | |
| 2267 | class TextIO(IO[str]): |
| 2268 | """Typed version of the return of open() in text mode.""" |
| 2269 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 2270 | __slots__ = () |
| 2271 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2272 | @abstractproperty |
| 2273 | def buffer(self) -> BinaryIO: |
| 2274 | pass |
| 2275 | |
| 2276 | @abstractproperty |
| 2277 | def encoding(self) -> str: |
| 2278 | pass |
| 2279 | |
| 2280 | @abstractproperty |
Guido van Rossum | 991d14f | 2016-11-09 13:12:51 -0800 | [diff] [blame] | 2281 | def errors(self) -> Optional[str]: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2282 | pass |
| 2283 | |
| 2284 | @abstractproperty |
| 2285 | def line_buffering(self) -> bool: |
| 2286 | pass |
| 2287 | |
| 2288 | @abstractproperty |
| 2289 | def newlines(self) -> Any: |
| 2290 | pass |
| 2291 | |
| 2292 | @abstractmethod |
| 2293 | def __enter__(self) -> 'TextIO': |
| 2294 | pass |
| 2295 | |
| 2296 | |
| 2297 | class io: |
| 2298 | """Wrapper namespace for IO generic classes.""" |
| 2299 | |
| 2300 | __all__ = ['IO', 'TextIO', 'BinaryIO'] |
| 2301 | IO = IO |
| 2302 | TextIO = TextIO |
| 2303 | BinaryIO = BinaryIO |
| 2304 | |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 2305 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2306 | io.__name__ = __name__ + '.io' |
| 2307 | sys.modules[io.__name__] = io |
| 2308 | |
| 2309 | |
| 2310 | Pattern = _TypeAlias('Pattern', AnyStr, type(stdlib_re.compile('')), |
| 2311 | lambda p: p.pattern) |
| 2312 | Match = _TypeAlias('Match', AnyStr, type(stdlib_re.match('', '')), |
| 2313 | lambda m: m.re.pattern) |
| 2314 | |
| 2315 | |
| 2316 | class re: |
| 2317 | """Wrapper namespace for re type aliases.""" |
| 2318 | |
| 2319 | __all__ = ['Pattern', 'Match'] |
| 2320 | Pattern = Pattern |
| 2321 | Match = Match |
| 2322 | |
Guido van Rossum | d7adfe1 | 2017-01-22 17:43:53 -0800 | [diff] [blame] | 2323 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2324 | re.__name__ = __name__ + '.re' |
| 2325 | sys.modules[re.__name__] = re |