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