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