Mercurial > repos > shellac > guppy_basecaller
comparison env/lib/python3.7/site-packages/typing_extensions.py @ 5:9b1c78e6ba9c draft default tip
"planemo upload commit 6c0a8142489327ece472c84e558c47da711a9142"
author | shellac |
---|---|
date | Mon, 01 Jun 2020 08:59:25 -0400 |
parents | 79f47841a781 |
children |
comparison
equal
deleted
inserted
replaced
4:79f47841a781 | 5:9b1c78e6ba9c |
---|---|
1 import abc | |
2 import collections | |
3 import contextlib | |
4 import sys | |
5 import typing | |
6 import collections.abc as collections_abc | |
7 import operator | |
8 | |
9 # These are used by Protocol implementation | |
10 # We use internal typing helpers here, but this significantly reduces | |
11 # code duplication. (Also this is only until Protocol is in typing.) | |
12 from typing import Generic, Callable, TypeVar, Tuple | |
13 | |
14 # After PEP 560, internal typing API was substantially reworked. | |
15 # This is especially important for Protocol class which uses internal APIs | |
16 # quite extensivelly. | |
17 PEP_560 = sys.version_info[:3] >= (3, 7, 0) | |
18 | |
19 if PEP_560: | |
20 GenericMeta = TypingMeta = type | |
21 else: | |
22 from typing import GenericMeta, TypingMeta | |
23 OLD_GENERICS = False | |
24 try: | |
25 from typing import _type_vars, _next_in_mro, _type_check | |
26 except ImportError: | |
27 OLD_GENERICS = True | |
28 try: | |
29 from typing import _subs_tree # noqa | |
30 SUBS_TREE = True | |
31 except ImportError: | |
32 SUBS_TREE = False | |
33 try: | |
34 from typing import _tp_cache | |
35 except ImportError: | |
36 def _tp_cache(x): | |
37 return x | |
38 try: | |
39 from typing import _TypingEllipsis, _TypingEmpty | |
40 except ImportError: | |
41 class _TypingEllipsis: | |
42 pass | |
43 | |
44 class _TypingEmpty: | |
45 pass | |
46 | |
47 | |
48 # The two functions below are copies of typing internal helpers. | |
49 # They are needed by _ProtocolMeta | |
50 | |
51 | |
52 def _no_slots_copy(dct): | |
53 dict_copy = dict(dct) | |
54 if '__slots__' in dict_copy: | |
55 for slot in dict_copy['__slots__']: | |
56 dict_copy.pop(slot, None) | |
57 return dict_copy | |
58 | |
59 | |
60 def _check_generic(cls, parameters): | |
61 if not cls.__parameters__: | |
62 raise TypeError("%s is not a generic class" % repr(cls)) | |
63 alen = len(parameters) | |
64 elen = len(cls.__parameters__) | |
65 if alen != elen: | |
66 raise TypeError("Too %s parameters for %s; actual %s, expected %s" % | |
67 ("many" if alen > elen else "few", repr(cls), alen, elen)) | |
68 | |
69 | |
70 if hasattr(typing, '_generic_new'): | |
71 _generic_new = typing._generic_new | |
72 else: | |
73 # Note: The '_generic_new(...)' function is used as a part of the | |
74 # process of creating a generic type and was added to the typing module | |
75 # as of Python 3.5.3. | |
76 # | |
77 # We've defined '_generic_new(...)' below to exactly match the behavior | |
78 # implemented in older versions of 'typing' bundled with Python 3.5.0 to | |
79 # 3.5.2. This helps eliminate redundancy when defining collection types | |
80 # like 'Deque' later. | |
81 # | |
82 # See https://github.com/python/typing/pull/308 for more details -- in | |
83 # particular, compare and contrast the definition of types like | |
84 # 'typing.List' before and after the merge. | |
85 | |
86 def _generic_new(base_cls, cls, *args, **kwargs): | |
87 return base_cls.__new__(cls, *args, **kwargs) | |
88 | |
89 # See https://github.com/python/typing/pull/439 | |
90 if hasattr(typing, '_geqv'): | |
91 from typing import _geqv | |
92 _geqv_defined = True | |
93 else: | |
94 _geqv = None | |
95 _geqv_defined = False | |
96 | |
97 if sys.version_info[:2] >= (3, 6): | |
98 import _collections_abc | |
99 _check_methods_in_mro = _collections_abc._check_methods | |
100 else: | |
101 def _check_methods_in_mro(C, *methods): | |
102 mro = C.__mro__ | |
103 for method in methods: | |
104 for B in mro: | |
105 if method in B.__dict__: | |
106 if B.__dict__[method] is None: | |
107 return NotImplemented | |
108 break | |
109 else: | |
110 return NotImplemented | |
111 return True | |
112 | |
113 | |
114 # Please keep __all__ alphabetized within each category. | |
115 __all__ = [ | |
116 # Super-special typing primitives. | |
117 'ClassVar', | |
118 'Final', | |
119 'Type', | |
120 | |
121 # ABCs (from collections.abc). | |
122 # The following are added depending on presence | |
123 # of their non-generic counterparts in stdlib: | |
124 # 'Awaitable', | |
125 # 'AsyncIterator', | |
126 # 'AsyncIterable', | |
127 # 'Coroutine', | |
128 # 'AsyncGenerator', | |
129 # 'AsyncContextManager', | |
130 # 'ChainMap', | |
131 | |
132 # Concrete collection types. | |
133 'ContextManager', | |
134 'Counter', | |
135 'Deque', | |
136 'DefaultDict', | |
137 'TypedDict', | |
138 | |
139 # One-off things. | |
140 'final', | |
141 'IntVar', | |
142 'Literal', | |
143 'NewType', | |
144 'overload', | |
145 'Text', | |
146 'TYPE_CHECKING', | |
147 ] | |
148 | |
149 # Annotated relies on substitution trees of pep 560. It will not work for | |
150 # versions of typing older than 3.5.3 | |
151 HAVE_ANNOTATED = PEP_560 or SUBS_TREE | |
152 | |
153 if PEP_560: | |
154 __all__.extend(["get_args", "get_origin", "get_type_hints"]) | |
155 | |
156 if HAVE_ANNOTATED: | |
157 __all__.append("Annotated") | |
158 | |
159 # Protocols are hard to backport to the original version of typing 3.5.0 | |
160 HAVE_PROTOCOLS = sys.version_info[:3] != (3, 5, 0) | |
161 | |
162 if HAVE_PROTOCOLS: | |
163 __all__.extend(['Protocol', 'runtime', 'runtime_checkable']) | |
164 | |
165 | |
166 # TODO | |
167 if hasattr(typing, 'NoReturn'): | |
168 NoReturn = typing.NoReturn | |
169 elif hasattr(typing, '_FinalTypingBase'): | |
170 class _NoReturn(typing._FinalTypingBase, _root=True): | |
171 """Special type indicating functions that never return. | |
172 Example:: | |
173 | |
174 from typing import NoReturn | |
175 | |
176 def stop() -> NoReturn: | |
177 raise Exception('no way') | |
178 | |
179 This type is invalid in other positions, e.g., ``List[NoReturn]`` | |
180 will fail in static type checkers. | |
181 """ | |
182 __slots__ = () | |
183 | |
184 def __instancecheck__(self, obj): | |
185 raise TypeError("NoReturn cannot be used with isinstance().") | |
186 | |
187 def __subclasscheck__(self, cls): | |
188 raise TypeError("NoReturn cannot be used with issubclass().") | |
189 | |
190 NoReturn = _NoReturn(_root=True) | |
191 else: | |
192 class _NoReturnMeta(typing.TypingMeta): | |
193 """Metaclass for NoReturn""" | |
194 def __new__(cls, name, bases, namespace, _root=False): | |
195 return super().__new__(cls, name, bases, namespace, _root=_root) | |
196 | |
197 def __instancecheck__(self, obj): | |
198 raise TypeError("NoReturn cannot be used with isinstance().") | |
199 | |
200 def __subclasscheck__(self, cls): | |
201 raise TypeError("NoReturn cannot be used with issubclass().") | |
202 | |
203 class NoReturn(typing.Final, metaclass=_NoReturnMeta, _root=True): | |
204 """Special type indicating functions that never return. | |
205 Example:: | |
206 | |
207 from typing import NoReturn | |
208 | |
209 def stop() -> NoReturn: | |
210 raise Exception('no way') | |
211 | |
212 This type is invalid in other positions, e.g., ``List[NoReturn]`` | |
213 will fail in static type checkers. | |
214 """ | |
215 __slots__ = () | |
216 | |
217 | |
218 # Some unconstrained type variables. These are used by the container types. | |
219 # (These are not for export.) | |
220 T = typing.TypeVar('T') # Any type. | |
221 KT = typing.TypeVar('KT') # Key type. | |
222 VT = typing.TypeVar('VT') # Value type. | |
223 T_co = typing.TypeVar('T_co', covariant=True) # Any type covariant containers. | |
224 V_co = typing.TypeVar('V_co', covariant=True) # Any type covariant containers. | |
225 VT_co = typing.TypeVar('VT_co', covariant=True) # Value type covariant containers. | |
226 T_contra = typing.TypeVar('T_contra', contravariant=True) # Ditto contravariant. | |
227 | |
228 | |
229 if hasattr(typing, 'ClassVar'): | |
230 ClassVar = typing.ClassVar | |
231 elif hasattr(typing, '_FinalTypingBase'): | |
232 class _ClassVar(typing._FinalTypingBase, _root=True): | |
233 """Special type construct to mark class variables. | |
234 | |
235 An annotation wrapped in ClassVar indicates that a given | |
236 attribute is intended to be used as a class variable and | |
237 should not be set on instances of that class. Usage:: | |
238 | |
239 class Starship: | |
240 stats: ClassVar[Dict[str, int]] = {} # class variable | |
241 damage: int = 10 # instance variable | |
242 | |
243 ClassVar accepts only types and cannot be further subscribed. | |
244 | |
245 Note that ClassVar is not a class itself, and should not | |
246 be used with isinstance() or issubclass(). | |
247 """ | |
248 | |
249 __slots__ = ('__type__',) | |
250 | |
251 def __init__(self, tp=None, **kwds): | |
252 self.__type__ = tp | |
253 | |
254 def __getitem__(self, item): | |
255 cls = type(self) | |
256 if self.__type__ is None: | |
257 return cls(typing._type_check(item, | |
258 '{} accepts only single type.'.format(cls.__name__[1:])), | |
259 _root=True) | |
260 raise TypeError('{} cannot be further subscripted' | |
261 .format(cls.__name__[1:])) | |
262 | |
263 def _eval_type(self, globalns, localns): | |
264 new_tp = typing._eval_type(self.__type__, globalns, localns) | |
265 if new_tp == self.__type__: | |
266 return self | |
267 return type(self)(new_tp, _root=True) | |
268 | |
269 def __repr__(self): | |
270 r = super().__repr__() | |
271 if self.__type__ is not None: | |
272 r += '[{}]'.format(typing._type_repr(self.__type__)) | |
273 return r | |
274 | |
275 def __hash__(self): | |
276 return hash((type(self).__name__, self.__type__)) | |
277 | |
278 def __eq__(self, other): | |
279 if not isinstance(other, _ClassVar): | |
280 return NotImplemented | |
281 if self.__type__ is not None: | |
282 return self.__type__ == other.__type__ | |
283 return self is other | |
284 | |
285 ClassVar = _ClassVar(_root=True) | |
286 else: | |
287 class _ClassVarMeta(typing.TypingMeta): | |
288 """Metaclass for ClassVar""" | |
289 | |
290 def __new__(cls, name, bases, namespace, tp=None, _root=False): | |
291 self = super().__new__(cls, name, bases, namespace, _root=_root) | |
292 if tp is not None: | |
293 self.__type__ = tp | |
294 return self | |
295 | |
296 def __instancecheck__(self, obj): | |
297 raise TypeError("ClassVar cannot be used with isinstance().") | |
298 | |
299 def __subclasscheck__(self, cls): | |
300 raise TypeError("ClassVar cannot be used with issubclass().") | |
301 | |
302 def __getitem__(self, item): | |
303 cls = type(self) | |
304 if self.__type__ is not None: | |
305 raise TypeError('{} cannot be further subscripted' | |
306 .format(cls.__name__[1:])) | |
307 | |
308 param = typing._type_check( | |
309 item, | |
310 '{} accepts only single type.'.format(cls.__name__[1:])) | |
311 return cls(self.__name__, self.__bases__, | |
312 dict(self.__dict__), tp=param, _root=True) | |
313 | |
314 def _eval_type(self, globalns, localns): | |
315 new_tp = typing._eval_type(self.__type__, globalns, localns) | |
316 if new_tp == self.__type__: | |
317 return self | |
318 return type(self)(self.__name__, self.__bases__, | |
319 dict(self.__dict__), tp=self.__type__, | |
320 _root=True) | |
321 | |
322 def __repr__(self): | |
323 r = super().__repr__() | |
324 if self.__type__ is not None: | |
325 r += '[{}]'.format(typing._type_repr(self.__type__)) | |
326 return r | |
327 | |
328 def __hash__(self): | |
329 return hash((type(self).__name__, self.__type__)) | |
330 | |
331 def __eq__(self, other): | |
332 if not isinstance(other, ClassVar): | |
333 return NotImplemented | |
334 if self.__type__ is not None: | |
335 return self.__type__ == other.__type__ | |
336 return self is other | |
337 | |
338 class ClassVar(typing.Final, metaclass=_ClassVarMeta, _root=True): | |
339 """Special type construct to mark class variables. | |
340 | |
341 An annotation wrapped in ClassVar indicates that a given | |
342 attribute is intended to be used as a class variable and | |
343 should not be set on instances of that class. Usage:: | |
344 | |
345 class Starship: | |
346 stats: ClassVar[Dict[str, int]] = {} # class variable | |
347 damage: int = 10 # instance variable | |
348 | |
349 ClassVar accepts only types and cannot be further subscribed. | |
350 | |
351 Note that ClassVar is not a class itself, and should not | |
352 be used with isinstance() or issubclass(). | |
353 """ | |
354 | |
355 __type__ = None | |
356 | |
357 # On older versions of typing there is an internal class named "Final". | |
358 if hasattr(typing, 'Final') and sys.version_info[:2] >= (3, 7): | |
359 Final = typing.Final | |
360 elif sys.version_info[:2] >= (3, 7): | |
361 class _FinalForm(typing._SpecialForm, _root=True): | |
362 | |
363 def __repr__(self): | |
364 return 'typing_extensions.' + self._name | |
365 | |
366 def __getitem__(self, parameters): | |
367 item = typing._type_check(parameters, | |
368 '{} accepts only single type'.format(self._name)) | |
369 return _GenericAlias(self, (item,)) | |
370 | |
371 Final = _FinalForm('Final', | |
372 doc="""A special typing construct to indicate that a name | |
373 cannot be re-assigned or overridden in a subclass. | |
374 For example: | |
375 | |
376 MAX_SIZE: Final = 9000 | |
377 MAX_SIZE += 1 # Error reported by type checker | |
378 | |
379 class Connection: | |
380 TIMEOUT: Final[int] = 10 | |
381 class FastConnector(Connection): | |
382 TIMEOUT = 1 # Error reported by type checker | |
383 | |
384 There is no runtime checking of these properties.""") | |
385 elif hasattr(typing, '_FinalTypingBase'): | |
386 class _Final(typing._FinalTypingBase, _root=True): | |
387 """A special typing construct to indicate that a name | |
388 cannot be re-assigned or overridden in a subclass. | |
389 For example: | |
390 | |
391 MAX_SIZE: Final = 9000 | |
392 MAX_SIZE += 1 # Error reported by type checker | |
393 | |
394 class Connection: | |
395 TIMEOUT: Final[int] = 10 | |
396 class FastConnector(Connection): | |
397 TIMEOUT = 1 # Error reported by type checker | |
398 | |
399 There is no runtime checking of these properties. | |
400 """ | |
401 | |
402 __slots__ = ('__type__',) | |
403 | |
404 def __init__(self, tp=None, **kwds): | |
405 self.__type__ = tp | |
406 | |
407 def __getitem__(self, item): | |
408 cls = type(self) | |
409 if self.__type__ is None: | |
410 return cls(typing._type_check(item, | |
411 '{} accepts only single type.'.format(cls.__name__[1:])), | |
412 _root=True) | |
413 raise TypeError('{} cannot be further subscripted' | |
414 .format(cls.__name__[1:])) | |
415 | |
416 def _eval_type(self, globalns, localns): | |
417 new_tp = typing._eval_type(self.__type__, globalns, localns) | |
418 if new_tp == self.__type__: | |
419 return self | |
420 return type(self)(new_tp, _root=True) | |
421 | |
422 def __repr__(self): | |
423 r = super().__repr__() | |
424 if self.__type__ is not None: | |
425 r += '[{}]'.format(typing._type_repr(self.__type__)) | |
426 return r | |
427 | |
428 def __hash__(self): | |
429 return hash((type(self).__name__, self.__type__)) | |
430 | |
431 def __eq__(self, other): | |
432 if not isinstance(other, _Final): | |
433 return NotImplemented | |
434 if self.__type__ is not None: | |
435 return self.__type__ == other.__type__ | |
436 return self is other | |
437 | |
438 Final = _Final(_root=True) | |
439 else: | |
440 class _FinalMeta(typing.TypingMeta): | |
441 """Metaclass for Final""" | |
442 | |
443 def __new__(cls, name, bases, namespace, tp=None, _root=False): | |
444 self = super().__new__(cls, name, bases, namespace, _root=_root) | |
445 if tp is not None: | |
446 self.__type__ = tp | |
447 return self | |
448 | |
449 def __instancecheck__(self, obj): | |
450 raise TypeError("Final cannot be used with isinstance().") | |
451 | |
452 def __subclasscheck__(self, cls): | |
453 raise TypeError("Final cannot be used with issubclass().") | |
454 | |
455 def __getitem__(self, item): | |
456 cls = type(self) | |
457 if self.__type__ is not None: | |
458 raise TypeError('{} cannot be further subscripted' | |
459 .format(cls.__name__[1:])) | |
460 | |
461 param = typing._type_check( | |
462 item, | |
463 '{} accepts only single type.'.format(cls.__name__[1:])) | |
464 return cls(self.__name__, self.__bases__, | |
465 dict(self.__dict__), tp=param, _root=True) | |
466 | |
467 def _eval_type(self, globalns, localns): | |
468 new_tp = typing._eval_type(self.__type__, globalns, localns) | |
469 if new_tp == self.__type__: | |
470 return self | |
471 return type(self)(self.__name__, self.__bases__, | |
472 dict(self.__dict__), tp=self.__type__, | |
473 _root=True) | |
474 | |
475 def __repr__(self): | |
476 r = super().__repr__() | |
477 if self.__type__ is not None: | |
478 r += '[{}]'.format(typing._type_repr(self.__type__)) | |
479 return r | |
480 | |
481 def __hash__(self): | |
482 return hash((type(self).__name__, self.__type__)) | |
483 | |
484 def __eq__(self, other): | |
485 if not isinstance(other, Final): | |
486 return NotImplemented | |
487 if self.__type__ is not None: | |
488 return self.__type__ == other.__type__ | |
489 return self is other | |
490 | |
491 class Final(typing.Final, metaclass=_FinalMeta, _root=True): | |
492 """A special typing construct to indicate that a name | |
493 cannot be re-assigned or overridden in a subclass. | |
494 For example: | |
495 | |
496 MAX_SIZE: Final = 9000 | |
497 MAX_SIZE += 1 # Error reported by type checker | |
498 | |
499 class Connection: | |
500 TIMEOUT: Final[int] = 10 | |
501 class FastConnector(Connection): | |
502 TIMEOUT = 1 # Error reported by type checker | |
503 | |
504 There is no runtime checking of these properties. | |
505 """ | |
506 | |
507 __type__ = None | |
508 | |
509 | |
510 if hasattr(typing, 'final'): | |
511 final = typing.final | |
512 else: | |
513 def final(f): | |
514 """This decorator can be used to indicate to type checkers that | |
515 the decorated method cannot be overridden, and decorated class | |
516 cannot be subclassed. For example: | |
517 | |
518 class Base: | |
519 @final | |
520 def done(self) -> None: | |
521 ... | |
522 class Sub(Base): | |
523 def done(self) -> None: # Error reported by type checker | |
524 ... | |
525 @final | |
526 class Leaf: | |
527 ... | |
528 class Other(Leaf): # Error reported by type checker | |
529 ... | |
530 | |
531 There is no runtime checking of these properties. | |
532 """ | |
533 return f | |
534 | |
535 | |
536 def IntVar(name): | |
537 return TypeVar(name) | |
538 | |
539 | |
540 if hasattr(typing, 'Literal'): | |
541 Literal = typing.Literal | |
542 elif sys.version_info[:2] >= (3, 7): | |
543 class _LiteralForm(typing._SpecialForm, _root=True): | |
544 | |
545 def __repr__(self): | |
546 return 'typing_extensions.' + self._name | |
547 | |
548 def __getitem__(self, parameters): | |
549 return _GenericAlias(self, parameters) | |
550 | |
551 Literal = _LiteralForm('Literal', | |
552 doc="""A type that can be used to indicate to type checkers | |
553 that the corresponding value has a value literally equivalent | |
554 to the provided parameter. For example: | |
555 | |
556 var: Literal[4] = 4 | |
557 | |
558 The type checker understands that 'var' is literally equal to | |
559 the value 4 and no other value. | |
560 | |
561 Literal[...] cannot be subclassed. There is no runtime | |
562 checking verifying that the parameter is actually a value | |
563 instead of a type.""") | |
564 elif hasattr(typing, '_FinalTypingBase'): | |
565 class _Literal(typing._FinalTypingBase, _root=True): | |
566 """A type that can be used to indicate to type checkers that the | |
567 corresponding value has a value literally equivalent to the | |
568 provided parameter. For example: | |
569 | |
570 var: Literal[4] = 4 | |
571 | |
572 The type checker understands that 'var' is literally equal to the | |
573 value 4 and no other value. | |
574 | |
575 Literal[...] cannot be subclassed. There is no runtime checking | |
576 verifying that the parameter is actually a value instead of a type. | |
577 """ | |
578 | |
579 __slots__ = ('__values__',) | |
580 | |
581 def __init__(self, values=None, **kwds): | |
582 self.__values__ = values | |
583 | |
584 def __getitem__(self, values): | |
585 cls = type(self) | |
586 if self.__values__ is None: | |
587 if not isinstance(values, tuple): | |
588 values = (values,) | |
589 return cls(values, _root=True) | |
590 raise TypeError('{} cannot be further subscripted' | |
591 .format(cls.__name__[1:])) | |
592 | |
593 def _eval_type(self, globalns, localns): | |
594 return self | |
595 | |
596 def __repr__(self): | |
597 r = super().__repr__() | |
598 if self.__values__ is not None: | |
599 r += '[{}]'.format(', '.join(map(typing._type_repr, self.__values__))) | |
600 return r | |
601 | |
602 def __hash__(self): | |
603 return hash((type(self).__name__, self.__values__)) | |
604 | |
605 def __eq__(self, other): | |
606 if not isinstance(other, _Literal): | |
607 return NotImplemented | |
608 if self.__values__ is not None: | |
609 return self.__values__ == other.__values__ | |
610 return self is other | |
611 | |
612 Literal = _Literal(_root=True) | |
613 else: | |
614 class _LiteralMeta(typing.TypingMeta): | |
615 """Metaclass for Literal""" | |
616 | |
617 def __new__(cls, name, bases, namespace, values=None, _root=False): | |
618 self = super().__new__(cls, name, bases, namespace, _root=_root) | |
619 if values is not None: | |
620 self.__values__ = values | |
621 return self | |
622 | |
623 def __instancecheck__(self, obj): | |
624 raise TypeError("Literal cannot be used with isinstance().") | |
625 | |
626 def __subclasscheck__(self, cls): | |
627 raise TypeError("Literal cannot be used with issubclass().") | |
628 | |
629 def __getitem__(self, item): | |
630 cls = type(self) | |
631 if self.__values__ is not None: | |
632 raise TypeError('{} cannot be further subscripted' | |
633 .format(cls.__name__[1:])) | |
634 | |
635 if not isinstance(item, tuple): | |
636 item = (item,) | |
637 return cls(self.__name__, self.__bases__, | |
638 dict(self.__dict__), values=item, _root=True) | |
639 | |
640 def _eval_type(self, globalns, localns): | |
641 return self | |
642 | |
643 def __repr__(self): | |
644 r = super().__repr__() | |
645 if self.__values__ is not None: | |
646 r += '[{}]'.format(', '.join(map(typing._type_repr, self.__values__))) | |
647 return r | |
648 | |
649 def __hash__(self): | |
650 return hash((type(self).__name__, self.__values__)) | |
651 | |
652 def __eq__(self, other): | |
653 if not isinstance(other, Literal): | |
654 return NotImplemented | |
655 if self.__values__ is not None: | |
656 return self.__values__ == other.__values__ | |
657 return self is other | |
658 | |
659 class Literal(typing.Final, metaclass=_LiteralMeta, _root=True): | |
660 """A type that can be used to indicate to type checkers that the | |
661 corresponding value has a value literally equivalent to the | |
662 provided parameter. For example: | |
663 | |
664 var: Literal[4] = 4 | |
665 | |
666 The type checker understands that 'var' is literally equal to the | |
667 value 4 and no other value. | |
668 | |
669 Literal[...] cannot be subclassed. There is no runtime checking | |
670 verifying that the parameter is actually a value instead of a type. | |
671 """ | |
672 | |
673 __values__ = None | |
674 | |
675 | |
676 def _overload_dummy(*args, **kwds): | |
677 """Helper for @overload to raise when called.""" | |
678 raise NotImplementedError( | |
679 "You should not call an overloaded function. " | |
680 "A series of @overload-decorated functions " | |
681 "outside a stub module should always be followed " | |
682 "by an implementation that is not @overload-ed.") | |
683 | |
684 | |
685 def overload(func): | |
686 """Decorator for overloaded functions/methods. | |
687 | |
688 In a stub file, place two or more stub definitions for the same | |
689 function in a row, each decorated with @overload. For example: | |
690 | |
691 @overload | |
692 def utf8(value: None) -> None: ... | |
693 @overload | |
694 def utf8(value: bytes) -> bytes: ... | |
695 @overload | |
696 def utf8(value: str) -> bytes: ... | |
697 | |
698 In a non-stub file (i.e. a regular .py file), do the same but | |
699 follow it with an implementation. The implementation should *not* | |
700 be decorated with @overload. For example: | |
701 | |
702 @overload | |
703 def utf8(value: None) -> None: ... | |
704 @overload | |
705 def utf8(value: bytes) -> bytes: ... | |
706 @overload | |
707 def utf8(value: str) -> bytes: ... | |
708 def utf8(value): | |
709 # implementation goes here | |
710 """ | |
711 return _overload_dummy | |
712 | |
713 | |
714 # This is not a real generic class. Don't use outside annotations. | |
715 if hasattr(typing, 'Type'): | |
716 Type = typing.Type | |
717 else: | |
718 # Internal type variable used for Type[]. | |
719 CT_co = typing.TypeVar('CT_co', covariant=True, bound=type) | |
720 | |
721 class Type(typing.Generic[CT_co], extra=type): | |
722 """A special construct usable to annotate class objects. | |
723 | |
724 For example, suppose we have the following classes:: | |
725 | |
726 class User: ... # Abstract base for User classes | |
727 class BasicUser(User): ... | |
728 class ProUser(User): ... | |
729 class TeamUser(User): ... | |
730 | |
731 And a function that takes a class argument that's a subclass of | |
732 User and returns an instance of the corresponding class:: | |
733 | |
734 U = TypeVar('U', bound=User) | |
735 def new_user(user_class: Type[U]) -> U: | |
736 user = user_class() | |
737 # (Here we could write the user object to a database) | |
738 return user | |
739 joe = new_user(BasicUser) | |
740 | |
741 At this point the type checker knows that joe has type BasicUser. | |
742 """ | |
743 | |
744 __slots__ = () | |
745 | |
746 | |
747 # Various ABCs mimicking those in collections.abc. | |
748 # A few are simply re-exported for completeness. | |
749 | |
750 def _define_guard(type_name): | |
751 """ | |
752 Returns True if the given type isn't defined in typing but | |
753 is defined in collections_abc. | |
754 | |
755 Adds the type to __all__ if the collection is found in either | |
756 typing or collection_abc. | |
757 """ | |
758 if hasattr(typing, type_name): | |
759 __all__.append(type_name) | |
760 globals()[type_name] = getattr(typing, type_name) | |
761 return False | |
762 elif hasattr(collections_abc, type_name): | |
763 __all__.append(type_name) | |
764 return True | |
765 else: | |
766 return False | |
767 | |
768 | |
769 class _ExtensionsGenericMeta(GenericMeta): | |
770 def __subclasscheck__(self, subclass): | |
771 """This mimics a more modern GenericMeta.__subclasscheck__() logic | |
772 (that does not have problems with recursion) to work around interactions | |
773 between collections, typing, and typing_extensions on older | |
774 versions of Python, see https://github.com/python/typing/issues/501. | |
775 """ | |
776 if sys.version_info[:3] >= (3, 5, 3) or sys.version_info[:3] < (3, 5, 0): | |
777 if self.__origin__ is not None: | |
778 if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools']: | |
779 raise TypeError("Parameterized generics cannot be used with class " | |
780 "or instance checks") | |
781 return False | |
782 if not self.__extra__: | |
783 return super().__subclasscheck__(subclass) | |
784 res = self.__extra__.__subclasshook__(subclass) | |
785 if res is not NotImplemented: | |
786 return res | |
787 if self.__extra__ in subclass.__mro__: | |
788 return True | |
789 for scls in self.__extra__.__subclasses__(): | |
790 if isinstance(scls, GenericMeta): | |
791 continue | |
792 if issubclass(subclass, scls): | |
793 return True | |
794 return False | |
795 | |
796 | |
797 if _define_guard('Awaitable'): | |
798 class Awaitable(typing.Generic[T_co], metaclass=_ExtensionsGenericMeta, | |
799 extra=collections_abc.Awaitable): | |
800 __slots__ = () | |
801 | |
802 | |
803 if _define_guard('Coroutine'): | |
804 class Coroutine(Awaitable[V_co], typing.Generic[T_co, T_contra, V_co], | |
805 metaclass=_ExtensionsGenericMeta, | |
806 extra=collections_abc.Coroutine): | |
807 __slots__ = () | |
808 | |
809 | |
810 if _define_guard('AsyncIterable'): | |
811 class AsyncIterable(typing.Generic[T_co], | |
812 metaclass=_ExtensionsGenericMeta, | |
813 extra=collections_abc.AsyncIterable): | |
814 __slots__ = () | |
815 | |
816 | |
817 if _define_guard('AsyncIterator'): | |
818 class AsyncIterator(AsyncIterable[T_co], | |
819 metaclass=_ExtensionsGenericMeta, | |
820 extra=collections_abc.AsyncIterator): | |
821 __slots__ = () | |
822 | |
823 | |
824 if hasattr(typing, 'Deque'): | |
825 Deque = typing.Deque | |
826 elif _geqv_defined: | |
827 class Deque(collections.deque, typing.MutableSequence[T], | |
828 metaclass=_ExtensionsGenericMeta, | |
829 extra=collections.deque): | |
830 __slots__ = () | |
831 | |
832 def __new__(cls, *args, **kwds): | |
833 if _geqv(cls, Deque): | |
834 return collections.deque(*args, **kwds) | |
835 return _generic_new(collections.deque, cls, *args, **kwds) | |
836 else: | |
837 class Deque(collections.deque, typing.MutableSequence[T], | |
838 metaclass=_ExtensionsGenericMeta, | |
839 extra=collections.deque): | |
840 __slots__ = () | |
841 | |
842 def __new__(cls, *args, **kwds): | |
843 if cls._gorg is Deque: | |
844 return collections.deque(*args, **kwds) | |
845 return _generic_new(collections.deque, cls, *args, **kwds) | |
846 | |
847 | |
848 if hasattr(typing, 'ContextManager'): | |
849 ContextManager = typing.ContextManager | |
850 elif hasattr(contextlib, 'AbstractContextManager'): | |
851 class ContextManager(typing.Generic[T_co], | |
852 metaclass=_ExtensionsGenericMeta, | |
853 extra=contextlib.AbstractContextManager): | |
854 __slots__ = () | |
855 else: | |
856 class ContextManager(typing.Generic[T_co]): | |
857 __slots__ = () | |
858 | |
859 def __enter__(self): | |
860 return self | |
861 | |
862 @abc.abstractmethod | |
863 def __exit__(self, exc_type, exc_value, traceback): | |
864 return None | |
865 | |
866 @classmethod | |
867 def __subclasshook__(cls, C): | |
868 if cls is ContextManager: | |
869 # In Python 3.6+, it is possible to set a method to None to | |
870 # explicitly indicate that the class does not implement an ABC | |
871 # (https://bugs.python.org/issue25958), but we do not support | |
872 # that pattern here because this fallback class is only used | |
873 # in Python 3.5 and earlier. | |
874 if (any("__enter__" in B.__dict__ for B in C.__mro__) and | |
875 any("__exit__" in B.__dict__ for B in C.__mro__)): | |
876 return True | |
877 return NotImplemented | |
878 | |
879 | |
880 if hasattr(typing, 'AsyncContextManager'): | |
881 AsyncContextManager = typing.AsyncContextManager | |
882 __all__.append('AsyncContextManager') | |
883 elif hasattr(contextlib, 'AbstractAsyncContextManager'): | |
884 class AsyncContextManager(typing.Generic[T_co], | |
885 metaclass=_ExtensionsGenericMeta, | |
886 extra=contextlib.AbstractAsyncContextManager): | |
887 __slots__ = () | |
888 | |
889 __all__.append('AsyncContextManager') | |
890 elif sys.version_info[:2] >= (3, 5): | |
891 exec(""" | |
892 class AsyncContextManager(typing.Generic[T_co]): | |
893 __slots__ = () | |
894 | |
895 async def __aenter__(self): | |
896 return self | |
897 | |
898 @abc.abstractmethod | |
899 async def __aexit__(self, exc_type, exc_value, traceback): | |
900 return None | |
901 | |
902 @classmethod | |
903 def __subclasshook__(cls, C): | |
904 if cls is AsyncContextManager: | |
905 return _check_methods_in_mro(C, "__aenter__", "__aexit__") | |
906 return NotImplemented | |
907 | |
908 __all__.append('AsyncContextManager') | |
909 """) | |
910 | |
911 | |
912 if hasattr(typing, 'DefaultDict'): | |
913 DefaultDict = typing.DefaultDict | |
914 elif _geqv_defined: | |
915 class DefaultDict(collections.defaultdict, typing.MutableMapping[KT, VT], | |
916 metaclass=_ExtensionsGenericMeta, | |
917 extra=collections.defaultdict): | |
918 | |
919 __slots__ = () | |
920 | |
921 def __new__(cls, *args, **kwds): | |
922 if _geqv(cls, DefaultDict): | |
923 return collections.defaultdict(*args, **kwds) | |
924 return _generic_new(collections.defaultdict, cls, *args, **kwds) | |
925 else: | |
926 class DefaultDict(collections.defaultdict, typing.MutableMapping[KT, VT], | |
927 metaclass=_ExtensionsGenericMeta, | |
928 extra=collections.defaultdict): | |
929 | |
930 __slots__ = () | |
931 | |
932 def __new__(cls, *args, **kwds): | |
933 if cls._gorg is DefaultDict: | |
934 return collections.defaultdict(*args, **kwds) | |
935 return _generic_new(collections.defaultdict, cls, *args, **kwds) | |
936 | |
937 | |
938 if hasattr(typing, 'Counter'): | |
939 Counter = typing.Counter | |
940 elif (3, 5, 0) <= sys.version_info[:3] <= (3, 5, 1): | |
941 assert _geqv_defined | |
942 _TInt = typing.TypeVar('_TInt') | |
943 | |
944 class _CounterMeta(typing.GenericMeta): | |
945 """Metaclass for Counter""" | |
946 def __getitem__(self, item): | |
947 return super().__getitem__((item, int)) | |
948 | |
949 class Counter(collections.Counter, | |
950 typing.Dict[T, int], | |
951 metaclass=_CounterMeta, | |
952 extra=collections.Counter): | |
953 | |
954 __slots__ = () | |
955 | |
956 def __new__(cls, *args, **kwds): | |
957 if _geqv(cls, Counter): | |
958 return collections.Counter(*args, **kwds) | |
959 return _generic_new(collections.Counter, cls, *args, **kwds) | |
960 | |
961 elif _geqv_defined: | |
962 class Counter(collections.Counter, | |
963 typing.Dict[T, int], | |
964 metaclass=_ExtensionsGenericMeta, extra=collections.Counter): | |
965 | |
966 __slots__ = () | |
967 | |
968 def __new__(cls, *args, **kwds): | |
969 if _geqv(cls, Counter): | |
970 return collections.Counter(*args, **kwds) | |
971 return _generic_new(collections.Counter, cls, *args, **kwds) | |
972 | |
973 else: | |
974 class Counter(collections.Counter, | |
975 typing.Dict[T, int], | |
976 metaclass=_ExtensionsGenericMeta, extra=collections.Counter): | |
977 | |
978 __slots__ = () | |
979 | |
980 def __new__(cls, *args, **kwds): | |
981 if cls._gorg is Counter: | |
982 return collections.Counter(*args, **kwds) | |
983 return _generic_new(collections.Counter, cls, *args, **kwds) | |
984 | |
985 | |
986 if hasattr(typing, 'ChainMap'): | |
987 ChainMap = typing.ChainMap | |
988 __all__.append('ChainMap') | |
989 elif hasattr(collections, 'ChainMap'): | |
990 # ChainMap only exists in 3.3+ | |
991 if _geqv_defined: | |
992 class ChainMap(collections.ChainMap, typing.MutableMapping[KT, VT], | |
993 metaclass=_ExtensionsGenericMeta, | |
994 extra=collections.ChainMap): | |
995 | |
996 __slots__ = () | |
997 | |
998 def __new__(cls, *args, **kwds): | |
999 if _geqv(cls, ChainMap): | |
1000 return collections.ChainMap(*args, **kwds) | |
1001 return _generic_new(collections.ChainMap, cls, *args, **kwds) | |
1002 else: | |
1003 class ChainMap(collections.ChainMap, typing.MutableMapping[KT, VT], | |
1004 metaclass=_ExtensionsGenericMeta, | |
1005 extra=collections.ChainMap): | |
1006 | |
1007 __slots__ = () | |
1008 | |
1009 def __new__(cls, *args, **kwds): | |
1010 if cls._gorg is ChainMap: | |
1011 return collections.ChainMap(*args, **kwds) | |
1012 return _generic_new(collections.ChainMap, cls, *args, **kwds) | |
1013 | |
1014 __all__.append('ChainMap') | |
1015 | |
1016 | |
1017 if _define_guard('AsyncGenerator'): | |
1018 class AsyncGenerator(AsyncIterator[T_co], typing.Generic[T_co, T_contra], | |
1019 metaclass=_ExtensionsGenericMeta, | |
1020 extra=collections_abc.AsyncGenerator): | |
1021 __slots__ = () | |
1022 | |
1023 | |
1024 if hasattr(typing, 'NewType'): | |
1025 NewType = typing.NewType | |
1026 else: | |
1027 def NewType(name, tp): | |
1028 """NewType creates simple unique types with almost zero | |
1029 runtime overhead. NewType(name, tp) is considered a subtype of tp | |
1030 by static type checkers. At runtime, NewType(name, tp) returns | |
1031 a dummy function that simply returns its argument. Usage:: | |
1032 | |
1033 UserId = NewType('UserId', int) | |
1034 | |
1035 def name_by_id(user_id: UserId) -> str: | |
1036 ... | |
1037 | |
1038 UserId('user') # Fails type check | |
1039 | |
1040 name_by_id(42) # Fails type check | |
1041 name_by_id(UserId(42)) # OK | |
1042 | |
1043 num = UserId(5) + 1 # type: int | |
1044 """ | |
1045 | |
1046 def new_type(x): | |
1047 return x | |
1048 | |
1049 new_type.__name__ = name | |
1050 new_type.__supertype__ = tp | |
1051 return new_type | |
1052 | |
1053 | |
1054 if hasattr(typing, 'Text'): | |
1055 Text = typing.Text | |
1056 else: | |
1057 Text = str | |
1058 | |
1059 | |
1060 if hasattr(typing, 'TYPE_CHECKING'): | |
1061 TYPE_CHECKING = typing.TYPE_CHECKING | |
1062 else: | |
1063 # Constant that's True when type checking, but False here. | |
1064 TYPE_CHECKING = False | |
1065 | |
1066 | |
1067 def _gorg(cls): | |
1068 """This function exists for compatibility with old typing versions.""" | |
1069 assert isinstance(cls, GenericMeta) | |
1070 if hasattr(cls, '_gorg'): | |
1071 return cls._gorg | |
1072 while cls.__origin__ is not None: | |
1073 cls = cls.__origin__ | |
1074 return cls | |
1075 | |
1076 | |
1077 if OLD_GENERICS: | |
1078 def _next_in_mro(cls): # noqa | |
1079 """This function exists for compatibility with old typing versions.""" | |
1080 next_in_mro = object | |
1081 for i, c in enumerate(cls.__mro__[:-1]): | |
1082 if isinstance(c, GenericMeta) and _gorg(c) is Generic: | |
1083 next_in_mro = cls.__mro__[i + 1] | |
1084 return next_in_mro | |
1085 | |
1086 | |
1087 _PROTO_WHITELIST = ['Callable', 'Awaitable', | |
1088 'Iterable', 'Iterator', 'AsyncIterable', 'AsyncIterator', | |
1089 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible', | |
1090 'ContextManager', 'AsyncContextManager'] | |
1091 | |
1092 | |
1093 def _get_protocol_attrs(cls): | |
1094 attrs = set() | |
1095 for base in cls.__mro__[:-1]: # without object | |
1096 if base.__name__ in ('Protocol', 'Generic'): | |
1097 continue | |
1098 annotations = getattr(base, '__annotations__', {}) | |
1099 for attr in list(base.__dict__.keys()) + list(annotations.keys()): | |
1100 if (not attr.startswith('_abc_') and attr not in ( | |
1101 '__abstractmethods__', '__annotations__', '__weakref__', | |
1102 '_is_protocol', '_is_runtime_protocol', '__dict__', | |
1103 '__args__', '__slots__', | |
1104 '__next_in_mro__', '__parameters__', '__origin__', | |
1105 '__orig_bases__', '__extra__', '__tree_hash__', | |
1106 '__doc__', '__subclasshook__', '__init__', '__new__', | |
1107 '__module__', '_MutableMapping__marker', '_gorg')): | |
1108 attrs.add(attr) | |
1109 return attrs | |
1110 | |
1111 | |
1112 def _is_callable_members_only(cls): | |
1113 return all(callable(getattr(cls, attr, None)) for attr in _get_protocol_attrs(cls)) | |
1114 | |
1115 | |
1116 if hasattr(typing, 'Protocol'): | |
1117 Protocol = typing.Protocol | |
1118 elif HAVE_PROTOCOLS and not PEP_560: | |
1119 class _ProtocolMeta(GenericMeta): | |
1120 """Internal metaclass for Protocol. | |
1121 | |
1122 This exists so Protocol classes can be generic without deriving | |
1123 from Generic. | |
1124 """ | |
1125 if not OLD_GENERICS: | |
1126 def __new__(cls, name, bases, namespace, | |
1127 tvars=None, args=None, origin=None, extra=None, orig_bases=None): | |
1128 # This is just a version copied from GenericMeta.__new__ that | |
1129 # includes "Protocol" special treatment. (Comments removed for brevity.) | |
1130 assert extra is None # Protocols should not have extra | |
1131 if tvars is not None: | |
1132 assert origin is not None | |
1133 assert all(isinstance(t, TypeVar) for t in tvars), tvars | |
1134 else: | |
1135 tvars = _type_vars(bases) | |
1136 gvars = None | |
1137 for base in bases: | |
1138 if base is Generic: | |
1139 raise TypeError("Cannot inherit from plain Generic") | |
1140 if (isinstance(base, GenericMeta) and | |
1141 base.__origin__ in (Generic, Protocol)): | |
1142 if gvars is not None: | |
1143 raise TypeError( | |
1144 "Cannot inherit from Generic[...] or" | |
1145 " Protocol[...] multiple times.") | |
1146 gvars = base.__parameters__ | |
1147 if gvars is None: | |
1148 gvars = tvars | |
1149 else: | |
1150 tvarset = set(tvars) | |
1151 gvarset = set(gvars) | |
1152 if not tvarset <= gvarset: | |
1153 raise TypeError( | |
1154 "Some type variables (%s) " | |
1155 "are not listed in %s[%s]" % | |
1156 (", ".join(str(t) for t in tvars if t not in gvarset), | |
1157 "Generic" if any(b.__origin__ is Generic | |
1158 for b in bases) else "Protocol", | |
1159 ", ".join(str(g) for g in gvars))) | |
1160 tvars = gvars | |
1161 | |
1162 initial_bases = bases | |
1163 if (extra is not None and type(extra) is abc.ABCMeta and | |
1164 extra not in bases): | |
1165 bases = (extra,) + bases | |
1166 bases = tuple(_gorg(b) if isinstance(b, GenericMeta) else b | |
1167 for b in bases) | |
1168 if any(isinstance(b, GenericMeta) and b is not Generic for b in bases): | |
1169 bases = tuple(b for b in bases if b is not Generic) | |
1170 namespace.update({'__origin__': origin, '__extra__': extra}) | |
1171 self = super(GenericMeta, cls).__new__(cls, name, bases, namespace, | |
1172 _root=True) | |
1173 super(GenericMeta, self).__setattr__('_gorg', | |
1174 self if not origin else | |
1175 _gorg(origin)) | |
1176 self.__parameters__ = tvars | |
1177 self.__args__ = tuple(... if a is _TypingEllipsis else | |
1178 () if a is _TypingEmpty else | |
1179 a for a in args) if args else None | |
1180 self.__next_in_mro__ = _next_in_mro(self) | |
1181 if orig_bases is None: | |
1182 self.__orig_bases__ = initial_bases | |
1183 elif origin is not None: | |
1184 self._abc_registry = origin._abc_registry | |
1185 self._abc_cache = origin._abc_cache | |
1186 if hasattr(self, '_subs_tree'): | |
1187 self.__tree_hash__ = (hash(self._subs_tree()) if origin else | |
1188 super(GenericMeta, self).__hash__()) | |
1189 return self | |
1190 | |
1191 def __init__(cls, *args, **kwargs): | |
1192 super().__init__(*args, **kwargs) | |
1193 if not cls.__dict__.get('_is_protocol', None): | |
1194 cls._is_protocol = any(b is Protocol or | |
1195 isinstance(b, _ProtocolMeta) and | |
1196 b.__origin__ is Protocol | |
1197 for b in cls.__bases__) | |
1198 if cls._is_protocol: | |
1199 for base in cls.__mro__[1:]: | |
1200 if not (base in (object, Generic) or | |
1201 base.__module__ == 'collections.abc' and | |
1202 base.__name__ in _PROTO_WHITELIST or | |
1203 isinstance(base, TypingMeta) and base._is_protocol or | |
1204 isinstance(base, GenericMeta) and | |
1205 base.__origin__ is Generic): | |
1206 raise TypeError('Protocols can only inherit from other' | |
1207 ' protocols, got %r' % base) | |
1208 | |
1209 def _no_init(self, *args, **kwargs): | |
1210 if type(self)._is_protocol: | |
1211 raise TypeError('Protocols cannot be instantiated') | |
1212 cls.__init__ = _no_init | |
1213 | |
1214 def _proto_hook(other): | |
1215 if not cls.__dict__.get('_is_protocol', None): | |
1216 return NotImplemented | |
1217 if not isinstance(other, type): | |
1218 # Same error as for issubclass(1, int) | |
1219 raise TypeError('issubclass() arg 1 must be a class') | |
1220 for attr in _get_protocol_attrs(cls): | |
1221 for base in other.__mro__: | |
1222 if attr in base.__dict__: | |
1223 if base.__dict__[attr] is None: | |
1224 return NotImplemented | |
1225 break | |
1226 annotations = getattr(base, '__annotations__', {}) | |
1227 if (isinstance(annotations, typing.Mapping) and | |
1228 attr in annotations and | |
1229 isinstance(other, _ProtocolMeta) and | |
1230 other._is_protocol): | |
1231 break | |
1232 else: | |
1233 return NotImplemented | |
1234 return True | |
1235 if '__subclasshook__' not in cls.__dict__: | |
1236 cls.__subclasshook__ = _proto_hook | |
1237 | |
1238 def __instancecheck__(self, instance): | |
1239 # We need this method for situations where attributes are | |
1240 # assigned in __init__. | |
1241 if ((not getattr(self, '_is_protocol', False) or | |
1242 _is_callable_members_only(self)) and | |
1243 issubclass(instance.__class__, self)): | |
1244 return True | |
1245 if self._is_protocol: | |
1246 if all(hasattr(instance, attr) and | |
1247 (not callable(getattr(self, attr, None)) or | |
1248 getattr(instance, attr) is not None) | |
1249 for attr in _get_protocol_attrs(self)): | |
1250 return True | |
1251 return super(GenericMeta, self).__instancecheck__(instance) | |
1252 | |
1253 def __subclasscheck__(self, cls): | |
1254 if self.__origin__ is not None: | |
1255 if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools']: | |
1256 raise TypeError("Parameterized generics cannot be used with class " | |
1257 "or instance checks") | |
1258 return False | |
1259 if (self.__dict__.get('_is_protocol', None) and | |
1260 not self.__dict__.get('_is_runtime_protocol', None)): | |
1261 if sys._getframe(1).f_globals['__name__'] in ['abc', | |
1262 'functools', | |
1263 'typing']: | |
1264 return False | |
1265 raise TypeError("Instance and class checks can only be used with" | |
1266 " @runtime protocols") | |
1267 if (self.__dict__.get('_is_runtime_protocol', None) and | |
1268 not _is_callable_members_only(self)): | |
1269 if sys._getframe(1).f_globals['__name__'] in ['abc', | |
1270 'functools', | |
1271 'typing']: | |
1272 return super(GenericMeta, self).__subclasscheck__(cls) | |
1273 raise TypeError("Protocols with non-method members" | |
1274 " don't support issubclass()") | |
1275 return super(GenericMeta, self).__subclasscheck__(cls) | |
1276 | |
1277 if not OLD_GENERICS: | |
1278 @_tp_cache | |
1279 def __getitem__(self, params): | |
1280 # We also need to copy this from GenericMeta.__getitem__ to get | |
1281 # special treatment of "Protocol". (Comments removed for brevity.) | |
1282 if not isinstance(params, tuple): | |
1283 params = (params,) | |
1284 if not params and _gorg(self) is not Tuple: | |
1285 raise TypeError( | |
1286 "Parameter list to %s[...] cannot be empty" % self.__qualname__) | |
1287 msg = "Parameters to generic types must be types." | |
1288 params = tuple(_type_check(p, msg) for p in params) | |
1289 if self in (Generic, Protocol): | |
1290 if not all(isinstance(p, TypeVar) for p in params): | |
1291 raise TypeError( | |
1292 "Parameters to %r[...] must all be type variables" % self) | |
1293 if len(set(params)) != len(params): | |
1294 raise TypeError( | |
1295 "Parameters to %r[...] must all be unique" % self) | |
1296 tvars = params | |
1297 args = params | |
1298 elif self in (Tuple, Callable): | |
1299 tvars = _type_vars(params) | |
1300 args = params | |
1301 elif self.__origin__ in (Generic, Protocol): | |
1302 raise TypeError("Cannot subscript already-subscripted %s" % | |
1303 repr(self)) | |
1304 else: | |
1305 _check_generic(self, params) | |
1306 tvars = _type_vars(params) | |
1307 args = params | |
1308 | |
1309 prepend = (self,) if self.__origin__ is None else () | |
1310 return self.__class__(self.__name__, | |
1311 prepend + self.__bases__, | |
1312 _no_slots_copy(self.__dict__), | |
1313 tvars=tvars, | |
1314 args=args, | |
1315 origin=self, | |
1316 extra=self.__extra__, | |
1317 orig_bases=self.__orig_bases__) | |
1318 | |
1319 class Protocol(metaclass=_ProtocolMeta): | |
1320 """Base class for protocol classes. Protocol classes are defined as:: | |
1321 | |
1322 class Proto(Protocol): | |
1323 def meth(self) -> int: | |
1324 ... | |
1325 | |
1326 Such classes are primarily used with static type checkers that recognize | |
1327 structural subtyping (static duck-typing), for example:: | |
1328 | |
1329 class C: | |
1330 def meth(self) -> int: | |
1331 return 0 | |
1332 | |
1333 def func(x: Proto) -> int: | |
1334 return x.meth() | |
1335 | |
1336 func(C()) # Passes static type check | |
1337 | |
1338 See PEP 544 for details. Protocol classes decorated with | |
1339 @typing_extensions.runtime act as simple-minded runtime protocol that checks | |
1340 only the presence of given attributes, ignoring their type signatures. | |
1341 | |
1342 Protocol classes can be generic, they are defined as:: | |
1343 | |
1344 class GenProto({bases}): | |
1345 def meth(self) -> T: | |
1346 ... | |
1347 """ | |
1348 __slots__ = () | |
1349 _is_protocol = True | |
1350 | |
1351 def __new__(cls, *args, **kwds): | |
1352 if _gorg(cls) is Protocol: | |
1353 raise TypeError("Type Protocol cannot be instantiated; " | |
1354 "it can be used only as a base class") | |
1355 if OLD_GENERICS: | |
1356 return _generic_new(_next_in_mro(cls), cls, *args, **kwds) | |
1357 return _generic_new(cls.__next_in_mro__, cls, *args, **kwds) | |
1358 if Protocol.__doc__ is not None: | |
1359 Protocol.__doc__ = Protocol.__doc__.format(bases="Protocol, Generic[T]" if | |
1360 OLD_GENERICS else "Protocol[T]") | |
1361 | |
1362 | |
1363 elif PEP_560: | |
1364 from typing import _type_check, _GenericAlias, _collect_type_vars # noqa | |
1365 | |
1366 class _ProtocolMeta(abc.ABCMeta): | |
1367 # This metaclass is a bit unfortunate and exists only because of the lack | |
1368 # of __instancehook__. | |
1369 def __instancecheck__(cls, instance): | |
1370 # We need this method for situations where attributes are | |
1371 # assigned in __init__. | |
1372 if ((not getattr(cls, '_is_protocol', False) or | |
1373 _is_callable_members_only(cls)) and | |
1374 issubclass(instance.__class__, cls)): | |
1375 return True | |
1376 if cls._is_protocol: | |
1377 if all(hasattr(instance, attr) and | |
1378 (not callable(getattr(cls, attr, None)) or | |
1379 getattr(instance, attr) is not None) | |
1380 for attr in _get_protocol_attrs(cls)): | |
1381 return True | |
1382 return super().__instancecheck__(instance) | |
1383 | |
1384 class Protocol(metaclass=_ProtocolMeta): | |
1385 # There is quite a lot of overlapping code with typing.Generic. | |
1386 # Unfortunately it is hard to avoid this while these live in two different | |
1387 # modules. The duplicated code will be removed when Protocol is moved to typing. | |
1388 """Base class for protocol classes. Protocol classes are defined as:: | |
1389 | |
1390 class Proto(Protocol): | |
1391 def meth(self) -> int: | |
1392 ... | |
1393 | |
1394 Such classes are primarily used with static type checkers that recognize | |
1395 structural subtyping (static duck-typing), for example:: | |
1396 | |
1397 class C: | |
1398 def meth(self) -> int: | |
1399 return 0 | |
1400 | |
1401 def func(x: Proto) -> int: | |
1402 return x.meth() | |
1403 | |
1404 func(C()) # Passes static type check | |
1405 | |
1406 See PEP 544 for details. Protocol classes decorated with | |
1407 @typing_extensions.runtime act as simple-minded runtime protocol that checks | |
1408 only the presence of given attributes, ignoring their type signatures. | |
1409 | |
1410 Protocol classes can be generic, they are defined as:: | |
1411 | |
1412 class GenProto(Protocol[T]): | |
1413 def meth(self) -> T: | |
1414 ... | |
1415 """ | |
1416 __slots__ = () | |
1417 _is_protocol = True | |
1418 | |
1419 def __new__(cls, *args, **kwds): | |
1420 if cls is Protocol: | |
1421 raise TypeError("Type Protocol cannot be instantiated; " | |
1422 "it can only be used as a base class") | |
1423 return super().__new__(cls) | |
1424 | |
1425 @_tp_cache | |
1426 def __class_getitem__(cls, params): | |
1427 if not isinstance(params, tuple): | |
1428 params = (params,) | |
1429 if not params and cls is not Tuple: | |
1430 raise TypeError( | |
1431 "Parameter list to {}[...] cannot be empty".format(cls.__qualname__)) | |
1432 msg = "Parameters to generic types must be types." | |
1433 params = tuple(_type_check(p, msg) for p in params) | |
1434 if cls is Protocol: | |
1435 # Generic can only be subscripted with unique type variables. | |
1436 if not all(isinstance(p, TypeVar) for p in params): | |
1437 i = 0 | |
1438 while isinstance(params[i], TypeVar): | |
1439 i += 1 | |
1440 raise TypeError( | |
1441 "Parameters to Protocol[...] must all be type variables." | |
1442 " Parameter {} is {}".format(i + 1, params[i])) | |
1443 if len(set(params)) != len(params): | |
1444 raise TypeError( | |
1445 "Parameters to Protocol[...] must all be unique") | |
1446 else: | |
1447 # Subscripting a regular Generic subclass. | |
1448 _check_generic(cls, params) | |
1449 return _GenericAlias(cls, params) | |
1450 | |
1451 def __init_subclass__(cls, *args, **kwargs): | |
1452 tvars = [] | |
1453 if '__orig_bases__' in cls.__dict__: | |
1454 error = Generic in cls.__orig_bases__ | |
1455 else: | |
1456 error = Generic in cls.__bases__ | |
1457 if error: | |
1458 raise TypeError("Cannot inherit from plain Generic") | |
1459 if '__orig_bases__' in cls.__dict__: | |
1460 tvars = _collect_type_vars(cls.__orig_bases__) | |
1461 # Look for Generic[T1, ..., Tn] or Protocol[T1, ..., Tn]. | |
1462 # If found, tvars must be a subset of it. | |
1463 # If not found, tvars is it. | |
1464 # Also check for and reject plain Generic, | |
1465 # and reject multiple Generic[...] and/or Protocol[...]. | |
1466 gvars = None | |
1467 for base in cls.__orig_bases__: | |
1468 if (isinstance(base, _GenericAlias) and | |
1469 base.__origin__ in (Generic, Protocol)): | |
1470 # for error messages | |
1471 the_base = 'Generic' if base.__origin__ is Generic else 'Protocol' | |
1472 if gvars is not None: | |
1473 raise TypeError( | |
1474 "Cannot inherit from Generic[...]" | |
1475 " and/or Protocol[...] multiple types.") | |
1476 gvars = base.__parameters__ | |
1477 if gvars is None: | |
1478 gvars = tvars | |
1479 else: | |
1480 tvarset = set(tvars) | |
1481 gvarset = set(gvars) | |
1482 if not tvarset <= gvarset: | |
1483 s_vars = ', '.join(str(t) for t in tvars if t not in gvarset) | |
1484 s_args = ', '.join(str(g) for g in gvars) | |
1485 raise TypeError("Some type variables ({}) are" | |
1486 " not listed in {}[{}]".format(s_vars, | |
1487 the_base, s_args)) | |
1488 tvars = gvars | |
1489 cls.__parameters__ = tuple(tvars) | |
1490 | |
1491 # Determine if this is a protocol or a concrete subclass. | |
1492 if not cls.__dict__.get('_is_protocol', None): | |
1493 cls._is_protocol = any(b is Protocol for b in cls.__bases__) | |
1494 | |
1495 # Set (or override) the protocol subclass hook. | |
1496 def _proto_hook(other): | |
1497 if not cls.__dict__.get('_is_protocol', None): | |
1498 return NotImplemented | |
1499 if not getattr(cls, '_is_runtime_protocol', False): | |
1500 if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']: | |
1501 return NotImplemented | |
1502 raise TypeError("Instance and class checks can only be used with" | |
1503 " @runtime protocols") | |
1504 if not _is_callable_members_only(cls): | |
1505 if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']: | |
1506 return NotImplemented | |
1507 raise TypeError("Protocols with non-method members" | |
1508 " don't support issubclass()") | |
1509 if not isinstance(other, type): | |
1510 # Same error as for issubclass(1, int) | |
1511 raise TypeError('issubclass() arg 1 must be a class') | |
1512 for attr in _get_protocol_attrs(cls): | |
1513 for base in other.__mro__: | |
1514 if attr in base.__dict__: | |
1515 if base.__dict__[attr] is None: | |
1516 return NotImplemented | |
1517 break | |
1518 annotations = getattr(base, '__annotations__', {}) | |
1519 if (isinstance(annotations, typing.Mapping) and | |
1520 attr in annotations and | |
1521 isinstance(other, _ProtocolMeta) and | |
1522 other._is_protocol): | |
1523 break | |
1524 else: | |
1525 return NotImplemented | |
1526 return True | |
1527 if '__subclasshook__' not in cls.__dict__: | |
1528 cls.__subclasshook__ = _proto_hook | |
1529 | |
1530 # We have nothing more to do for non-protocols. | |
1531 if not cls._is_protocol: | |
1532 return | |
1533 | |
1534 # Check consistency of bases. | |
1535 for base in cls.__bases__: | |
1536 if not (base in (object, Generic) or | |
1537 base.__module__ == 'collections.abc' and | |
1538 base.__name__ in _PROTO_WHITELIST or | |
1539 isinstance(base, _ProtocolMeta) and base._is_protocol): | |
1540 raise TypeError('Protocols can only inherit from other' | |
1541 ' protocols, got %r' % base) | |
1542 | |
1543 def _no_init(self, *args, **kwargs): | |
1544 if type(self)._is_protocol: | |
1545 raise TypeError('Protocols cannot be instantiated') | |
1546 cls.__init__ = _no_init | |
1547 | |
1548 | |
1549 if hasattr(typing, 'runtime_checkable'): | |
1550 runtime_checkable = typing.runtime_checkable | |
1551 elif HAVE_PROTOCOLS: | |
1552 def runtime_checkable(cls): | |
1553 """Mark a protocol class as a runtime protocol, so that it | |
1554 can be used with isinstance() and issubclass(). Raise TypeError | |
1555 if applied to a non-protocol class. | |
1556 | |
1557 This allows a simple-minded structural check very similar to the | |
1558 one-offs in collections.abc such as Hashable. | |
1559 """ | |
1560 if not isinstance(cls, _ProtocolMeta) or not cls._is_protocol: | |
1561 raise TypeError('@runtime_checkable can be only applied to protocol classes,' | |
1562 ' got %r' % cls) | |
1563 cls._is_runtime_protocol = True | |
1564 return cls | |
1565 | |
1566 | |
1567 if HAVE_PROTOCOLS: | |
1568 # Exists for backwards compatibility. | |
1569 runtime = runtime_checkable | |
1570 | |
1571 | |
1572 if sys.version_info[:2] >= (3, 9): | |
1573 # The standard library TypedDict in Python 3.8 does not store runtime information | |
1574 # about which (if any) keys are optional. See https://bugs.python.org/issue38834 | |
1575 TypedDict = typing.TypedDict | |
1576 else: | |
1577 def _check_fails(cls, other): | |
1578 try: | |
1579 if sys._getframe(1).f_globals['__name__'] not in ['abc', | |
1580 'functools', | |
1581 'typing']: | |
1582 # Typed dicts are only for static structural subtyping. | |
1583 raise TypeError('TypedDict does not support instance and class checks') | |
1584 except (AttributeError, ValueError): | |
1585 pass | |
1586 return False | |
1587 | |
1588 def _dict_new(*args, **kwargs): | |
1589 if not args: | |
1590 raise TypeError('TypedDict.__new__(): not enough arguments') | |
1591 _, args = args[0], args[1:] # allow the "cls" keyword be passed | |
1592 return dict(*args, **kwargs) | |
1593 | |
1594 _dict_new.__text_signature__ = '($cls, _typename, _fields=None, /, **kwargs)' | |
1595 | |
1596 def _typeddict_new(*args, total=True, **kwargs): | |
1597 if not args: | |
1598 raise TypeError('TypedDict.__new__(): not enough arguments') | |
1599 _, args = args[0], args[1:] # allow the "cls" keyword be passed | |
1600 if args: | |
1601 typename, args = args[0], args[1:] # allow the "_typename" keyword be passed | |
1602 elif '_typename' in kwargs: | |
1603 typename = kwargs.pop('_typename') | |
1604 import warnings | |
1605 warnings.warn("Passing '_typename' as keyword argument is deprecated", | |
1606 DeprecationWarning, stacklevel=2) | |
1607 else: | |
1608 raise TypeError("TypedDict.__new__() missing 1 required positional " | |
1609 "argument: '_typename'") | |
1610 if args: | |
1611 try: | |
1612 fields, = args # allow the "_fields" keyword be passed | |
1613 except ValueError: | |
1614 raise TypeError('TypedDict.__new__() takes from 2 to 3 ' | |
1615 'positional arguments but {} ' | |
1616 'were given'.format(len(args) + 2)) | |
1617 elif '_fields' in kwargs and len(kwargs) == 1: | |
1618 fields = kwargs.pop('_fields') | |
1619 import warnings | |
1620 warnings.warn("Passing '_fields' as keyword argument is deprecated", | |
1621 DeprecationWarning, stacklevel=2) | |
1622 else: | |
1623 fields = None | |
1624 | |
1625 if fields is None: | |
1626 fields = kwargs | |
1627 elif kwargs: | |
1628 raise TypeError("TypedDict takes either a dict or keyword arguments," | |
1629 " but not both") | |
1630 | |
1631 ns = {'__annotations__': dict(fields), '__total__': total} | |
1632 try: | |
1633 # Setting correct module is necessary to make typed dict classes pickleable. | |
1634 ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__') | |
1635 except (AttributeError, ValueError): | |
1636 pass | |
1637 | |
1638 return _TypedDictMeta(typename, (), ns) | |
1639 | |
1640 _typeddict_new.__text_signature__ = ('($cls, _typename, _fields=None,' | |
1641 ' /, *, total=True, **kwargs)') | |
1642 | |
1643 class _TypedDictMeta(type): | |
1644 def __new__(cls, name, bases, ns, total=True): | |
1645 # Create new typed dict class object. | |
1646 # This method is called directly when TypedDict is subclassed, | |
1647 # or via _typeddict_new when TypedDict is instantiated. This way | |
1648 # TypedDict supports all three syntaxes described in its docstring. | |
1649 # Subclasses and instances of TypedDict return actual dictionaries | |
1650 # via _dict_new. | |
1651 ns['__new__'] = _typeddict_new if name == 'TypedDict' else _dict_new | |
1652 tp_dict = super(_TypedDictMeta, cls).__new__(cls, name, (dict,), ns) | |
1653 | |
1654 annotations = {} | |
1655 own_annotations = ns.get('__annotations__', {}) | |
1656 own_annotation_keys = set(own_annotations.keys()) | |
1657 msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type" | |
1658 own_annotations = { | |
1659 n: typing._type_check(tp, msg) for n, tp in own_annotations.items() | |
1660 } | |
1661 required_keys = set() | |
1662 optional_keys = set() | |
1663 | |
1664 for base in bases: | |
1665 annotations.update(base.__dict__.get('__annotations__', {})) | |
1666 required_keys.update(base.__dict__.get('__required_keys__', ())) | |
1667 optional_keys.update(base.__dict__.get('__optional_keys__', ())) | |
1668 | |
1669 annotations.update(own_annotations) | |
1670 if total: | |
1671 required_keys.update(own_annotation_keys) | |
1672 else: | |
1673 optional_keys.update(own_annotation_keys) | |
1674 | |
1675 tp_dict.__annotations__ = annotations | |
1676 tp_dict.__required_keys__ = frozenset(required_keys) | |
1677 tp_dict.__optional_keys__ = frozenset(optional_keys) | |
1678 if not hasattr(tp_dict, '__total__'): | |
1679 tp_dict.__total__ = total | |
1680 return tp_dict | |
1681 | |
1682 __instancecheck__ = __subclasscheck__ = _check_fails | |
1683 | |
1684 TypedDict = _TypedDictMeta('TypedDict', (dict,), {}) | |
1685 TypedDict.__module__ = __name__ | |
1686 TypedDict.__doc__ = \ | |
1687 """A simple typed name space. At runtime it is equivalent to a plain dict. | |
1688 | |
1689 TypedDict creates a dictionary type that expects all of its | |
1690 instances to have a certain set of keys, with each key | |
1691 associated with a value of a consistent type. This expectation | |
1692 is not checked at runtime but is only enforced by type checkers. | |
1693 Usage:: | |
1694 | |
1695 class Point2D(TypedDict): | |
1696 x: int | |
1697 y: int | |
1698 label: str | |
1699 | |
1700 a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK | |
1701 b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check | |
1702 | |
1703 assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first') | |
1704 | |
1705 The type info can be accessed via the Point2D.__annotations__ dict, and | |
1706 the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets. | |
1707 TypedDict supports two additional equivalent forms:: | |
1708 | |
1709 Point2D = TypedDict('Point2D', x=int, y=int, label=str) | |
1710 Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) | |
1711 | |
1712 The class syntax is only supported in Python 3.6+, while two other | |
1713 syntax forms work for Python 2.7 and 3.2+ | |
1714 """ | |
1715 | |
1716 | |
1717 # Python 3.9+ has PEP 593 (Annotated and modified get_type_hints) | |
1718 if hasattr(typing, 'Annotated'): | |
1719 Annotated = typing.Annotated | |
1720 get_type_hints = typing.get_type_hints | |
1721 # Not exported and not a public API, but needed for get_origin() and get_args() | |
1722 # to work. | |
1723 _AnnotatedAlias = typing._AnnotatedAlias | |
1724 elif PEP_560: | |
1725 class _AnnotatedAlias(typing._GenericAlias, _root=True): | |
1726 """Runtime representation of an annotated type. | |
1727 | |
1728 At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't' | |
1729 with extra annotations. The alias behaves like a normal typing alias, | |
1730 instantiating is the same as instantiating the underlying type, binding | |
1731 it to types is also the same. | |
1732 """ | |
1733 def __init__(self, origin, metadata): | |
1734 if isinstance(origin, _AnnotatedAlias): | |
1735 metadata = origin.__metadata__ + metadata | |
1736 origin = origin.__origin__ | |
1737 super().__init__(origin, origin) | |
1738 self.__metadata__ = metadata | |
1739 | |
1740 def copy_with(self, params): | |
1741 assert len(params) == 1 | |
1742 new_type = params[0] | |
1743 return _AnnotatedAlias(new_type, self.__metadata__) | |
1744 | |
1745 def __repr__(self): | |
1746 return "typing_extensions.Annotated[{}, {}]".format( | |
1747 typing._type_repr(self.__origin__), | |
1748 ", ".join(repr(a) for a in self.__metadata__) | |
1749 ) | |
1750 | |
1751 def __reduce__(self): | |
1752 return operator.getitem, ( | |
1753 Annotated, (self.__origin__,) + self.__metadata__ | |
1754 ) | |
1755 | |
1756 def __eq__(self, other): | |
1757 if not isinstance(other, _AnnotatedAlias): | |
1758 return NotImplemented | |
1759 if self.__origin__ != other.__origin__: | |
1760 return False | |
1761 return self.__metadata__ == other.__metadata__ | |
1762 | |
1763 def __hash__(self): | |
1764 return hash((self.__origin__, self.__metadata__)) | |
1765 | |
1766 class Annotated: | |
1767 """Add context specific metadata to a type. | |
1768 | |
1769 Example: Annotated[int, runtime_check.Unsigned] indicates to the | |
1770 hypothetical runtime_check module that this type is an unsigned int. | |
1771 Every other consumer of this type can ignore this metadata and treat | |
1772 this type as int. | |
1773 | |
1774 The first argument to Annotated must be a valid type (and will be in | |
1775 the __origin__ field), the remaining arguments are kept as a tuple in | |
1776 the __extra__ field. | |
1777 | |
1778 Details: | |
1779 | |
1780 - It's an error to call `Annotated` with less than two arguments. | |
1781 - Nested Annotated are flattened:: | |
1782 | |
1783 Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3] | |
1784 | |
1785 - Instantiating an annotated type is equivalent to instantiating the | |
1786 underlying type:: | |
1787 | |
1788 Annotated[C, Ann1](5) == C(5) | |
1789 | |
1790 - Annotated can be used as a generic type alias:: | |
1791 | |
1792 Optimized = Annotated[T, runtime.Optimize()] | |
1793 Optimized[int] == Annotated[int, runtime.Optimize()] | |
1794 | |
1795 OptimizedList = Annotated[List[T], runtime.Optimize()] | |
1796 OptimizedList[int] == Annotated[List[int], runtime.Optimize()] | |
1797 """ | |
1798 | |
1799 __slots__ = () | |
1800 | |
1801 def __new__(cls, *args, **kwargs): | |
1802 raise TypeError("Type Annotated cannot be instantiated.") | |
1803 | |
1804 @_tp_cache | |
1805 def __class_getitem__(cls, params): | |
1806 if not isinstance(params, tuple) or len(params) < 2: | |
1807 raise TypeError("Annotated[...] should be used " | |
1808 "with at least two arguments (a type and an " | |
1809 "annotation).") | |
1810 msg = "Annotated[t, ...]: t must be a type." | |
1811 origin = typing._type_check(params[0], msg) | |
1812 metadata = tuple(params[1:]) | |
1813 return _AnnotatedAlias(origin, metadata) | |
1814 | |
1815 def __init_subclass__(cls, *args, **kwargs): | |
1816 raise TypeError( | |
1817 "Cannot subclass {}.Annotated".format(cls.__module__) | |
1818 ) | |
1819 | |
1820 def _strip_annotations(t): | |
1821 """Strips the annotations from a given type. | |
1822 """ | |
1823 if isinstance(t, _AnnotatedAlias): | |
1824 return _strip_annotations(t.__origin__) | |
1825 if isinstance(t, typing._GenericAlias): | |
1826 stripped_args = tuple(_strip_annotations(a) for a in t.__args__) | |
1827 if stripped_args == t.__args__: | |
1828 return t | |
1829 res = t.copy_with(stripped_args) | |
1830 res._special = t._special | |
1831 return res | |
1832 return t | |
1833 | |
1834 def get_type_hints(obj, globalns=None, localns=None, include_extras=False): | |
1835 """Return type hints for an object. | |
1836 | |
1837 This is often the same as obj.__annotations__, but it handles | |
1838 forward references encoded as string literals, adds Optional[t] if a | |
1839 default value equal to None is set and recursively replaces all | |
1840 'Annotated[T, ...]' with 'T' (unless 'include_extras=True'). | |
1841 | |
1842 The argument may be a module, class, method, or function. The annotations | |
1843 are returned as a dictionary. For classes, annotations include also | |
1844 inherited members. | |
1845 | |
1846 TypeError is raised if the argument is not of a type that can contain | |
1847 annotations, and an empty dictionary is returned if no annotations are | |
1848 present. | |
1849 | |
1850 BEWARE -- the behavior of globalns and localns is counterintuitive | |
1851 (unless you are familiar with how eval() and exec() work). The | |
1852 search order is locals first, then globals. | |
1853 | |
1854 - If no dict arguments are passed, an attempt is made to use the | |
1855 globals from obj (or the respective module's globals for classes), | |
1856 and these are also used as the locals. If the object does not appear | |
1857 to have globals, an empty dictionary is used. | |
1858 | |
1859 - If one dict argument is passed, it is used for both globals and | |
1860 locals. | |
1861 | |
1862 - If two dict arguments are passed, they specify globals and | |
1863 locals, respectively. | |
1864 """ | |
1865 hint = typing.get_type_hints(obj, globalns=globalns, localns=localns) | |
1866 if include_extras: | |
1867 return hint | |
1868 return {k: _strip_annotations(t) for k, t in hint.items()} | |
1869 | |
1870 elif HAVE_ANNOTATED: | |
1871 | |
1872 def _is_dunder(name): | |
1873 """Returns True if name is a __dunder_variable_name__.""" | |
1874 return len(name) > 4 and name.startswith('__') and name.endswith('__') | |
1875 | |
1876 # Prior to Python 3.7 types did not have `copy_with`. A lot of the equality | |
1877 # checks, argument expansion etc. are done on the _subs_tre. As a result we | |
1878 # can't provide a get_type_hints function that strips out annotations. | |
1879 | |
1880 class AnnotatedMeta(typing.GenericMeta): | |
1881 """Metaclass for Annotated""" | |
1882 | |
1883 def __new__(cls, name, bases, namespace, **kwargs): | |
1884 if any(b is not object for b in bases): | |
1885 raise TypeError("Cannot subclass " + str(Annotated)) | |
1886 return super().__new__(cls, name, bases, namespace, **kwargs) | |
1887 | |
1888 @property | |
1889 def __metadata__(self): | |
1890 return self._subs_tree()[2] | |
1891 | |
1892 def _tree_repr(self, tree): | |
1893 cls, origin, metadata = tree | |
1894 if not isinstance(origin, tuple): | |
1895 tp_repr = typing._type_repr(origin) | |
1896 else: | |
1897 tp_repr = origin[0]._tree_repr(origin) | |
1898 metadata_reprs = ", ".join(repr(arg) for arg in metadata) | |
1899 return '%s[%s, %s]' % (cls, tp_repr, metadata_reprs) | |
1900 | |
1901 def _subs_tree(self, tvars=None, args=None): # noqa | |
1902 if self is Annotated: | |
1903 return Annotated | |
1904 res = super()._subs_tree(tvars=tvars, args=args) | |
1905 # Flatten nested Annotated | |
1906 if isinstance(res[1], tuple) and res[1][0] is Annotated: | |
1907 sub_tp = res[1][1] | |
1908 sub_annot = res[1][2] | |
1909 return (Annotated, sub_tp, sub_annot + res[2]) | |
1910 return res | |
1911 | |
1912 def _get_cons(self): | |
1913 """Return the class used to create instance of this type.""" | |
1914 if self.__origin__ is None: | |
1915 raise TypeError("Cannot get the underlying type of a " | |
1916 "non-specialized Annotated type.") | |
1917 tree = self._subs_tree() | |
1918 while isinstance(tree, tuple) and tree[0] is Annotated: | |
1919 tree = tree[1] | |
1920 if isinstance(tree, tuple): | |
1921 return tree[0] | |
1922 else: | |
1923 return tree | |
1924 | |
1925 @_tp_cache | |
1926 def __getitem__(self, params): | |
1927 if not isinstance(params, tuple): | |
1928 params = (params,) | |
1929 if self.__origin__ is not None: # specializing an instantiated type | |
1930 return super().__getitem__(params) | |
1931 elif not isinstance(params, tuple) or len(params) < 2: | |
1932 raise TypeError("Annotated[...] should be instantiated " | |
1933 "with at least two arguments (a type and an " | |
1934 "annotation).") | |
1935 else: | |
1936 msg = "Annotated[t, ...]: t must be a type." | |
1937 tp = typing._type_check(params[0], msg) | |
1938 metadata = tuple(params[1:]) | |
1939 return self.__class__( | |
1940 self.__name__, | |
1941 self.__bases__, | |
1942 _no_slots_copy(self.__dict__), | |
1943 tvars=_type_vars((tp,)), | |
1944 # Metadata is a tuple so it won't be touched by _replace_args et al. | |
1945 args=(tp, metadata), | |
1946 origin=self, | |
1947 ) | |
1948 | |
1949 def __call__(self, *args, **kwargs): | |
1950 cons = self._get_cons() | |
1951 result = cons(*args, **kwargs) | |
1952 try: | |
1953 result.__orig_class__ = self | |
1954 except AttributeError: | |
1955 pass | |
1956 return result | |
1957 | |
1958 def __getattr__(self, attr): | |
1959 # For simplicity we just don't relay all dunder names | |
1960 if self.__origin__ is not None and not _is_dunder(attr): | |
1961 return getattr(self._get_cons(), attr) | |
1962 raise AttributeError(attr) | |
1963 | |
1964 def __setattr__(self, attr, value): | |
1965 if _is_dunder(attr) or attr.startswith('_abc_'): | |
1966 super().__setattr__(attr, value) | |
1967 elif self.__origin__ is None: | |
1968 raise AttributeError(attr) | |
1969 else: | |
1970 setattr(self._get_cons(), attr, value) | |
1971 | |
1972 def __instancecheck__(self, obj): | |
1973 raise TypeError("Annotated cannot be used with isinstance().") | |
1974 | |
1975 def __subclasscheck__(self, cls): | |
1976 raise TypeError("Annotated cannot be used with issubclass().") | |
1977 | |
1978 class Annotated(metaclass=AnnotatedMeta): | |
1979 """Add context specific metadata to a type. | |
1980 | |
1981 Example: Annotated[int, runtime_check.Unsigned] indicates to the | |
1982 hypothetical runtime_check module that this type is an unsigned int. | |
1983 Every other consumer of this type can ignore this metadata and treat | |
1984 this type as int. | |
1985 | |
1986 The first argument to Annotated must be a valid type, the remaining | |
1987 arguments are kept as a tuple in the __metadata__ field. | |
1988 | |
1989 Details: | |
1990 | |
1991 - It's an error to call `Annotated` with less than two arguments. | |
1992 - Nested Annotated are flattened:: | |
1993 | |
1994 Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3] | |
1995 | |
1996 - Instantiating an annotated type is equivalent to instantiating the | |
1997 underlying type:: | |
1998 | |
1999 Annotated[C, Ann1](5) == C(5) | |
2000 | |
2001 - Annotated can be used as a generic type alias:: | |
2002 | |
2003 Optimized = Annotated[T, runtime.Optimize()] | |
2004 Optimized[int] == Annotated[int, runtime.Optimize()] | |
2005 | |
2006 OptimizedList = Annotated[List[T], runtime.Optimize()] | |
2007 OptimizedList[int] == Annotated[List[int], runtime.Optimize()] | |
2008 """ | |
2009 | |
2010 # Python 3.8 has get_origin() and get_args() but those implementations aren't | |
2011 # Annotated-aware, so we can't use those, only Python 3.9 versions will do. | |
2012 if sys.version_info[:2] >= (3, 9): | |
2013 get_origin = typing.get_origin | |
2014 get_args = typing.get_args | |
2015 elif PEP_560: | |
2016 from typing import _GenericAlias # noqa | |
2017 | |
2018 def get_origin(tp): | |
2019 """Get the unsubscripted version of a type. | |
2020 | |
2021 This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar | |
2022 and Annotated. Return None for unsupported types. Examples:: | |
2023 | |
2024 get_origin(Literal[42]) is Literal | |
2025 get_origin(int) is None | |
2026 get_origin(ClassVar[int]) is ClassVar | |
2027 get_origin(Generic) is Generic | |
2028 get_origin(Generic[T]) is Generic | |
2029 get_origin(Union[T, int]) is Union | |
2030 get_origin(List[Tuple[T, T]][int]) == list | |
2031 """ | |
2032 if isinstance(tp, _AnnotatedAlias): | |
2033 return Annotated | |
2034 if isinstance(tp, _GenericAlias): | |
2035 return tp.__origin__ | |
2036 if tp is Generic: | |
2037 return Generic | |
2038 return None | |
2039 | |
2040 def get_args(tp): | |
2041 """Get type arguments with all substitutions performed. | |
2042 | |
2043 For unions, basic simplifications used by Union constructor are performed. | |
2044 Examples:: | |
2045 get_args(Dict[str, int]) == (str, int) | |
2046 get_args(int) == () | |
2047 get_args(Union[int, Union[T, int], str][int]) == (int, str) | |
2048 get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int]) | |
2049 get_args(Callable[[], T][int]) == ([], int) | |
2050 """ | |
2051 if isinstance(tp, _AnnotatedAlias): | |
2052 return (tp.__origin__,) + tp.__metadata__ | |
2053 if isinstance(tp, _GenericAlias): | |
2054 res = tp.__args__ | |
2055 if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis: | |
2056 res = (list(res[:-1]), res[-1]) | |
2057 return res | |
2058 return () |