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 | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 295 | if isinstance(parameter, TypeVar): |
| 296 | raise TypeError("%s cannot be re-parameterized." % self.type_var) |
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): |
| 625 | r = super().__repr__() |
| 626 | if self.__union_params__: |
| 627 | r += '[%s]' % (', '.join(_type_repr(t) |
| 628 | for t in self.__union_params__)) |
| 629 | return r |
| 630 | |
| 631 | @_tp_cache |
| 632 | def __getitem__(self, parameters): |
| 633 | if self.__union_params__ is not None: |
| 634 | raise TypeError( |
| 635 | "Cannot subscript an existing Union. Use Union[u, t] instead.") |
| 636 | if parameters == (): |
| 637 | raise TypeError("Cannot take a Union of no types.") |
| 638 | if not isinstance(parameters, tuple): |
| 639 | parameters = (parameters,) |
| 640 | return self.__class__(parameters, _root=True) |
| 641 | |
| 642 | def __eq__(self, other): |
| 643 | if not isinstance(other, _Union): |
| 644 | return NotImplemented |
| 645 | return self.__union_set_params__ == other.__union_set_params__ |
| 646 | |
| 647 | def __hash__(self): |
| 648 | return hash(self.__union_set_params__) |
| 649 | |
| 650 | def __instancecheck__(self, obj): |
| 651 | raise TypeError("Unions cannot be used with isinstance().") |
| 652 | |
| 653 | def __subclasscheck__(self, cls): |
| 654 | raise TypeError("Unions cannot be used with issubclass().") |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 655 | |
| 656 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 657 | Union = _Union(_root=True) |
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 | class _Optional(_FinalTypingBase, _root=True): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 661 | """Optional type. |
| 662 | |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 663 | Optional[X] is equivalent to Union[X, None]. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 664 | """ |
| 665 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 666 | __slots__ = () |
| 667 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 668 | @_tp_cache |
| 669 | def __getitem__(self, arg): |
| 670 | arg = _type_check(arg, "Optional[t] requires a single type.") |
| 671 | return Union[arg, type(None)] |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 672 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 673 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 674 | Optional = _Optional(_root=True) |
| 675 | |
| 676 | |
| 677 | class _Tuple(_FinalTypingBase, _root=True): |
| 678 | """Tuple type; Tuple[X, Y] is the cross-product type of X and Y. |
| 679 | |
| 680 | Example: Tuple[T1, T2] is a tuple of two elements corresponding |
| 681 | to type variables T1 and T2. Tuple[int, float, str] is a tuple |
| 682 | of an int, a float and a string. |
| 683 | |
| 684 | To specify a variable-length tuple of homogeneous type, use Tuple[T, ...]. |
| 685 | """ |
| 686 | |
| 687 | __slots__ = ('__tuple_params__', '__tuple_use_ellipsis__') |
| 688 | |
| 689 | def __init__(self, parameters=None, |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 690 | use_ellipsis=False, _root=False): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 691 | self.__tuple_params__ = parameters |
| 692 | self.__tuple_use_ellipsis__ = use_ellipsis |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 693 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 694 | def _get_type_vars(self, tvars): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 695 | if self.__tuple_params__: |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 696 | _get_type_vars(self.__tuple_params__, tvars) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 697 | |
| 698 | def _eval_type(self, globalns, localns): |
| 699 | tp = self.__tuple_params__ |
| 700 | if tp is None: |
| 701 | return self |
| 702 | p = tuple(_eval_type(t, globalns, localns) for t in tp) |
| 703 | if p == self.__tuple_params__: |
| 704 | return self |
| 705 | else: |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 706 | return self.__class__(p, _root=True) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 707 | |
| 708 | def __repr__(self): |
| 709 | r = super().__repr__() |
| 710 | if self.__tuple_params__ is not None: |
| 711 | params = [_type_repr(p) for p in self.__tuple_params__] |
| 712 | if self.__tuple_use_ellipsis__: |
| 713 | params.append('...') |
Guido van Rossum | 91185fe | 2016-06-08 11:19:11 -0700 | [diff] [blame] | 714 | if not params: |
| 715 | params.append('()') |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 716 | r += '[%s]' % ( |
| 717 | ', '.join(params)) |
| 718 | return r |
| 719 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 720 | @_tp_cache |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 721 | def __getitem__(self, parameters): |
| 722 | if self.__tuple_params__ is not None: |
| 723 | raise TypeError("Cannot re-parameterize %r" % (self,)) |
| 724 | if not isinstance(parameters, tuple): |
| 725 | parameters = (parameters,) |
| 726 | if len(parameters) == 2 and parameters[1] == Ellipsis: |
| 727 | parameters = parameters[:1] |
| 728 | use_ellipsis = True |
| 729 | msg = "Tuple[t, ...]: t must be a type." |
| 730 | else: |
| 731 | use_ellipsis = False |
| 732 | msg = "Tuple[t0, t1, ...]: each t must be a type." |
| 733 | parameters = tuple(_type_check(p, msg) for p in parameters) |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 734 | return self.__class__(parameters, |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 735 | use_ellipsis=use_ellipsis, _root=True) |
| 736 | |
| 737 | def __eq__(self, other): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 738 | if not isinstance(other, _Tuple): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 739 | return NotImplemented |
Guido van Rossum | 5abcbb3 | 2016-04-18 07:37:41 -0700 | [diff] [blame] | 740 | return (self.__tuple_params__ == other.__tuple_params__ and |
| 741 | self.__tuple_use_ellipsis__ == other.__tuple_use_ellipsis__) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 742 | |
| 743 | def __hash__(self): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 744 | return hash((self.__tuple_params__, self.__tuple_use_ellipsis__)) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 745 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 746 | def __instancecheck__(self, obj): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 747 | if self.__tuple_params__ == None: |
| 748 | return isinstance(obj, tuple) |
| 749 | raise TypeError("Parameterized Tuple cannot be used " |
| 750 | "with isinstance().") |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 751 | |
| 752 | def __subclasscheck__(self, cls): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 753 | if self.__tuple_params__ == None: |
| 754 | return issubclass(cls, tuple) |
| 755 | raise TypeError("Parameterized Tuple cannot be used " |
| 756 | "with issubclass().") |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 757 | |
| 758 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 759 | Tuple = _Tuple(_root=True) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 760 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 761 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 762 | class _Callable(_FinalTypingBase, _root=True): |
| 763 | """Callable type; Callable[[int], str] is a function of (int) -> str. |
| 764 | |
| 765 | The subscription syntax must always be used with exactly two |
| 766 | values: the argument list and the return type. The argument list |
| 767 | must be a list of types; the return type must be a single type. |
| 768 | |
| 769 | There is no syntax to indicate optional or keyword arguments, |
| 770 | such function types are rarely used as callback types. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 771 | """ |
| 772 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 773 | __slots__ = ('__args__', '__result__') |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 774 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 775 | def __init__(self, args=None, result=None, _root=False): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 776 | if args is None and result is None: |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 777 | pass |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 778 | else: |
| 779 | if args is not Ellipsis: |
| 780 | if not isinstance(args, list): |
| 781 | raise TypeError("Callable[args, result]: " |
| 782 | "args must be a list." |
| 783 | " Got %.100r." % (args,)) |
| 784 | msg = "Callable[[arg, ...], result]: each arg must be a type." |
| 785 | args = tuple(_type_check(arg, msg) for arg in args) |
| 786 | msg = "Callable[args, result]: result must be a type." |
| 787 | result = _type_check(result, msg) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 788 | self.__args__ = args |
| 789 | self.__result__ = result |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 790 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 791 | def _get_type_vars(self, tvars): |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 792 | if self.__args__ and self.__args__ is not Ellipsis: |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 793 | _get_type_vars(self.__args__, tvars) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 794 | |
| 795 | def _eval_type(self, globalns, localns): |
| 796 | if self.__args__ is None and self.__result__ is None: |
| 797 | return self |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 798 | if self.__args__ is Ellipsis: |
| 799 | args = self.__args__ |
| 800 | else: |
| 801 | args = [_eval_type(t, globalns, localns) for t in self.__args__] |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 802 | result = _eval_type(self.__result__, globalns, localns) |
| 803 | if args == self.__args__ and result == self.__result__: |
| 804 | return self |
| 805 | else: |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 806 | return self.__class__(args, result, _root=True) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 807 | |
| 808 | def __repr__(self): |
| 809 | r = super().__repr__() |
| 810 | if self.__args__ is not None or self.__result__ is not None: |
| 811 | if self.__args__ is Ellipsis: |
| 812 | args_r = '...' |
| 813 | else: |
| 814 | args_r = '[%s]' % ', '.join(_type_repr(t) |
| 815 | for t in self.__args__) |
| 816 | r += '[%s, %s]' % (args_r, _type_repr(self.__result__)) |
| 817 | return r |
| 818 | |
| 819 | def __getitem__(self, parameters): |
| 820 | if self.__args__ is not None or self.__result__ is not None: |
| 821 | raise TypeError("This Callable type is already parameterized.") |
| 822 | if not isinstance(parameters, tuple) or len(parameters) != 2: |
| 823 | raise TypeError( |
| 824 | "Callable must be used as Callable[[arg, ...], result].") |
| 825 | args, result = parameters |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 826 | return self.__class__(args, result, _root=True) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 827 | |
| 828 | def __eq__(self, other): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 829 | if not isinstance(other, _Callable): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 830 | return NotImplemented |
| 831 | return (self.__args__ == other.__args__ and |
| 832 | self.__result__ == other.__result__) |
| 833 | |
| 834 | def __hash__(self): |
| 835 | return hash(self.__args__) ^ hash(self.__result__) |
| 836 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 837 | def __instancecheck__(self, obj): |
| 838 | # For unparametrized Callable we allow this, because |
| 839 | # typing.Callable should be equivalent to |
| 840 | # collections.abc.Callable. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 841 | if self.__args__ is None and self.__result__ is None: |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 842 | return isinstance(obj, collections_abc.Callable) |
| 843 | else: |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 844 | raise TypeError("Parameterized Callable cannot be used " |
| 845 | "with isinstance().") |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 846 | |
| 847 | def __subclasscheck__(self, cls): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 848 | if self.__args__ is None and self.__result__ is None: |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 849 | return issubclass(cls, collections_abc.Callable) |
| 850 | else: |
| 851 | raise TypeError("Parameterized Callable cannot be used " |
| 852 | "with issubclass().") |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 853 | |
| 854 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 855 | Callable = _Callable(_root=True) |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 856 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 857 | |
| 858 | def _gorg(a): |
| 859 | """Return the farthest origin of a generic class.""" |
| 860 | assert isinstance(a, GenericMeta) |
| 861 | while a.__origin__ is not None: |
| 862 | a = a.__origin__ |
| 863 | return a |
| 864 | |
| 865 | |
| 866 | def _geqv(a, b): |
| 867 | """Return whether two generic classes are equivalent. |
| 868 | |
| 869 | The intention is to consider generic class X and any of its |
| 870 | parameterized forms (X[T], X[int], etc.) as equivalent. |
| 871 | |
| 872 | However, X is not equivalent to a subclass of X. |
| 873 | |
| 874 | The relation is reflexive, symmetric and transitive. |
| 875 | """ |
| 876 | assert isinstance(a, GenericMeta) and isinstance(b, GenericMeta) |
| 877 | # Reduce each to its origin. |
| 878 | return _gorg(a) is _gorg(b) |
| 879 | |
| 880 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 881 | def _next_in_mro(cls): |
| 882 | """Helper for Generic.__new__. |
| 883 | |
| 884 | Returns the class after the last occurrence of Generic or |
| 885 | Generic[...] in cls.__mro__. |
| 886 | """ |
| 887 | next_in_mro = object |
| 888 | # Look for the last occurrence of Generic or Generic[...]. |
| 889 | for i, c in enumerate(cls.__mro__[:-1]): |
| 890 | if isinstance(c, GenericMeta) and _gorg(c) is Generic: |
| 891 | next_in_mro = cls.__mro__[i+1] |
| 892 | return next_in_mro |
| 893 | |
| 894 | |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 895 | def _valid_for_check(cls): |
| 896 | if cls is Generic: |
| 897 | raise TypeError("Class %r cannot be used with class " |
| 898 | "or instance checks" % cls) |
| 899 | if (cls.__origin__ is not None and |
| 900 | sys._getframe(3).f_globals['__name__'] not in ['abc', 'functools']): |
| 901 | raise TypeError("Parameterized generics cannot be used with class " |
| 902 | "or instance checks") |
| 903 | |
| 904 | |
| 905 | def _make_subclasshook(cls): |
| 906 | """Construct a __subclasshook__ callable that incorporates |
| 907 | the associated __extra__ class in subclass checks performed |
| 908 | against cls. |
| 909 | """ |
| 910 | if isinstance(cls.__extra__, abc.ABCMeta): |
| 911 | # The logic mirrors that of ABCMeta.__subclasscheck__. |
| 912 | # Registered classes need not be checked here because |
| 913 | # cls and its extra share the same _abc_registry. |
| 914 | def __extrahook__(subclass): |
| 915 | _valid_for_check(cls) |
| 916 | res = cls.__extra__.__subclasshook__(subclass) |
| 917 | if res is not NotImplemented: |
| 918 | return res |
| 919 | if cls.__extra__ in subclass.__mro__: |
| 920 | return True |
| 921 | for scls in cls.__extra__.__subclasses__(): |
| 922 | if isinstance(scls, GenericMeta): |
| 923 | continue |
| 924 | if issubclass(subclass, scls): |
| 925 | return True |
| 926 | return NotImplemented |
| 927 | else: |
| 928 | # For non-ABC extras we'll just call issubclass(). |
| 929 | def __extrahook__(subclass): |
| 930 | _valid_for_check(cls) |
| 931 | if cls.__extra__ and issubclass(subclass, cls.__extra__): |
| 932 | return True |
| 933 | return NotImplemented |
| 934 | return __extrahook__ |
| 935 | |
| 936 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 937 | class GenericMeta(TypingMeta, abc.ABCMeta): |
| 938 | """Metaclass for generic types.""" |
| 939 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 940 | def __new__(cls, name, bases, namespace, |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 941 | tvars=None, args=None, origin=None, extra=None): |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 942 | if extra is not None and type(extra) is abc.ABCMeta and extra not in bases: |
| 943 | bases = (extra,) + bases |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 944 | self = super().__new__(cls, name, bases, namespace, _root=True) |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 945 | |
| 946 | if tvars is not None: |
| 947 | # Called from __getitem__() below. |
| 948 | assert origin is not None |
| 949 | assert all(isinstance(t, TypeVar) for t in tvars), tvars |
| 950 | else: |
| 951 | # Called from class statement. |
| 952 | assert tvars is None, tvars |
| 953 | assert args is None, args |
| 954 | assert origin is None, origin |
| 955 | |
| 956 | # Get the full set of tvars from the bases. |
| 957 | tvars = _type_vars(bases) |
| 958 | # Look for Generic[T1, ..., Tn]. |
| 959 | # If found, tvars must be a subset of it. |
| 960 | # If not found, tvars is it. |
| 961 | # Also check for and reject plain Generic, |
| 962 | # and reject multiple Generic[...]. |
| 963 | gvars = None |
| 964 | for base in bases: |
| 965 | if base is Generic: |
| 966 | raise TypeError("Cannot inherit from plain Generic") |
| 967 | if (isinstance(base, GenericMeta) and |
| 968 | base.__origin__ is Generic): |
| 969 | if gvars is not None: |
| 970 | raise TypeError( |
| 971 | "Cannot inherit from Generic[...] multiple types.") |
| 972 | gvars = base.__parameters__ |
| 973 | if gvars is None: |
| 974 | gvars = tvars |
| 975 | else: |
| 976 | tvarset = set(tvars) |
| 977 | gvarset = set(gvars) |
| 978 | if not tvarset <= gvarset: |
| 979 | raise TypeError( |
| 980 | "Some type variables (%s) " |
| 981 | "are not listed in Generic[%s]" % |
| 982 | (", ".join(str(t) for t in tvars if t not in gvarset), |
| 983 | ", ".join(str(g) for g in gvars))) |
| 984 | tvars = gvars |
| 985 | |
| 986 | self.__parameters__ = tvars |
| 987 | self.__args__ = args |
| 988 | self.__origin__ = origin |
Guido van Rossum | 1cea70f | 2016-05-18 08:35:00 -0700 | [diff] [blame] | 989 | self.__extra__ = extra |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 990 | # Speed hack (https://github.com/python/typing/issues/196). |
| 991 | self.__next_in_mro__ = _next_in_mro(self) |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 992 | |
| 993 | # This allows unparameterized generic collections to be used |
| 994 | # with issubclass() and isinstance() in the same way as their |
| 995 | # collections.abc counterparts (e.g., isinstance([], Iterable)). |
Guido van Rossum | e259267 | 2016-10-08 20:27:22 -0700 | [diff] [blame] | 996 | if ('__subclasshook__' not in namespace and extra # allow overriding |
| 997 | or hasattr(self.__subclasshook__, '__name__') and |
| 998 | self.__subclasshook__.__name__ == '__extrahook__'): |
| 999 | self.__subclasshook__ = _make_subclasshook(self) |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 1000 | if isinstance(extra, abc.ABCMeta): |
| 1001 | self._abc_registry = extra._abc_registry |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1002 | return self |
| 1003 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1004 | def _get_type_vars(self, tvars): |
| 1005 | if self.__origin__ and self.__parameters__: |
| 1006 | _get_type_vars(self.__parameters__, tvars) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1007 | |
| 1008 | def __repr__(self): |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1009 | if self.__origin__ is not None: |
| 1010 | r = repr(self.__origin__) |
| 1011 | else: |
| 1012 | r = super().__repr__() |
| 1013 | if self.__args__: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1014 | r += '[%s]' % ( |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1015 | ', '.join(_type_repr(p) for p in self.__args__)) |
| 1016 | if self.__parameters__: |
| 1017 | r += '<%s>' % ( |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1018 | ', '.join(_type_repr(p) for p in self.__parameters__)) |
| 1019 | return r |
| 1020 | |
| 1021 | def __eq__(self, other): |
| 1022 | if not isinstance(other, GenericMeta): |
| 1023 | return NotImplemented |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1024 | if self.__origin__ is not None: |
| 1025 | return (self.__origin__ is other.__origin__ and |
| 1026 | self.__args__ == other.__args__ and |
| 1027 | self.__parameters__ == other.__parameters__) |
| 1028 | else: |
| 1029 | return self is other |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1030 | |
| 1031 | def __hash__(self): |
| 1032 | return hash((self.__name__, self.__parameters__)) |
| 1033 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1034 | @_tp_cache |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1035 | def __getitem__(self, params): |
| 1036 | if not isinstance(params, tuple): |
| 1037 | params = (params,) |
| 1038 | if not params: |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1039 | raise TypeError( |
| 1040 | "Parameter list to %s[...] cannot be empty" % _qualname(self)) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1041 | msg = "Parameters to generic types must be types." |
| 1042 | params = tuple(_type_check(p, msg) for p in params) |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1043 | if self is Generic: |
| 1044 | # Generic can only be subscripted with unique type variables. |
| 1045 | if not all(isinstance(p, TypeVar) for p in params): |
| 1046 | raise TypeError( |
| 1047 | "Parameters to Generic[...] must all be type variables") |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1048 | if len(set(params)) != len(params): |
Guido van Rossum | 1b66910 | 2015-09-04 12:15:54 -0700 | [diff] [blame] | 1049 | raise TypeError( |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1050 | "Parameters to Generic[...] must all be unique") |
| 1051 | tvars = params |
| 1052 | args = None |
| 1053 | elif self is _Protocol: |
| 1054 | # _Protocol is internal, don't check anything. |
| 1055 | tvars = params |
| 1056 | args = None |
| 1057 | elif self.__origin__ in (Generic, _Protocol): |
| 1058 | # Can't subscript Generic[...] or _Protocol[...]. |
| 1059 | raise TypeError("Cannot subscript already-subscripted %s" % |
| 1060 | repr(self)) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1061 | else: |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1062 | # Subscripting a regular Generic subclass. |
| 1063 | if not self.__parameters__: |
| 1064 | raise TypeError("%s is not a generic class" % repr(self)) |
| 1065 | alen = len(params) |
| 1066 | elen = len(self.__parameters__) |
| 1067 | if alen != elen: |
| 1068 | raise TypeError( |
| 1069 | "Too %s parameters for %s; actual %s, expected %s" % |
| 1070 | ("many" if alen > elen else "few", repr(self), alen, elen)) |
| 1071 | tvars = _type_vars(params) |
| 1072 | args = params |
| 1073 | return self.__class__(self.__name__, |
| 1074 | (self,) + self.__bases__, |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1075 | dict(self.__dict__), |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1076 | tvars=tvars, |
| 1077 | args=args, |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1078 | origin=self, |
| 1079 | extra=self.__extra__) |
| 1080 | |
Guido van Rossum | 1b66910 | 2015-09-04 12:15:54 -0700 | [diff] [blame] | 1081 | def __instancecheck__(self, instance): |
| 1082 | # Since we extend ABC.__subclasscheck__ and |
| 1083 | # ABC.__instancecheck__ inlines the cache checking done by the |
| 1084 | # latter, we must extend __instancecheck__ too. For simplicity |
| 1085 | # we just skip the cache check -- instance checks for generic |
| 1086 | # classes are supposed to be rare anyways. |
Guido van Rossum | b47c9d2 | 2016-10-03 08:40:50 -0700 | [diff] [blame] | 1087 | return issubclass(instance.__class__, self) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1088 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1089 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1090 | # Prevent checks for Generic to crash when defining Generic. |
| 1091 | Generic = None |
| 1092 | |
| 1093 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1094 | class Generic(metaclass=GenericMeta): |
| 1095 | """Abstract base class for generic types. |
| 1096 | |
| 1097 | A generic type is typically declared by inheriting from an |
| 1098 | instantiation of this class with one or more type variables. |
| 1099 | For example, a generic mapping type might be defined as:: |
| 1100 | |
| 1101 | class Mapping(Generic[KT, VT]): |
| 1102 | def __getitem__(self, key: KT) -> VT: |
| 1103 | ... |
| 1104 | # Etc. |
| 1105 | |
| 1106 | This class can then be used as follows:: |
| 1107 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1108 | 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] | 1109 | try: |
| 1110 | return mapping[key] |
| 1111 | except KeyError: |
| 1112 | return default |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1113 | """ |
| 1114 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1115 | __slots__ = () |
| 1116 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1117 | def __new__(cls, *args, **kwds): |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1118 | if cls.__origin__ is None: |
| 1119 | return cls.__next_in_mro__.__new__(cls) |
| 1120 | else: |
| 1121 | origin = _gorg(cls) |
| 1122 | obj = cls.__next_in_mro__.__new__(origin) |
| 1123 | obj.__init__(*args, **kwds) |
| 1124 | return obj |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1125 | |
| 1126 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1127 | class _ClassVar(_FinalTypingBase, _root=True): |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1128 | """Special type construct to mark class variables. |
| 1129 | |
| 1130 | An annotation wrapped in ClassVar indicates that a given |
| 1131 | attribute is intended to be used as a class variable and |
| 1132 | should not be set on instances of that class. Usage:: |
| 1133 | |
| 1134 | class Starship: |
| 1135 | stats: ClassVar[Dict[str, int]] = {} # class variable |
| 1136 | damage: int = 10 # instance variable |
| 1137 | |
| 1138 | ClassVar accepts only types and cannot be further subscribed. |
| 1139 | |
| 1140 | Note that ClassVar is not a class itself, and should not |
| 1141 | be used with isinstance() or issubclass(). |
| 1142 | """ |
| 1143 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1144 | __slots__ = ('__type__',) |
| 1145 | |
| 1146 | def __init__(self, tp=None, **kwds): |
| 1147 | self.__type__ = tp |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1148 | |
| 1149 | def __getitem__(self, item): |
| 1150 | cls = type(self) |
| 1151 | if self.__type__ is None: |
| 1152 | return cls(_type_check(item, |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1153 | '{} accepts only single type.'.format(cls.__name__[1:])), |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1154 | _root=True) |
| 1155 | raise TypeError('{} cannot be further subscripted' |
| 1156 | .format(cls.__name__[1:])) |
| 1157 | |
| 1158 | def _eval_type(self, globalns, localns): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1159 | new_tp = _eval_type(self.__type__, globalns, localns) |
| 1160 | if new_tp == self.__type__: |
| 1161 | return self |
| 1162 | return type(self)(new_tp, _root=True) |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1163 | |
| 1164 | def _get_type_vars(self, tvars): |
| 1165 | if self.__type__: |
| 1166 | _get_type_vars(self.__type__, tvars) |
| 1167 | |
| 1168 | def __repr__(self): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1169 | r = super().__repr__() |
| 1170 | if self.__type__ is not None: |
| 1171 | r += '[{}]'.format(_type_repr(self.__type__)) |
| 1172 | return r |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1173 | |
| 1174 | def __hash__(self): |
| 1175 | return hash((type(self).__name__, self.__type__)) |
| 1176 | |
| 1177 | def __eq__(self, other): |
| 1178 | if not isinstance(other, _ClassVar): |
| 1179 | return NotImplemented |
| 1180 | if self.__type__ is not None: |
| 1181 | return self.__type__ == other.__type__ |
| 1182 | return self is other |
| 1183 | |
| 1184 | ClassVar = _ClassVar(_root=True) |
| 1185 | |
| 1186 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1187 | def cast(typ, val): |
| 1188 | """Cast a value to a type. |
| 1189 | |
| 1190 | This returns the value unchanged. To the type checker this |
| 1191 | signals that the return value has the designated type, but at |
| 1192 | runtime we intentionally don't check anything (we want this |
| 1193 | to be as fast as possible). |
| 1194 | """ |
| 1195 | return val |
| 1196 | |
| 1197 | |
| 1198 | def _get_defaults(func): |
| 1199 | """Internal helper to extract the default arguments, by name.""" |
| 1200 | code = func.__code__ |
| 1201 | pos_count = code.co_argcount |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1202 | arg_names = code.co_varnames |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1203 | arg_names = arg_names[:pos_count] |
| 1204 | defaults = func.__defaults__ or () |
| 1205 | kwdefaults = func.__kwdefaults__ |
| 1206 | res = dict(kwdefaults) if kwdefaults else {} |
| 1207 | pos_offset = pos_count - len(defaults) |
| 1208 | for name, value in zip(arg_names[pos_offset:], defaults): |
| 1209 | assert name not in res |
| 1210 | res[name] = value |
| 1211 | return res |
| 1212 | |
| 1213 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1214 | if sys.version_info[:2] >= (3, 3): |
| 1215 | def get_type_hints(obj, globalns=None, localns=None): |
| 1216 | """Return type hints for an object. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1217 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1218 | This is often the same as obj.__annotations__, but it handles |
| 1219 | forward references encoded as string literals, and if necessary |
| 1220 | 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] | 1221 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1222 | The argument may be a module, class, method, or function. The annotations |
| 1223 | are returned as a dictionary, or in the case of a class, a ChainMap of |
| 1224 | dictionaries. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1225 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1226 | TypeError is raised if the argument is not of a type that can contain |
| 1227 | annotations, and an empty dictionary is returned if no annotations are |
| 1228 | present. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1229 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1230 | BEWARE -- the behavior of globalns and localns is counterintuitive |
| 1231 | (unless you are familiar with how eval() and exec() work). The |
| 1232 | search order is locals first, then globals. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1233 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1234 | - If no dict arguments are passed, an attempt is made to use the |
| 1235 | globals from obj, and these are also used as the locals. If the |
| 1236 | object does not appear to have globals, an exception is raised. |
| 1237 | |
| 1238 | - If one dict argument is passed, it is used for both globals and |
| 1239 | locals. |
| 1240 | |
| 1241 | - If two dict arguments are passed, they specify globals and |
| 1242 | locals, respectively. |
| 1243 | """ |
| 1244 | |
| 1245 | if getattr(obj, '__no_type_check__', None): |
| 1246 | return {} |
| 1247 | if globalns is None: |
| 1248 | globalns = getattr(obj, '__globals__', {}) |
| 1249 | if localns is None: |
| 1250 | localns = globalns |
| 1251 | elif localns is None: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1252 | localns = globalns |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1253 | |
| 1254 | if (isinstance(obj, types.FunctionType) or |
| 1255 | isinstance(obj, types.BuiltinFunctionType) or |
| 1256 | isinstance(obj, types.MethodType)): |
| 1257 | defaults = _get_defaults(obj) |
| 1258 | hints = obj.__annotations__ |
| 1259 | for name, value in hints.items(): |
| 1260 | if value is None: |
| 1261 | value = type(None) |
| 1262 | if isinstance(value, str): |
| 1263 | value = _ForwardRef(value) |
| 1264 | value = _eval_type(value, globalns, localns) |
| 1265 | if name in defaults and defaults[name] is None: |
| 1266 | value = Optional[value] |
| 1267 | hints[name] = value |
| 1268 | return hints |
| 1269 | |
| 1270 | if isinstance(obj, types.ModuleType): |
| 1271 | try: |
| 1272 | hints = obj.__annotations__ |
| 1273 | except AttributeError: |
| 1274 | return {} |
| 1275 | # we keep only those annotations that can be accessed on module |
| 1276 | members = obj.__dict__ |
| 1277 | hints = {name: value for name, value in hints.items() |
| 1278 | if name in members} |
| 1279 | for name, value in hints.items(): |
| 1280 | if value is None: |
| 1281 | value = type(None) |
| 1282 | if isinstance(value, str): |
| 1283 | value = _ForwardRef(value) |
| 1284 | value = _eval_type(value, globalns, localns) |
| 1285 | hints[name] = value |
| 1286 | return hints |
| 1287 | |
| 1288 | if isinstance(object, type): |
| 1289 | cmap = None |
| 1290 | for base in reversed(obj.__mro__): |
| 1291 | new_map = collections.ChainMap if cmap is None else cmap.new_child |
| 1292 | try: |
| 1293 | hints = base.__dict__['__annotations__'] |
| 1294 | except KeyError: |
| 1295 | cmap = new_map() |
| 1296 | else: |
| 1297 | for name, value in hints.items(): |
| 1298 | if value is None: |
| 1299 | value = type(None) |
| 1300 | if isinstance(value, str): |
| 1301 | value = _ForwardRef(value) |
| 1302 | value = _eval_type(value, globalns, localns) |
| 1303 | hints[name] = value |
| 1304 | cmap = new_map(hints) |
| 1305 | return cmap |
| 1306 | |
| 1307 | raise TypeError('{!r} is not a module, class, method, ' |
| 1308 | 'or function.'.format(obj)) |
| 1309 | |
| 1310 | else: |
| 1311 | def get_type_hints(obj, globalns=None, localns=None): |
| 1312 | """Return type hints for a function or method object. |
| 1313 | |
| 1314 | This is often the same as obj.__annotations__, but it handles |
| 1315 | forward references encoded as string literals, and if necessary |
| 1316 | adds Optional[t] if a default value equal to None is set. |
| 1317 | |
| 1318 | BEWARE -- the behavior of globalns and localns is counterintuitive |
| 1319 | (unless you are familiar with how eval() and exec() work). The |
| 1320 | search order is locals first, then globals. |
| 1321 | |
| 1322 | - If no dict arguments are passed, an attempt is made to use the |
| 1323 | globals from obj, and these are also used as the locals. If the |
| 1324 | object does not appear to have globals, an exception is raised. |
| 1325 | |
| 1326 | - If one dict argument is passed, it is used for both globals and |
| 1327 | locals. |
| 1328 | |
| 1329 | - If two dict arguments are passed, they specify globals and |
| 1330 | locals, respectively. |
| 1331 | """ |
| 1332 | if getattr(obj, '__no_type_check__', None): |
| 1333 | return {} |
| 1334 | if globalns is None: |
| 1335 | globalns = getattr(obj, '__globals__', {}) |
| 1336 | if localns is None: |
| 1337 | localns = globalns |
| 1338 | elif localns is None: |
| 1339 | localns = globalns |
| 1340 | defaults = _get_defaults(obj) |
| 1341 | hints = dict(obj.__annotations__) |
| 1342 | for name, value in hints.items(): |
| 1343 | if isinstance(value, str): |
| 1344 | value = _ForwardRef(value) |
| 1345 | value = _eval_type(value, globalns, localns) |
| 1346 | if name in defaults and defaults[name] is None: |
| 1347 | value = Optional[value] |
| 1348 | hints[name] = value |
| 1349 | return hints |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1350 | |
| 1351 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1352 | def no_type_check(arg): |
| 1353 | """Decorator to indicate that annotations are not type hints. |
| 1354 | |
| 1355 | 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] | 1356 | applies recursively to all methods and classes defined in that class |
| 1357 | (but not to methods defined in its superclasses or subclasses). |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1358 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1359 | This mutates the function(s) or class(es) in place. |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1360 | """ |
| 1361 | if isinstance(arg, type): |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1362 | arg_attrs = arg.__dict__.copy() |
| 1363 | for attr, val in arg.__dict__.items(): |
| 1364 | if val in arg.__bases__: |
| 1365 | arg_attrs.pop(attr) |
| 1366 | for obj in arg_attrs.values(): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1367 | if isinstance(obj, types.FunctionType): |
| 1368 | obj.__no_type_check__ = True |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1369 | if isinstance(obj, type): |
| 1370 | no_type_check(obj) |
| 1371 | try: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1372 | arg.__no_type_check__ = True |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1373 | except TypeError: # built-in classes |
| 1374 | pass |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1375 | return arg |
| 1376 | |
| 1377 | |
| 1378 | def no_type_check_decorator(decorator): |
| 1379 | """Decorator to give another decorator the @no_type_check effect. |
| 1380 | |
| 1381 | This wraps the decorator with something that wraps the decorated |
| 1382 | function in @no_type_check. |
| 1383 | """ |
| 1384 | |
| 1385 | @functools.wraps(decorator) |
| 1386 | def wrapped_decorator(*args, **kwds): |
| 1387 | func = decorator(*args, **kwds) |
| 1388 | func = no_type_check(func) |
| 1389 | return func |
| 1390 | |
| 1391 | return wrapped_decorator |
| 1392 | |
| 1393 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1394 | def _overload_dummy(*args, **kwds): |
| 1395 | """Helper for @overload to raise when called.""" |
| 1396 | raise NotImplementedError( |
| 1397 | "You should not call an overloaded function. " |
| 1398 | "A series of @overload-decorated functions " |
| 1399 | "outside a stub module should always be followed " |
| 1400 | "by an implementation that is not @overload-ed.") |
| 1401 | |
| 1402 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1403 | def overload(func): |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1404 | """Decorator for overloaded functions/methods. |
| 1405 | |
| 1406 | In a stub file, place two or more stub definitions for the same |
| 1407 | function in a row, each decorated with @overload. For example: |
| 1408 | |
| 1409 | @overload |
| 1410 | def utf8(value: None) -> None: ... |
| 1411 | @overload |
| 1412 | def utf8(value: bytes) -> bytes: ... |
| 1413 | @overload |
| 1414 | def utf8(value: str) -> bytes: ... |
| 1415 | |
| 1416 | In a non-stub file (i.e. a regular .py file), do the same but |
| 1417 | follow it with an implementation. The implementation should *not* |
| 1418 | be decorated with @overload. For example: |
| 1419 | |
| 1420 | @overload |
| 1421 | def utf8(value: None) -> None: ... |
| 1422 | @overload |
| 1423 | def utf8(value: bytes) -> bytes: ... |
| 1424 | @overload |
| 1425 | def utf8(value: str) -> bytes: ... |
| 1426 | def utf8(value): |
| 1427 | # implementation goes here |
| 1428 | """ |
| 1429 | return _overload_dummy |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1430 | |
| 1431 | |
| 1432 | class _ProtocolMeta(GenericMeta): |
| 1433 | """Internal metaclass for _Protocol. |
| 1434 | |
| 1435 | This exists so _Protocol classes can be generic without deriving |
| 1436 | from Generic. |
| 1437 | """ |
| 1438 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1439 | def __instancecheck__(self, obj): |
| 1440 | raise TypeError("Protocols cannot be used with isinstance().") |
| 1441 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1442 | def __subclasscheck__(self, cls): |
| 1443 | if not self._is_protocol: |
| 1444 | # No structural checks since this isn't a protocol. |
| 1445 | return NotImplemented |
| 1446 | |
| 1447 | if self is _Protocol: |
| 1448 | # Every class is a subclass of the empty protocol. |
| 1449 | return True |
| 1450 | |
| 1451 | # Find all attributes defined in the protocol. |
| 1452 | attrs = self._get_protocol_attrs() |
| 1453 | |
| 1454 | for attr in attrs: |
| 1455 | if not any(attr in d.__dict__ for d in cls.__mro__): |
| 1456 | return False |
| 1457 | return True |
| 1458 | |
| 1459 | def _get_protocol_attrs(self): |
| 1460 | # Get all Protocol base classes. |
| 1461 | protocol_bases = [] |
| 1462 | for c in self.__mro__: |
| 1463 | if getattr(c, '_is_protocol', False) and c.__name__ != '_Protocol': |
| 1464 | protocol_bases.append(c) |
| 1465 | |
| 1466 | # Get attributes included in protocol. |
| 1467 | attrs = set() |
| 1468 | for base in protocol_bases: |
| 1469 | for attr in base.__dict__.keys(): |
| 1470 | # Include attributes not defined in any non-protocol bases. |
| 1471 | for c in self.__mro__: |
| 1472 | if (c is not base and attr in c.__dict__ and |
| 1473 | not getattr(c, '_is_protocol', False)): |
| 1474 | break |
| 1475 | else: |
| 1476 | if (not attr.startswith('_abc_') and |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1477 | attr != '__abstractmethods__' and |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1478 | attr != '__annotations__' and |
| 1479 | attr != '__weakref__' and |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1480 | attr != '_is_protocol' and |
| 1481 | attr != '__dict__' and |
| 1482 | attr != '__args__' and |
| 1483 | attr != '__slots__' and |
| 1484 | attr != '_get_protocol_attrs' and |
| 1485 | attr != '__next_in_mro__' and |
| 1486 | attr != '__parameters__' and |
| 1487 | attr != '__origin__' and |
Guido van Rossum | 1cea70f | 2016-05-18 08:35:00 -0700 | [diff] [blame] | 1488 | attr != '__extra__' and |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1489 | attr != '__module__'): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1490 | attrs.add(attr) |
| 1491 | |
| 1492 | return attrs |
| 1493 | |
| 1494 | |
| 1495 | class _Protocol(metaclass=_ProtocolMeta): |
| 1496 | """Internal base class for protocol classes. |
| 1497 | |
| 1498 | This implements a simple-minded structural isinstance check |
| 1499 | (similar but more general than the one-offs in collections.abc |
| 1500 | such as Hashable). |
| 1501 | """ |
| 1502 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1503 | __slots__ = () |
| 1504 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1505 | _is_protocol = True |
| 1506 | |
| 1507 | |
| 1508 | # Various ABCs mimicking those in collections.abc. |
| 1509 | # A few are simply re-exported for completeness. |
| 1510 | |
| 1511 | Hashable = collections_abc.Hashable # Not generic. |
| 1512 | |
| 1513 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1514 | if hasattr(collections_abc, 'Awaitable'): |
| 1515 | class Awaitable(Generic[T_co], extra=collections_abc.Awaitable): |
| 1516 | __slots__ = () |
| 1517 | else: |
| 1518 | Awaitable = None |
Guido van Rossum | f17c200 | 2015-12-03 17:31:24 -0800 | [diff] [blame] | 1519 | |
| 1520 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1521 | if hasattr(collections_abc, 'AsyncIterable'): |
Guido van Rossum | f17c200 | 2015-12-03 17:31:24 -0800 | [diff] [blame] | 1522 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1523 | class AsyncIterable(Generic[T_co], extra=collections_abc.AsyncIterable): |
| 1524 | __slots__ = () |
Guido van Rossum | f17c200 | 2015-12-03 17:31:24 -0800 | [diff] [blame] | 1525 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1526 | class AsyncIterator(AsyncIterable[T_co], |
| 1527 | extra=collections_abc.AsyncIterator): |
| 1528 | __slots__ = () |
| 1529 | |
| 1530 | else: |
| 1531 | AsyncIterable = None |
| 1532 | AsyncIterator = None |
Guido van Rossum | f17c200 | 2015-12-03 17:31:24 -0800 | [diff] [blame] | 1533 | |
| 1534 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1535 | class Iterable(Generic[T_co], extra=collections_abc.Iterable): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1536 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1537 | |
| 1538 | |
| 1539 | class Iterator(Iterable[T_co], extra=collections_abc.Iterator): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1540 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1541 | |
| 1542 | |
| 1543 | class SupportsInt(_Protocol): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1544 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1545 | |
| 1546 | @abstractmethod |
| 1547 | def __int__(self) -> int: |
| 1548 | pass |
| 1549 | |
| 1550 | |
| 1551 | class SupportsFloat(_Protocol): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1552 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1553 | |
| 1554 | @abstractmethod |
| 1555 | def __float__(self) -> float: |
| 1556 | pass |
| 1557 | |
| 1558 | |
| 1559 | class SupportsComplex(_Protocol): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1560 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1561 | |
| 1562 | @abstractmethod |
| 1563 | def __complex__(self) -> complex: |
| 1564 | pass |
| 1565 | |
| 1566 | |
| 1567 | class SupportsBytes(_Protocol): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1568 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1569 | |
| 1570 | @abstractmethod |
| 1571 | def __bytes__(self) -> bytes: |
| 1572 | pass |
| 1573 | |
| 1574 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1575 | class SupportsAbs(_Protocol[T_co]): |
| 1576 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1577 | |
| 1578 | @abstractmethod |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1579 | def __abs__(self) -> T_co: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1580 | pass |
| 1581 | |
| 1582 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1583 | class SupportsRound(_Protocol[T_co]): |
| 1584 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1585 | |
| 1586 | @abstractmethod |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1587 | def __round__(self, ndigits: int = 0) -> T_co: |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1588 | pass |
| 1589 | |
| 1590 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1591 | if hasattr(collections_abc, 'Reversible'): |
| 1592 | class Reversible(Iterable[T_co], extra=collections_abc.Reversible): |
| 1593 | __slots__ = () |
| 1594 | else: |
| 1595 | class Reversible(_Protocol[T_co]): |
| 1596 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1597 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1598 | @abstractmethod |
| 1599 | def __reversed__(self) -> 'Iterator[T_co]': |
| 1600 | pass |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1601 | |
| 1602 | |
| 1603 | Sized = collections_abc.Sized # Not generic. |
| 1604 | |
| 1605 | |
| 1606 | class Container(Generic[T_co], extra=collections_abc.Container): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1607 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1608 | |
| 1609 | |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1610 | if hasattr(collections_abc, 'Collection'): |
| 1611 | class Collection(Sized, Iterable[T_co], Container[T_co], |
| 1612 | extra=collections_abc.Collection): |
| 1613 | __slots__ = () |
| 1614 | |
| 1615 | __all__.append('Collection') |
| 1616 | |
| 1617 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1618 | # Callable was defined earlier. |
| 1619 | |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1620 | if hasattr(collections_abc, 'Collection'): |
| 1621 | class AbstractSet(Collection[T_co], |
| 1622 | extra=collections_abc.Set): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1623 | __slots__ = () |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1624 | else: |
| 1625 | class AbstractSet(Sized, Iterable[T_co], Container[T_co], |
| 1626 | extra=collections_abc.Set): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1627 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1628 | |
| 1629 | |
| 1630 | class MutableSet(AbstractSet[T], extra=collections_abc.MutableSet): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1631 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1632 | |
| 1633 | |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1634 | # NOTE: It is only covariant in the value type. |
| 1635 | if hasattr(collections_abc, 'Collection'): |
| 1636 | class Mapping(Collection[KT], Generic[KT, VT_co], |
| 1637 | extra=collections_abc.Mapping): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1638 | __slots__ = () |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1639 | else: |
| 1640 | class Mapping(Sized, Iterable[KT], Container[KT], Generic[KT, VT_co], |
| 1641 | extra=collections_abc.Mapping): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1642 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1643 | |
| 1644 | |
| 1645 | class MutableMapping(Mapping[KT, VT], extra=collections_abc.MutableMapping): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1646 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1647 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1648 | if hasattr(collections_abc, 'Reversible'): |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1649 | if hasattr(collections_abc, 'Collection'): |
| 1650 | class Sequence(Reversible[T_co], Collection[T_co], |
| 1651 | extra=collections_abc.Sequence): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1652 | __slots__ = () |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1653 | else: |
| 1654 | class Sequence(Sized, Reversible[T_co], Container[T_co], |
| 1655 | extra=collections_abc.Sequence): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1656 | __slots__ = () |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1657 | else: |
| 1658 | class Sequence(Sized, Iterable[T_co], Container[T_co], |
| 1659 | extra=collections_abc.Sequence): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1660 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1661 | |
| 1662 | |
| 1663 | class MutableSequence(Sequence[T], extra=collections_abc.MutableSequence): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1664 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1665 | |
| 1666 | |
| 1667 | class ByteString(Sequence[int], extra=collections_abc.ByteString): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1668 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1669 | |
| 1670 | |
Guido van Rossum | 1cea70f | 2016-05-18 08:35:00 -0700 | [diff] [blame] | 1671 | class List(list, MutableSequence[T], extra=list): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1672 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1673 | __slots__ = () |
| 1674 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1675 | def __new__(cls, *args, **kwds): |
| 1676 | if _geqv(cls, List): |
| 1677 | raise TypeError("Type List cannot be instantiated; " |
| 1678 | "use list() instead") |
| 1679 | return list.__new__(cls, *args, **kwds) |
| 1680 | |
| 1681 | |
Guido van Rossum | 1cea70f | 2016-05-18 08:35:00 -0700 | [diff] [blame] | 1682 | class Set(set, MutableSet[T], extra=set): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1683 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1684 | __slots__ = () |
| 1685 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1686 | def __new__(cls, *args, **kwds): |
| 1687 | if _geqv(cls, Set): |
| 1688 | raise TypeError("Type Set cannot be instantiated; " |
| 1689 | "use set() instead") |
| 1690 | return set.__new__(cls, *args, **kwds) |
| 1691 | |
| 1692 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1693 | class FrozenSet(frozenset, AbstractSet[T_co], extra=frozenset): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1694 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1695 | |
| 1696 | def __new__(cls, *args, **kwds): |
| 1697 | if _geqv(cls, FrozenSet): |
| 1698 | raise TypeError("Type FrozenSet cannot be instantiated; " |
| 1699 | "use frozenset() instead") |
| 1700 | return frozenset.__new__(cls, *args, **kwds) |
| 1701 | |
| 1702 | |
| 1703 | class MappingView(Sized, Iterable[T_co], extra=collections_abc.MappingView): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1704 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1705 | |
| 1706 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1707 | class KeysView(MappingView[KT], AbstractSet[KT], |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1708 | extra=collections_abc.KeysView): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1709 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1710 | |
| 1711 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1712 | class ItemsView(MappingView[Tuple[KT, VT_co]], |
Guido van Rossum | 0e0563c | 2016-04-05 14:54:25 -0700 | [diff] [blame] | 1713 | AbstractSet[Tuple[KT, VT_co]], |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1714 | Generic[KT, VT_co], |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1715 | extra=collections_abc.ItemsView): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1716 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1717 | |
| 1718 | |
| 1719 | class ValuesView(MappingView[VT_co], extra=collections_abc.ValuesView): |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1720 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1721 | |
| 1722 | |
Brett Cannon | f3ad042 | 2016-04-15 10:51:30 -0700 | [diff] [blame] | 1723 | if hasattr(contextlib, 'AbstractContextManager'): |
| 1724 | class ContextManager(Generic[T_co], extra=contextlib.AbstractContextManager): |
| 1725 | __slots__ = () |
| 1726 | __all__.append('ContextManager') |
| 1727 | |
| 1728 | |
Guido van Rossum | 1cea70f | 2016-05-18 08:35:00 -0700 | [diff] [blame] | 1729 | class Dict(dict, MutableMapping[KT, VT], extra=dict): |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1730 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1731 | __slots__ = () |
| 1732 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1733 | def __new__(cls, *args, **kwds): |
| 1734 | if _geqv(cls, Dict): |
| 1735 | raise TypeError("Type Dict cannot be instantiated; " |
| 1736 | "use dict() instead") |
| 1737 | return dict.__new__(cls, *args, **kwds) |
| 1738 | |
Guido van Rossum | 1cea70f | 2016-05-18 08:35:00 -0700 | [diff] [blame] | 1739 | class DefaultDict(collections.defaultdict, MutableMapping[KT, VT], |
| 1740 | extra=collections.defaultdict): |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1741 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1742 | __slots__ = () |
| 1743 | |
Guido van Rossum | bd5b9a0 | 2016-04-05 08:28:52 -0700 | [diff] [blame] | 1744 | def __new__(cls, *args, **kwds): |
| 1745 | if _geqv(cls, DefaultDict): |
| 1746 | raise TypeError("Type DefaultDict cannot be instantiated; " |
| 1747 | "use collections.defaultdict() instead") |
| 1748 | return collections.defaultdict.__new__(cls, *args, **kwds) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1749 | |
| 1750 | # Determine what base class to use for Generator. |
| 1751 | if hasattr(collections_abc, 'Generator'): |
| 1752 | # Sufficiently recent versions of 3.5 have a Generator ABC. |
| 1753 | _G_base = collections_abc.Generator |
| 1754 | else: |
| 1755 | # Fall back on the exact type. |
| 1756 | _G_base = types.GeneratorType |
| 1757 | |
| 1758 | |
| 1759 | class Generator(Iterator[T_co], Generic[T_co, T_contra, V_co], |
| 1760 | extra=_G_base): |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1761 | __slots__ = () |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1762 | |
| 1763 | def __new__(cls, *args, **kwds): |
| 1764 | if _geqv(cls, Generator): |
| 1765 | raise TypeError("Type Generator cannot be instantiated; " |
| 1766 | "create a subclass instead") |
| 1767 | return super().__new__(cls, *args, **kwds) |
| 1768 | |
| 1769 | |
Guido van Rossum | eb9aca3 | 2016-05-24 16:38:22 -0700 | [diff] [blame] | 1770 | # Internal type variable used for Type[]. |
Guido van Rossum | efa798d | 2016-08-23 11:01:50 -0700 | [diff] [blame] | 1771 | CT_co = TypeVar('CT_co', covariant=True, bound=type) |
Guido van Rossum | eb9aca3 | 2016-05-24 16:38:22 -0700 | [diff] [blame] | 1772 | |
| 1773 | |
Guido van Rossum | b22c708 | 2016-05-26 09:56:19 -0700 | [diff] [blame] | 1774 | # 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] | 1775 | class Type(Generic[CT_co], extra=type): |
Guido van Rossum | b22c708 | 2016-05-26 09:56:19 -0700 | [diff] [blame] | 1776 | """A special construct usable to annotate class objects. |
Guido van Rossum | eb9aca3 | 2016-05-24 16:38:22 -0700 | [diff] [blame] | 1777 | |
| 1778 | For example, suppose we have the following classes:: |
| 1779 | |
| 1780 | class User: ... # Abstract base for User classes |
| 1781 | class BasicUser(User): ... |
| 1782 | class ProUser(User): ... |
| 1783 | class TeamUser(User): ... |
| 1784 | |
| 1785 | And a function that takes a class argument that's a subclass of |
| 1786 | User and returns an instance of the corresponding class:: |
| 1787 | |
| 1788 | U = TypeVar('U', bound=User) |
| 1789 | def new_user(user_class: Type[U]) -> U: |
| 1790 | user = user_class() |
| 1791 | # (Here we could write the user object to a database) |
| 1792 | return user |
| 1793 | |
| 1794 | joe = new_user(BasicUser) |
| 1795 | |
| 1796 | At this point the type checker knows that joe has type BasicUser. |
| 1797 | """ |
| 1798 | |
Guido van Rossum | 4cefe74 | 2016-09-27 15:20:12 -0700 | [diff] [blame] | 1799 | __slots__ = () |
| 1800 | |
Guido van Rossum | eb9aca3 | 2016-05-24 16:38:22 -0700 | [diff] [blame] | 1801 | |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1802 | def _make_nmtuple(name, types): |
| 1803 | nm_tpl = collections.namedtuple(name, [n for n, t in types]) |
| 1804 | nm_tpl._field_types = dict(types) |
Guido van Rossum | 557d1eb | 2015-11-19 08:16:31 -0800 | [diff] [blame] | 1805 | try: |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1806 | nm_tpl.__module__ = sys._getframe(2).f_globals.get('__name__', '__main__') |
Guido van Rossum | 557d1eb | 2015-11-19 08:16:31 -0800 | [diff] [blame] | 1807 | except (AttributeError, ValueError): |
| 1808 | pass |
Guido van Rossum | 0a6976d | 2016-09-11 15:34:56 -0700 | [diff] [blame] | 1809 | return nm_tpl |
| 1810 | |
| 1811 | |
| 1812 | if sys.version_info[:2] >= (3, 6): |
| 1813 | class NamedTupleMeta(type): |
| 1814 | |
| 1815 | def __new__(cls, typename, bases, ns, *, _root=False): |
| 1816 | if _root: |
| 1817 | return super().__new__(cls, typename, bases, ns) |
| 1818 | types = ns.get('__annotations__', {}) |
| 1819 | return _make_nmtuple(typename, types.items()) |
| 1820 | |
| 1821 | class NamedTuple(metaclass=NamedTupleMeta, _root=True): |
| 1822 | """Typed version of namedtuple. |
| 1823 | |
| 1824 | Usage:: |
| 1825 | |
| 1826 | class Employee(NamedTuple): |
| 1827 | name: str |
| 1828 | id: int |
| 1829 | |
| 1830 | This is equivalent to:: |
| 1831 | |
| 1832 | Employee = collections.namedtuple('Employee', ['name', 'id']) |
| 1833 | |
| 1834 | The resulting class has one extra attribute: _field_types, |
| 1835 | giving a dict mapping field names to types. (The field names |
| 1836 | are in the _fields attribute, which is part of the namedtuple |
| 1837 | API.) Backward-compatible usage:: |
| 1838 | |
| 1839 | Employee = NamedTuple('Employee', [('name', str), ('id', int)]) |
| 1840 | """ |
| 1841 | |
| 1842 | def __new__(self, typename, fields): |
| 1843 | return _make_nmtuple(typename, fields) |
| 1844 | else: |
| 1845 | def NamedTuple(typename, fields): |
| 1846 | """Typed version of namedtuple. |
| 1847 | |
| 1848 | Usage:: |
| 1849 | |
| 1850 | Employee = typing.NamedTuple('Employee', [('name', str), 'id', int)]) |
| 1851 | |
| 1852 | This is equivalent to:: |
| 1853 | |
| 1854 | Employee = collections.namedtuple('Employee', ['name', 'id']) |
| 1855 | |
| 1856 | The resulting class has one extra attribute: _field_types, |
| 1857 | giving a dict mapping field names to types. (The field names |
| 1858 | are in the _fields attribute, which is part of the namedtuple |
| 1859 | API.) |
| 1860 | """ |
| 1861 | return _make_nmtuple(typename, fields) |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1862 | |
| 1863 | |
Guido van Rossum | 91185fe | 2016-06-08 11:19:11 -0700 | [diff] [blame] | 1864 | def NewType(name, tp): |
| 1865 | """NewType creates simple unique types with almost zero |
| 1866 | runtime overhead. NewType(name, tp) is considered a subtype of tp |
| 1867 | by static type checkers. At runtime, NewType(name, tp) returns |
| 1868 | a dummy function that simply returns its argument. Usage:: |
| 1869 | |
| 1870 | UserId = NewType('UserId', int) |
| 1871 | |
| 1872 | def name_by_id(user_id: UserId) -> str: |
| 1873 | ... |
| 1874 | |
| 1875 | UserId('user') # Fails type check |
| 1876 | |
| 1877 | name_by_id(42) # Fails type check |
| 1878 | name_by_id(UserId(42)) # OK |
| 1879 | |
| 1880 | num = UserId(5) + 1 # type: int |
| 1881 | """ |
| 1882 | |
| 1883 | def new_type(x): |
| 1884 | return x |
| 1885 | |
| 1886 | new_type.__name__ = name |
| 1887 | new_type.__supertype__ = tp |
| 1888 | return new_type |
| 1889 | |
| 1890 | |
Guido van Rossum | 0e0563c | 2016-04-05 14:54:25 -0700 | [diff] [blame] | 1891 | # Python-version-specific alias (Python 2: unicode; Python 3: str) |
| 1892 | Text = str |
| 1893 | |
| 1894 | |
Guido van Rossum | 91185fe | 2016-06-08 11:19:11 -0700 | [diff] [blame] | 1895 | # Constant that's True when type checking, but False here. |
| 1896 | TYPE_CHECKING = False |
| 1897 | |
| 1898 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1899 | class IO(Generic[AnyStr]): |
| 1900 | """Generic base class for TextIO and BinaryIO. |
| 1901 | |
| 1902 | This is an abstract, generic version of the return of open(). |
| 1903 | |
| 1904 | NOTE: This does not distinguish between the different possible |
| 1905 | classes (text vs. binary, read vs. write vs. read/write, |
| 1906 | append-only, unbuffered). The TextIO and BinaryIO subclasses |
| 1907 | below capture the distinctions between text vs. binary, which is |
| 1908 | pervasive in the interface; however we currently do not offer a |
| 1909 | way to track the other distinctions in the type system. |
| 1910 | """ |
| 1911 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1912 | __slots__ = () |
| 1913 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 1914 | @abstractproperty |
| 1915 | def mode(self) -> str: |
| 1916 | pass |
| 1917 | |
| 1918 | @abstractproperty |
| 1919 | def name(self) -> str: |
| 1920 | pass |
| 1921 | |
| 1922 | @abstractmethod |
| 1923 | def close(self) -> None: |
| 1924 | pass |
| 1925 | |
| 1926 | @abstractmethod |
| 1927 | def closed(self) -> bool: |
| 1928 | pass |
| 1929 | |
| 1930 | @abstractmethod |
| 1931 | def fileno(self) -> int: |
| 1932 | pass |
| 1933 | |
| 1934 | @abstractmethod |
| 1935 | def flush(self) -> None: |
| 1936 | pass |
| 1937 | |
| 1938 | @abstractmethod |
| 1939 | def isatty(self) -> bool: |
| 1940 | pass |
| 1941 | |
| 1942 | @abstractmethod |
| 1943 | def read(self, n: int = -1) -> AnyStr: |
| 1944 | pass |
| 1945 | |
| 1946 | @abstractmethod |
| 1947 | def readable(self) -> bool: |
| 1948 | pass |
| 1949 | |
| 1950 | @abstractmethod |
| 1951 | def readline(self, limit: int = -1) -> AnyStr: |
| 1952 | pass |
| 1953 | |
| 1954 | @abstractmethod |
| 1955 | def readlines(self, hint: int = -1) -> List[AnyStr]: |
| 1956 | pass |
| 1957 | |
| 1958 | @abstractmethod |
| 1959 | def seek(self, offset: int, whence: int = 0) -> int: |
| 1960 | pass |
| 1961 | |
| 1962 | @abstractmethod |
| 1963 | def seekable(self) -> bool: |
| 1964 | pass |
| 1965 | |
| 1966 | @abstractmethod |
| 1967 | def tell(self) -> int: |
| 1968 | pass |
| 1969 | |
| 1970 | @abstractmethod |
| 1971 | def truncate(self, size: int = None) -> int: |
| 1972 | pass |
| 1973 | |
| 1974 | @abstractmethod |
| 1975 | def writable(self) -> bool: |
| 1976 | pass |
| 1977 | |
| 1978 | @abstractmethod |
| 1979 | def write(self, s: AnyStr) -> int: |
| 1980 | pass |
| 1981 | |
| 1982 | @abstractmethod |
| 1983 | def writelines(self, lines: List[AnyStr]) -> None: |
| 1984 | pass |
| 1985 | |
| 1986 | @abstractmethod |
| 1987 | def __enter__(self) -> 'IO[AnyStr]': |
| 1988 | pass |
| 1989 | |
| 1990 | @abstractmethod |
| 1991 | def __exit__(self, type, value, traceback) -> None: |
| 1992 | pass |
| 1993 | |
| 1994 | |
| 1995 | class BinaryIO(IO[bytes]): |
| 1996 | """Typed version of the return of open() in binary mode.""" |
| 1997 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 1998 | __slots__ = () |
| 1999 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2000 | @abstractmethod |
| 2001 | def write(self, s: Union[bytes, bytearray]) -> int: |
| 2002 | pass |
| 2003 | |
| 2004 | @abstractmethod |
| 2005 | def __enter__(self) -> 'BinaryIO': |
| 2006 | pass |
| 2007 | |
| 2008 | |
| 2009 | class TextIO(IO[str]): |
| 2010 | """Typed version of the return of open() in text mode.""" |
| 2011 | |
Guido van Rossum | d70fe63 | 2015-08-05 12:11:06 +0200 | [diff] [blame] | 2012 | __slots__ = () |
| 2013 | |
Guido van Rossum | 46dbb7d | 2015-05-22 10:14:11 -0700 | [diff] [blame] | 2014 | @abstractproperty |
| 2015 | def buffer(self) -> BinaryIO: |
| 2016 | pass |
| 2017 | |
| 2018 | @abstractproperty |
| 2019 | def encoding(self) -> str: |
| 2020 | pass |
| 2021 | |
| 2022 | @abstractproperty |
| 2023 | def errors(self) -> str: |
| 2024 | pass |
| 2025 | |
| 2026 | @abstractproperty |
| 2027 | def line_buffering(self) -> bool: |
| 2028 | pass |
| 2029 | |
| 2030 | @abstractproperty |
| 2031 | def newlines(self) -> Any: |
| 2032 | pass |
| 2033 | |
| 2034 | @abstractmethod |
| 2035 | def __enter__(self) -> 'TextIO': |
| 2036 | pass |
| 2037 | |
| 2038 | |
| 2039 | class io: |
| 2040 | """Wrapper namespace for IO generic classes.""" |
| 2041 | |
| 2042 | __all__ = ['IO', 'TextIO', 'BinaryIO'] |
| 2043 | IO = IO |
| 2044 | TextIO = TextIO |
| 2045 | BinaryIO = BinaryIO |
| 2046 | |
| 2047 | io.__name__ = __name__ + '.io' |
| 2048 | sys.modules[io.__name__] = io |
| 2049 | |
| 2050 | |
| 2051 | Pattern = _TypeAlias('Pattern', AnyStr, type(stdlib_re.compile('')), |
| 2052 | lambda p: p.pattern) |
| 2053 | Match = _TypeAlias('Match', AnyStr, type(stdlib_re.match('', '')), |
| 2054 | lambda m: m.re.pattern) |
| 2055 | |
| 2056 | |
| 2057 | class re: |
| 2058 | """Wrapper namespace for re type aliases.""" |
| 2059 | |
| 2060 | __all__ = ['Pattern', 'Match'] |
| 2061 | Pattern = Pattern |
| 2062 | Match = Match |
| 2063 | |
| 2064 | re.__name__ = __name__ + '.re' |
| 2065 | sys.modules[re.__name__] = re |