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