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