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