1import abc 2import collections 3import contextlib 4import sys 5import typing 6import collections.abc as collections_abc 7import 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.) 12from 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. 17PEP_560 = sys.version_info[:3] >= (3, 7, 0) 18 19if PEP_560: 20 GenericMeta = TypingMeta = type 21else: 22 from typing import GenericMeta, TypingMeta 23OLD_GENERICS = False 24try: 25 from typing import _type_vars, _next_in_mro, _type_check 26except ImportError: 27 OLD_GENERICS = True 28try: 29 from typing import _subs_tree # noqa 30 SUBS_TREE = True 31except ImportError: 32 SUBS_TREE = False 33try: 34 from typing import _tp_cache 35except ImportError: 36 def _tp_cache(x): 37 return x 38try: 39 from typing import _TypingEllipsis, _TypingEmpty 40except 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 52def _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 60def _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 70if hasattr(typing, '_generic_new'): 71 _generic_new = typing._generic_new 72else: 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 90if hasattr(typing, '_geqv'): 91 from typing import _geqv 92 _geqv_defined = True 93else: 94 _geqv = None 95 _geqv_defined = False 96 97if sys.version_info[:2] >= (3, 6): 98 import _collections_abc 99 _check_methods_in_mro = _collections_abc._check_methods 100else: 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 'Concatenate', 119 'Final', 120 'ParamSpec', 121 'Type', 122 123 # ABCs (from collections.abc). 124 # The following are added depending on presence 125 # of their non-generic counterparts in stdlib: 126 # 'Awaitable', 127 # 'AsyncIterator', 128 # 'AsyncIterable', 129 # 'Coroutine', 130 # 'AsyncGenerator', 131 # 'AsyncContextManager', 132 # 'ChainMap', 133 134 # Concrete collection types. 135 'ContextManager', 136 'Counter', 137 'Deque', 138 'DefaultDict', 139 'OrderedDict' 140 'TypedDict', 141 142 # Structural checks, a.k.a. protocols. 143 'SupportsIndex', 144 145 # One-off things. 146 'final', 147 'IntVar', 148 'Literal', 149 'NewType', 150 'overload', 151 'Text', 152 'TypeAlias', 153 'TypeGuard', 154 'TYPE_CHECKING', 155] 156 157# Annotated relies on substitution trees of pep 560. It will not work for 158# versions of typing older than 3.5.3 159HAVE_ANNOTATED = PEP_560 or SUBS_TREE 160 161if PEP_560: 162 __all__.extend(["get_args", "get_origin", "get_type_hints"]) 163 164if HAVE_ANNOTATED: 165 __all__.append("Annotated") 166 167# Protocols are hard to backport to the original version of typing 3.5.0 168HAVE_PROTOCOLS = sys.version_info[:3] != (3, 5, 0) 169 170if HAVE_PROTOCOLS: 171 __all__.extend(['Protocol', 'runtime', 'runtime_checkable']) 172 173 174# TODO 175if hasattr(typing, 'NoReturn'): 176 NoReturn = typing.NoReturn 177elif hasattr(typing, '_FinalTypingBase'): 178 class _NoReturn(typing._FinalTypingBase, _root=True): 179 """Special type indicating functions that never return. 180 Example:: 181 182 from typing import NoReturn 183 184 def stop() -> NoReturn: 185 raise Exception('no way') 186 187 This type is invalid in other positions, e.g., ``List[NoReturn]`` 188 will fail in static type checkers. 189 """ 190 __slots__ = () 191 192 def __instancecheck__(self, obj): 193 raise TypeError("NoReturn cannot be used with isinstance().") 194 195 def __subclasscheck__(self, cls): 196 raise TypeError("NoReturn cannot be used with issubclass().") 197 198 NoReturn = _NoReturn(_root=True) 199else: 200 class _NoReturnMeta(typing.TypingMeta): 201 """Metaclass for NoReturn""" 202 def __new__(cls, name, bases, namespace, _root=False): 203 return super().__new__(cls, name, bases, namespace, _root=_root) 204 205 def __instancecheck__(self, obj): 206 raise TypeError("NoReturn cannot be used with isinstance().") 207 208 def __subclasscheck__(self, cls): 209 raise TypeError("NoReturn cannot be used with issubclass().") 210 211 class NoReturn(typing.Final, metaclass=_NoReturnMeta, _root=True): 212 """Special type indicating functions that never return. 213 Example:: 214 215 from typing import NoReturn 216 217 def stop() -> NoReturn: 218 raise Exception('no way') 219 220 This type is invalid in other positions, e.g., ``List[NoReturn]`` 221 will fail in static type checkers. 222 """ 223 __slots__ = () 224 225 226# Some unconstrained type variables. These are used by the container types. 227# (These are not for export.) 228T = typing.TypeVar('T') # Any type. 229KT = typing.TypeVar('KT') # Key type. 230VT = typing.TypeVar('VT') # Value type. 231T_co = typing.TypeVar('T_co', covariant=True) # Any type covariant containers. 232V_co = typing.TypeVar('V_co', covariant=True) # Any type covariant containers. 233VT_co = typing.TypeVar('VT_co', covariant=True) # Value type covariant containers. 234T_contra = typing.TypeVar('T_contra', contravariant=True) # Ditto contravariant. 235 236 237if hasattr(typing, 'ClassVar'): 238 ClassVar = typing.ClassVar 239elif hasattr(typing, '_FinalTypingBase'): 240 class _ClassVar(typing._FinalTypingBase, _root=True): 241 """Special type construct to mark class variables. 242 243 An annotation wrapped in ClassVar indicates that a given 244 attribute is intended to be used as a class variable and 245 should not be set on instances of that class. Usage:: 246 247 class Starship: 248 stats: ClassVar[Dict[str, int]] = {} # class variable 249 damage: int = 10 # instance variable 250 251 ClassVar accepts only types and cannot be further subscribed. 252 253 Note that ClassVar is not a class itself, and should not 254 be used with isinstance() or issubclass(). 255 """ 256 257 __slots__ = ('__type__',) 258 259 def __init__(self, tp=None, **kwds): 260 self.__type__ = tp 261 262 def __getitem__(self, item): 263 cls = type(self) 264 if self.__type__ is None: 265 return cls(typing._type_check(item, 266 '{} accepts only single type.'.format(cls.__name__[1:])), 267 _root=True) 268 raise TypeError('{} cannot be further subscripted' 269 .format(cls.__name__[1:])) 270 271 def _eval_type(self, globalns, localns): 272 new_tp = typing._eval_type(self.__type__, globalns, localns) 273 if new_tp == self.__type__: 274 return self 275 return type(self)(new_tp, _root=True) 276 277 def __repr__(self): 278 r = super().__repr__() 279 if self.__type__ is not None: 280 r += '[{}]'.format(typing._type_repr(self.__type__)) 281 return r 282 283 def __hash__(self): 284 return hash((type(self).__name__, self.__type__)) 285 286 def __eq__(self, other): 287 if not isinstance(other, _ClassVar): 288 return NotImplemented 289 if self.__type__ is not None: 290 return self.__type__ == other.__type__ 291 return self is other 292 293 ClassVar = _ClassVar(_root=True) 294else: 295 class _ClassVarMeta(typing.TypingMeta): 296 """Metaclass for ClassVar""" 297 298 def __new__(cls, name, bases, namespace, tp=None, _root=False): 299 self = super().__new__(cls, name, bases, namespace, _root=_root) 300 if tp is not None: 301 self.__type__ = tp 302 return self 303 304 def __instancecheck__(self, obj): 305 raise TypeError("ClassVar cannot be used with isinstance().") 306 307 def __subclasscheck__(self, cls): 308 raise TypeError("ClassVar cannot be used with issubclass().") 309 310 def __getitem__(self, item): 311 cls = type(self) 312 if self.__type__ is not None: 313 raise TypeError('{} cannot be further subscripted' 314 .format(cls.__name__[1:])) 315 316 param = typing._type_check( 317 item, 318 '{} accepts only single type.'.format(cls.__name__[1:])) 319 return cls(self.__name__, self.__bases__, 320 dict(self.__dict__), tp=param, _root=True) 321 322 def _eval_type(self, globalns, localns): 323 new_tp = typing._eval_type(self.__type__, globalns, localns) 324 if new_tp == self.__type__: 325 return self 326 return type(self)(self.__name__, self.__bases__, 327 dict(self.__dict__), tp=self.__type__, 328 _root=True) 329 330 def __repr__(self): 331 r = super().__repr__() 332 if self.__type__ is not None: 333 r += '[{}]'.format(typing._type_repr(self.__type__)) 334 return r 335 336 def __hash__(self): 337 return hash((type(self).__name__, self.__type__)) 338 339 def __eq__(self, other): 340 if not isinstance(other, ClassVar): 341 return NotImplemented 342 if self.__type__ is not None: 343 return self.__type__ == other.__type__ 344 return self is other 345 346 class ClassVar(typing.Final, metaclass=_ClassVarMeta, _root=True): 347 """Special type construct to mark class variables. 348 349 An annotation wrapped in ClassVar indicates that a given 350 attribute is intended to be used as a class variable and 351 should not be set on instances of that class. Usage:: 352 353 class Starship: 354 stats: ClassVar[Dict[str, int]] = {} # class variable 355 damage: int = 10 # instance variable 356 357 ClassVar accepts only types and cannot be further subscribed. 358 359 Note that ClassVar is not a class itself, and should not 360 be used with isinstance() or issubclass(). 361 """ 362 363 __type__ = None 364 365# On older versions of typing there is an internal class named "Final". 366if hasattr(typing, 'Final') and sys.version_info[:2] >= (3, 7): 367 Final = typing.Final 368elif sys.version_info[:2] >= (3, 7): 369 class _FinalForm(typing._SpecialForm, _root=True): 370 371 def __repr__(self): 372 return 'typing_extensions.' + self._name 373 374 def __getitem__(self, parameters): 375 item = typing._type_check(parameters, 376 '{} accepts only single type'.format(self._name)) 377 return _GenericAlias(self, (item,)) 378 379 Final = _FinalForm('Final', 380 doc="""A special typing construct to indicate that a name 381 cannot be re-assigned or overridden in a subclass. 382 For example: 383 384 MAX_SIZE: Final = 9000 385 MAX_SIZE += 1 # Error reported by type checker 386 387 class Connection: 388 TIMEOUT: Final[int] = 10 389 class FastConnector(Connection): 390 TIMEOUT = 1 # Error reported by type checker 391 392 There is no runtime checking of these properties.""") 393elif hasattr(typing, '_FinalTypingBase'): 394 class _Final(typing._FinalTypingBase, _root=True): 395 """A special typing construct to indicate that a name 396 cannot be re-assigned or overridden in a subclass. 397 For example: 398 399 MAX_SIZE: Final = 9000 400 MAX_SIZE += 1 # Error reported by type checker 401 402 class Connection: 403 TIMEOUT: Final[int] = 10 404 class FastConnector(Connection): 405 TIMEOUT = 1 # Error reported by type checker 406 407 There is no runtime checking of these properties. 408 """ 409 410 __slots__ = ('__type__',) 411 412 def __init__(self, tp=None, **kwds): 413 self.__type__ = tp 414 415 def __getitem__(self, item): 416 cls = type(self) 417 if self.__type__ is None: 418 return cls(typing._type_check(item, 419 '{} accepts only single type.'.format(cls.__name__[1:])), 420 _root=True) 421 raise TypeError('{} cannot be further subscripted' 422 .format(cls.__name__[1:])) 423 424 def _eval_type(self, globalns, localns): 425 new_tp = typing._eval_type(self.__type__, globalns, localns) 426 if new_tp == self.__type__: 427 return self 428 return type(self)(new_tp, _root=True) 429 430 def __repr__(self): 431 r = super().__repr__() 432 if self.__type__ is not None: 433 r += '[{}]'.format(typing._type_repr(self.__type__)) 434 return r 435 436 def __hash__(self): 437 return hash((type(self).__name__, self.__type__)) 438 439 def __eq__(self, other): 440 if not isinstance(other, _Final): 441 return NotImplemented 442 if self.__type__ is not None: 443 return self.__type__ == other.__type__ 444 return self is other 445 446 Final = _Final(_root=True) 447else: 448 class _FinalMeta(typing.TypingMeta): 449 """Metaclass for Final""" 450 451 def __new__(cls, name, bases, namespace, tp=None, _root=False): 452 self = super().__new__(cls, name, bases, namespace, _root=_root) 453 if tp is not None: 454 self.__type__ = tp 455 return self 456 457 def __instancecheck__(self, obj): 458 raise TypeError("Final cannot be used with isinstance().") 459 460 def __subclasscheck__(self, cls): 461 raise TypeError("Final cannot be used with issubclass().") 462 463 def __getitem__(self, item): 464 cls = type(self) 465 if self.__type__ is not None: 466 raise TypeError('{} cannot be further subscripted' 467 .format(cls.__name__[1:])) 468 469 param = typing._type_check( 470 item, 471 '{} accepts only single type.'.format(cls.__name__[1:])) 472 return cls(self.__name__, self.__bases__, 473 dict(self.__dict__), tp=param, _root=True) 474 475 def _eval_type(self, globalns, localns): 476 new_tp = typing._eval_type(self.__type__, globalns, localns) 477 if new_tp == self.__type__: 478 return self 479 return type(self)(self.__name__, self.__bases__, 480 dict(self.__dict__), tp=self.__type__, 481 _root=True) 482 483 def __repr__(self): 484 r = super().__repr__() 485 if self.__type__ is not None: 486 r += '[{}]'.format(typing._type_repr(self.__type__)) 487 return r 488 489 def __hash__(self): 490 return hash((type(self).__name__, self.__type__)) 491 492 def __eq__(self, other): 493 if not isinstance(other, Final): 494 return NotImplemented 495 if self.__type__ is not None: 496 return self.__type__ == other.__type__ 497 return self is other 498 499 class Final(typing.Final, metaclass=_FinalMeta, _root=True): 500 """A special typing construct to indicate that a name 501 cannot be re-assigned or overridden in a subclass. 502 For example: 503 504 MAX_SIZE: Final = 9000 505 MAX_SIZE += 1 # Error reported by type checker 506 507 class Connection: 508 TIMEOUT: Final[int] = 10 509 class FastConnector(Connection): 510 TIMEOUT = 1 # Error reported by type checker 511 512 There is no runtime checking of these properties. 513 """ 514 515 __type__ = None 516 517 518if hasattr(typing, 'final'): 519 final = typing.final 520else: 521 def final(f): 522 """This decorator can be used to indicate to type checkers that 523 the decorated method cannot be overridden, and decorated class 524 cannot be subclassed. For example: 525 526 class Base: 527 @final 528 def done(self) -> None: 529 ... 530 class Sub(Base): 531 def done(self) -> None: # Error reported by type checker 532 ... 533 @final 534 class Leaf: 535 ... 536 class Other(Leaf): # Error reported by type checker 537 ... 538 539 There is no runtime checking of these properties. 540 """ 541 return f 542 543 544def IntVar(name): 545 return TypeVar(name) 546 547 548if hasattr(typing, 'Literal'): 549 Literal = typing.Literal 550elif sys.version_info[:2] >= (3, 7): 551 class _LiteralForm(typing._SpecialForm, _root=True): 552 553 def __repr__(self): 554 return 'typing_extensions.' + self._name 555 556 def __getitem__(self, parameters): 557 return _GenericAlias(self, parameters) 558 559 Literal = _LiteralForm('Literal', 560 doc="""A type that can be used to indicate to type checkers 561 that the corresponding value has a value literally equivalent 562 to the provided parameter. For example: 563 564 var: Literal[4] = 4 565 566 The type checker understands that 'var' is literally equal to 567 the value 4 and no other value. 568 569 Literal[...] cannot be subclassed. There is no runtime 570 checking verifying that the parameter is actually a value 571 instead of a type.""") 572elif hasattr(typing, '_FinalTypingBase'): 573 class _Literal(typing._FinalTypingBase, _root=True): 574 """A type that can be used to indicate to type checkers that the 575 corresponding value has a value literally equivalent to the 576 provided parameter. For example: 577 578 var: Literal[4] = 4 579 580 The type checker understands that 'var' is literally equal to the 581 value 4 and no other value. 582 583 Literal[...] cannot be subclassed. There is no runtime checking 584 verifying that the parameter is actually a value instead of a type. 585 """ 586 587 __slots__ = ('__values__',) 588 589 def __init__(self, values=None, **kwds): 590 self.__values__ = values 591 592 def __getitem__(self, values): 593 cls = type(self) 594 if self.__values__ is None: 595 if not isinstance(values, tuple): 596 values = (values,) 597 return cls(values, _root=True) 598 raise TypeError('{} cannot be further subscripted' 599 .format(cls.__name__[1:])) 600 601 def _eval_type(self, globalns, localns): 602 return self 603 604 def __repr__(self): 605 r = super().__repr__() 606 if self.__values__ is not None: 607 r += '[{}]'.format(', '.join(map(typing._type_repr, self.__values__))) 608 return r 609 610 def __hash__(self): 611 return hash((type(self).__name__, self.__values__)) 612 613 def __eq__(self, other): 614 if not isinstance(other, _Literal): 615 return NotImplemented 616 if self.__values__ is not None: 617 return self.__values__ == other.__values__ 618 return self is other 619 620 Literal = _Literal(_root=True) 621else: 622 class _LiteralMeta(typing.TypingMeta): 623 """Metaclass for Literal""" 624 625 def __new__(cls, name, bases, namespace, values=None, _root=False): 626 self = super().__new__(cls, name, bases, namespace, _root=_root) 627 if values is not None: 628 self.__values__ = values 629 return self 630 631 def __instancecheck__(self, obj): 632 raise TypeError("Literal cannot be used with isinstance().") 633 634 def __subclasscheck__(self, cls): 635 raise TypeError("Literal cannot be used with issubclass().") 636 637 def __getitem__(self, item): 638 cls = type(self) 639 if self.__values__ is not None: 640 raise TypeError('{} cannot be further subscripted' 641 .format(cls.__name__[1:])) 642 643 if not isinstance(item, tuple): 644 item = (item,) 645 return cls(self.__name__, self.__bases__, 646 dict(self.__dict__), values=item, _root=True) 647 648 def _eval_type(self, globalns, localns): 649 return self 650 651 def __repr__(self): 652 r = super().__repr__() 653 if self.__values__ is not None: 654 r += '[{}]'.format(', '.join(map(typing._type_repr, self.__values__))) 655 return r 656 657 def __hash__(self): 658 return hash((type(self).__name__, self.__values__)) 659 660 def __eq__(self, other): 661 if not isinstance(other, Literal): 662 return NotImplemented 663 if self.__values__ is not None: 664 return self.__values__ == other.__values__ 665 return self is other 666 667 class Literal(typing.Final, metaclass=_LiteralMeta, _root=True): 668 """A type that can be used to indicate to type checkers that the 669 corresponding value has a value literally equivalent to the 670 provided parameter. For example: 671 672 var: Literal[4] = 4 673 674 The type checker understands that 'var' is literally equal to the 675 value 4 and no other value. 676 677 Literal[...] cannot be subclassed. There is no runtime checking 678 verifying that the parameter is actually a value instead of a type. 679 """ 680 681 __values__ = None 682 683 684def _overload_dummy(*args, **kwds): 685 """Helper for @overload to raise when called.""" 686 raise NotImplementedError( 687 "You should not call an overloaded function. " 688 "A series of @overload-decorated functions " 689 "outside a stub module should always be followed " 690 "by an implementation that is not @overload-ed.") 691 692 693def overload(func): 694 """Decorator for overloaded functions/methods. 695 696 In a stub file, place two or more stub definitions for the same 697 function in a row, each decorated with @overload. For example: 698 699 @overload 700 def utf8(value: None) -> None: ... 701 @overload 702 def utf8(value: bytes) -> bytes: ... 703 @overload 704 def utf8(value: str) -> bytes: ... 705 706 In a non-stub file (i.e. a regular .py file), do the same but 707 follow it with an implementation. The implementation should *not* 708 be decorated with @overload. For example: 709 710 @overload 711 def utf8(value: None) -> None: ... 712 @overload 713 def utf8(value: bytes) -> bytes: ... 714 @overload 715 def utf8(value: str) -> bytes: ... 716 def utf8(value): 717 # implementation goes here 718 """ 719 return _overload_dummy 720 721 722# This is not a real generic class. Don't use outside annotations. 723if hasattr(typing, 'Type'): 724 Type = typing.Type 725else: 726 # Internal type variable used for Type[]. 727 CT_co = typing.TypeVar('CT_co', covariant=True, bound=type) 728 729 class Type(typing.Generic[CT_co], extra=type): 730 """A special construct usable to annotate class objects. 731 732 For example, suppose we have the following classes:: 733 734 class User: ... # Abstract base for User classes 735 class BasicUser(User): ... 736 class ProUser(User): ... 737 class TeamUser(User): ... 738 739 And a function that takes a class argument that's a subclass of 740 User and returns an instance of the corresponding class:: 741 742 U = TypeVar('U', bound=User) 743 def new_user(user_class: Type[U]) -> U: 744 user = user_class() 745 # (Here we could write the user object to a database) 746 return user 747 joe = new_user(BasicUser) 748 749 At this point the type checker knows that joe has type BasicUser. 750 """ 751 752 __slots__ = () 753 754 755# Various ABCs mimicking those in collections.abc. 756# A few are simply re-exported for completeness. 757 758def _define_guard(type_name): 759 """ 760 Returns True if the given type isn't defined in typing but 761 is defined in collections_abc. 762 763 Adds the type to __all__ if the collection is found in either 764 typing or collection_abc. 765 """ 766 if hasattr(typing, type_name): 767 __all__.append(type_name) 768 globals()[type_name] = getattr(typing, type_name) 769 return False 770 elif hasattr(collections_abc, type_name): 771 __all__.append(type_name) 772 return True 773 else: 774 return False 775 776 777class _ExtensionsGenericMeta(GenericMeta): 778 def __subclasscheck__(self, subclass): 779 """This mimics a more modern GenericMeta.__subclasscheck__() logic 780 (that does not have problems with recursion) to work around interactions 781 between collections, typing, and typing_extensions on older 782 versions of Python, see https://github.com/python/typing/issues/501. 783 """ 784 if sys.version_info[:3] >= (3, 5, 3) or sys.version_info[:3] < (3, 5, 0): 785 if self.__origin__ is not None: 786 if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools']: 787 raise TypeError("Parameterized generics cannot be used with class " 788 "or instance checks") 789 return False 790 if not self.__extra__: 791 return super().__subclasscheck__(subclass) 792 res = self.__extra__.__subclasshook__(subclass) 793 if res is not NotImplemented: 794 return res 795 if self.__extra__ in subclass.__mro__: 796 return True 797 for scls in self.__extra__.__subclasses__(): 798 if isinstance(scls, GenericMeta): 799 continue 800 if issubclass(subclass, scls): 801 return True 802 return False 803 804 805if _define_guard('Awaitable'): 806 class Awaitable(typing.Generic[T_co], metaclass=_ExtensionsGenericMeta, 807 extra=collections_abc.Awaitable): 808 __slots__ = () 809 810 811if _define_guard('Coroutine'): 812 class Coroutine(Awaitable[V_co], typing.Generic[T_co, T_contra, V_co], 813 metaclass=_ExtensionsGenericMeta, 814 extra=collections_abc.Coroutine): 815 __slots__ = () 816 817 818if _define_guard('AsyncIterable'): 819 class AsyncIterable(typing.Generic[T_co], 820 metaclass=_ExtensionsGenericMeta, 821 extra=collections_abc.AsyncIterable): 822 __slots__ = () 823 824 825if _define_guard('AsyncIterator'): 826 class AsyncIterator(AsyncIterable[T_co], 827 metaclass=_ExtensionsGenericMeta, 828 extra=collections_abc.AsyncIterator): 829 __slots__ = () 830 831 832if hasattr(typing, 'Deque'): 833 Deque = typing.Deque 834elif _geqv_defined: 835 class Deque(collections.deque, typing.MutableSequence[T], 836 metaclass=_ExtensionsGenericMeta, 837 extra=collections.deque): 838 __slots__ = () 839 840 def __new__(cls, *args, **kwds): 841 if _geqv(cls, Deque): 842 return collections.deque(*args, **kwds) 843 return _generic_new(collections.deque, cls, *args, **kwds) 844else: 845 class Deque(collections.deque, typing.MutableSequence[T], 846 metaclass=_ExtensionsGenericMeta, 847 extra=collections.deque): 848 __slots__ = () 849 850 def __new__(cls, *args, **kwds): 851 if cls._gorg is Deque: 852 return collections.deque(*args, **kwds) 853 return _generic_new(collections.deque, cls, *args, **kwds) 854 855 856if hasattr(typing, 'ContextManager'): 857 ContextManager = typing.ContextManager 858elif hasattr(contextlib, 'AbstractContextManager'): 859 class ContextManager(typing.Generic[T_co], 860 metaclass=_ExtensionsGenericMeta, 861 extra=contextlib.AbstractContextManager): 862 __slots__ = () 863else: 864 class ContextManager(typing.Generic[T_co]): 865 __slots__ = () 866 867 def __enter__(self): 868 return self 869 870 @abc.abstractmethod 871 def __exit__(self, exc_type, exc_value, traceback): 872 return None 873 874 @classmethod 875 def __subclasshook__(cls, C): 876 if cls is ContextManager: 877 # In Python 3.6+, it is possible to set a method to None to 878 # explicitly indicate that the class does not implement an ABC 879 # (https://bugs.python.org/issue25958), but we do not support 880 # that pattern here because this fallback class is only used 881 # in Python 3.5 and earlier. 882 if (any("__enter__" in B.__dict__ for B in C.__mro__) and 883 any("__exit__" in B.__dict__ for B in C.__mro__)): 884 return True 885 return NotImplemented 886 887 888if hasattr(typing, 'AsyncContextManager'): 889 AsyncContextManager = typing.AsyncContextManager 890 __all__.append('AsyncContextManager') 891elif hasattr(contextlib, 'AbstractAsyncContextManager'): 892 class AsyncContextManager(typing.Generic[T_co], 893 metaclass=_ExtensionsGenericMeta, 894 extra=contextlib.AbstractAsyncContextManager): 895 __slots__ = () 896 897 __all__.append('AsyncContextManager') 898elif sys.version_info[:2] >= (3, 5): 899 exec(""" 900class AsyncContextManager(typing.Generic[T_co]): 901 __slots__ = () 902 903 async def __aenter__(self): 904 return self 905 906 @abc.abstractmethod 907 async def __aexit__(self, exc_type, exc_value, traceback): 908 return None 909 910 @classmethod 911 def __subclasshook__(cls, C): 912 if cls is AsyncContextManager: 913 return _check_methods_in_mro(C, "__aenter__", "__aexit__") 914 return NotImplemented 915 916__all__.append('AsyncContextManager') 917""") 918 919 920if hasattr(typing, 'DefaultDict'): 921 DefaultDict = typing.DefaultDict 922elif _geqv_defined: 923 class DefaultDict(collections.defaultdict, typing.MutableMapping[KT, VT], 924 metaclass=_ExtensionsGenericMeta, 925 extra=collections.defaultdict): 926 927 __slots__ = () 928 929 def __new__(cls, *args, **kwds): 930 if _geqv(cls, DefaultDict): 931 return collections.defaultdict(*args, **kwds) 932 return _generic_new(collections.defaultdict, cls, *args, **kwds) 933else: 934 class DefaultDict(collections.defaultdict, typing.MutableMapping[KT, VT], 935 metaclass=_ExtensionsGenericMeta, 936 extra=collections.defaultdict): 937 938 __slots__ = () 939 940 def __new__(cls, *args, **kwds): 941 if cls._gorg is DefaultDict: 942 return collections.defaultdict(*args, **kwds) 943 return _generic_new(collections.defaultdict, cls, *args, **kwds) 944 945 946if hasattr(typing, 'OrderedDict'): 947 OrderedDict = typing.OrderedDict 948elif (3, 7, 0) <= sys.version_info[:3] < (3, 7, 2): 949 OrderedDict = typing._alias(collections.OrderedDict, (KT, VT)) 950elif _geqv_defined: 951 class OrderedDict(collections.OrderedDict, typing.MutableMapping[KT, VT], 952 metaclass=_ExtensionsGenericMeta, 953 extra=collections.OrderedDict): 954 955 __slots__ = () 956 957 def __new__(cls, *args, **kwds): 958 if _geqv(cls, OrderedDict): 959 return collections.OrderedDict(*args, **kwds) 960 return _generic_new(collections.OrderedDict, cls, *args, **kwds) 961else: 962 class OrderedDict(collections.OrderedDict, typing.MutableMapping[KT, VT], 963 metaclass=_ExtensionsGenericMeta, 964 extra=collections.OrderedDict): 965 966 __slots__ = () 967 968 def __new__(cls, *args, **kwds): 969 if cls._gorg is OrderedDict: 970 return collections.OrderedDict(*args, **kwds) 971 return _generic_new(collections.OrderedDict, cls, *args, **kwds) 972 973 974if hasattr(typing, 'Counter'): 975 Counter = typing.Counter 976elif (3, 5, 0) <= sys.version_info[:3] <= (3, 5, 1): 977 assert _geqv_defined 978 _TInt = typing.TypeVar('_TInt') 979 980 class _CounterMeta(typing.GenericMeta): 981 """Metaclass for Counter""" 982 def __getitem__(self, item): 983 return super().__getitem__((item, int)) 984 985 class Counter(collections.Counter, 986 typing.Dict[T, int], 987 metaclass=_CounterMeta, 988 extra=collections.Counter): 989 990 __slots__ = () 991 992 def __new__(cls, *args, **kwds): 993 if _geqv(cls, Counter): 994 return collections.Counter(*args, **kwds) 995 return _generic_new(collections.Counter, cls, *args, **kwds) 996 997elif _geqv_defined: 998 class Counter(collections.Counter, 999 typing.Dict[T, int], 1000 metaclass=_ExtensionsGenericMeta, extra=collections.Counter): 1001 1002 __slots__ = () 1003 1004 def __new__(cls, *args, **kwds): 1005 if _geqv(cls, Counter): 1006 return collections.Counter(*args, **kwds) 1007 return _generic_new(collections.Counter, cls, *args, **kwds) 1008 1009else: 1010 class Counter(collections.Counter, 1011 typing.Dict[T, int], 1012 metaclass=_ExtensionsGenericMeta, extra=collections.Counter): 1013 1014 __slots__ = () 1015 1016 def __new__(cls, *args, **kwds): 1017 if cls._gorg is Counter: 1018 return collections.Counter(*args, **kwds) 1019 return _generic_new(collections.Counter, cls, *args, **kwds) 1020 1021 1022if hasattr(typing, 'ChainMap'): 1023 ChainMap = typing.ChainMap 1024 __all__.append('ChainMap') 1025elif hasattr(collections, 'ChainMap'): 1026 # ChainMap only exists in 3.3+ 1027 if _geqv_defined: 1028 class ChainMap(collections.ChainMap, typing.MutableMapping[KT, VT], 1029 metaclass=_ExtensionsGenericMeta, 1030 extra=collections.ChainMap): 1031 1032 __slots__ = () 1033 1034 def __new__(cls, *args, **kwds): 1035 if _geqv(cls, ChainMap): 1036 return collections.ChainMap(*args, **kwds) 1037 return _generic_new(collections.ChainMap, cls, *args, **kwds) 1038 else: 1039 class ChainMap(collections.ChainMap, typing.MutableMapping[KT, VT], 1040 metaclass=_ExtensionsGenericMeta, 1041 extra=collections.ChainMap): 1042 1043 __slots__ = () 1044 1045 def __new__(cls, *args, **kwds): 1046 if cls._gorg is ChainMap: 1047 return collections.ChainMap(*args, **kwds) 1048 return _generic_new(collections.ChainMap, cls, *args, **kwds) 1049 1050 __all__.append('ChainMap') 1051 1052 1053if _define_guard('AsyncGenerator'): 1054 class AsyncGenerator(AsyncIterator[T_co], typing.Generic[T_co, T_contra], 1055 metaclass=_ExtensionsGenericMeta, 1056 extra=collections_abc.AsyncGenerator): 1057 __slots__ = () 1058 1059 1060if hasattr(typing, 'NewType'): 1061 NewType = typing.NewType 1062else: 1063 def NewType(name, tp): 1064 """NewType creates simple unique types with almost zero 1065 runtime overhead. NewType(name, tp) is considered a subtype of tp 1066 by static type checkers. At runtime, NewType(name, tp) returns 1067 a dummy function that simply returns its argument. Usage:: 1068 1069 UserId = NewType('UserId', int) 1070 1071 def name_by_id(user_id: UserId) -> str: 1072 ... 1073 1074 UserId('user') # Fails type check 1075 1076 name_by_id(42) # Fails type check 1077 name_by_id(UserId(42)) # OK 1078 1079 num = UserId(5) + 1 # type: int 1080 """ 1081 1082 def new_type(x): 1083 return x 1084 1085 new_type.__name__ = name 1086 new_type.__supertype__ = tp 1087 return new_type 1088 1089 1090if hasattr(typing, 'Text'): 1091 Text = typing.Text 1092else: 1093 Text = str 1094 1095 1096if hasattr(typing, 'TYPE_CHECKING'): 1097 TYPE_CHECKING = typing.TYPE_CHECKING 1098else: 1099 # Constant that's True when type checking, but False here. 1100 TYPE_CHECKING = False 1101 1102 1103def _gorg(cls): 1104 """This function exists for compatibility with old typing versions.""" 1105 assert isinstance(cls, GenericMeta) 1106 if hasattr(cls, '_gorg'): 1107 return cls._gorg 1108 while cls.__origin__ is not None: 1109 cls = cls.__origin__ 1110 return cls 1111 1112 1113if OLD_GENERICS: 1114 def _next_in_mro(cls): # noqa 1115 """This function exists for compatibility with old typing versions.""" 1116 next_in_mro = object 1117 for i, c in enumerate(cls.__mro__[:-1]): 1118 if isinstance(c, GenericMeta) and _gorg(c) is Generic: 1119 next_in_mro = cls.__mro__[i + 1] 1120 return next_in_mro 1121 1122 1123_PROTO_WHITELIST = ['Callable', 'Awaitable', 1124 'Iterable', 'Iterator', 'AsyncIterable', 'AsyncIterator', 1125 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible', 1126 'ContextManager', 'AsyncContextManager'] 1127 1128 1129def _get_protocol_attrs(cls): 1130 attrs = set() 1131 for base in cls.__mro__[:-1]: # without object 1132 if base.__name__ in ('Protocol', 'Generic'): 1133 continue 1134 annotations = getattr(base, '__annotations__', {}) 1135 for attr in list(base.__dict__.keys()) + list(annotations.keys()): 1136 if (not attr.startswith('_abc_') and attr not in ( 1137 '__abstractmethods__', '__annotations__', '__weakref__', 1138 '_is_protocol', '_is_runtime_protocol', '__dict__', 1139 '__args__', '__slots__', 1140 '__next_in_mro__', '__parameters__', '__origin__', 1141 '__orig_bases__', '__extra__', '__tree_hash__', 1142 '__doc__', '__subclasshook__', '__init__', '__new__', 1143 '__module__', '_MutableMapping__marker', '_gorg')): 1144 attrs.add(attr) 1145 return attrs 1146 1147 1148def _is_callable_members_only(cls): 1149 return all(callable(getattr(cls, attr, None)) for attr in _get_protocol_attrs(cls)) 1150 1151 1152if hasattr(typing, 'Protocol'): 1153 Protocol = typing.Protocol 1154elif HAVE_PROTOCOLS and not PEP_560: 1155 1156 def _no_init(self, *args, **kwargs): 1157 if type(self)._is_protocol: 1158 raise TypeError('Protocols cannot be instantiated') 1159 1160 class _ProtocolMeta(GenericMeta): 1161 """Internal metaclass for Protocol. 1162 1163 This exists so Protocol classes can be generic without deriving 1164 from Generic. 1165 """ 1166 if not OLD_GENERICS: 1167 def __new__(cls, name, bases, namespace, 1168 tvars=None, args=None, origin=None, extra=None, orig_bases=None): 1169 # This is just a version copied from GenericMeta.__new__ that 1170 # includes "Protocol" special treatment. (Comments removed for brevity.) 1171 assert extra is None # Protocols should not have extra 1172 if tvars is not None: 1173 assert origin is not None 1174 assert all(isinstance(t, TypeVar) for t in tvars), tvars 1175 else: 1176 tvars = _type_vars(bases) 1177 gvars = None 1178 for base in bases: 1179 if base is Generic: 1180 raise TypeError("Cannot inherit from plain Generic") 1181 if (isinstance(base, GenericMeta) and 1182 base.__origin__ in (Generic, Protocol)): 1183 if gvars is not None: 1184 raise TypeError( 1185 "Cannot inherit from Generic[...] or" 1186 " Protocol[...] multiple times.") 1187 gvars = base.__parameters__ 1188 if gvars is None: 1189 gvars = tvars 1190 else: 1191 tvarset = set(tvars) 1192 gvarset = set(gvars) 1193 if not tvarset <= gvarset: 1194 raise TypeError( 1195 "Some type variables (%s) " 1196 "are not listed in %s[%s]" % 1197 (", ".join(str(t) for t in tvars if t not in gvarset), 1198 "Generic" if any(b.__origin__ is Generic 1199 for b in bases) else "Protocol", 1200 ", ".join(str(g) for g in gvars))) 1201 tvars = gvars 1202 1203 initial_bases = bases 1204 if (extra is not None and type(extra) is abc.ABCMeta and 1205 extra not in bases): 1206 bases = (extra,) + bases 1207 bases = tuple(_gorg(b) if isinstance(b, GenericMeta) else b 1208 for b in bases) 1209 if any(isinstance(b, GenericMeta) and b is not Generic for b in bases): 1210 bases = tuple(b for b in bases if b is not Generic) 1211 namespace.update({'__origin__': origin, '__extra__': extra}) 1212 self = super(GenericMeta, cls).__new__(cls, name, bases, namespace, 1213 _root=True) 1214 super(GenericMeta, self).__setattr__('_gorg', 1215 self if not origin else 1216 _gorg(origin)) 1217 self.__parameters__ = tvars 1218 self.__args__ = tuple(... if a is _TypingEllipsis else 1219 () if a is _TypingEmpty else 1220 a for a in args) if args else None 1221 self.__next_in_mro__ = _next_in_mro(self) 1222 if orig_bases is None: 1223 self.__orig_bases__ = initial_bases 1224 elif origin is not None: 1225 self._abc_registry = origin._abc_registry 1226 self._abc_cache = origin._abc_cache 1227 if hasattr(self, '_subs_tree'): 1228 self.__tree_hash__ = (hash(self._subs_tree()) if origin else 1229 super(GenericMeta, self).__hash__()) 1230 return self 1231 1232 def __init__(cls, *args, **kwargs): 1233 super().__init__(*args, **kwargs) 1234 if not cls.__dict__.get('_is_protocol', None): 1235 cls._is_protocol = any(b is Protocol or 1236 isinstance(b, _ProtocolMeta) and 1237 b.__origin__ is Protocol 1238 for b in cls.__bases__) 1239 if cls._is_protocol: 1240 for base in cls.__mro__[1:]: 1241 if not (base in (object, Generic) or 1242 base.__module__ == 'collections.abc' and 1243 base.__name__ in _PROTO_WHITELIST or 1244 isinstance(base, TypingMeta) and base._is_protocol or 1245 isinstance(base, GenericMeta) and 1246 base.__origin__ is Generic): 1247 raise TypeError('Protocols can only inherit from other' 1248 ' protocols, got %r' % base) 1249 1250 cls.__init__ = _no_init 1251 1252 def _proto_hook(other): 1253 if not cls.__dict__.get('_is_protocol', None): 1254 return NotImplemented 1255 if not isinstance(other, type): 1256 # Same error as for issubclass(1, int) 1257 raise TypeError('issubclass() arg 1 must be a class') 1258 for attr in _get_protocol_attrs(cls): 1259 for base in other.__mro__: 1260 if attr in base.__dict__: 1261 if base.__dict__[attr] is None: 1262 return NotImplemented 1263 break 1264 annotations = getattr(base, '__annotations__', {}) 1265 if (isinstance(annotations, typing.Mapping) and 1266 attr in annotations and 1267 isinstance(other, _ProtocolMeta) and 1268 other._is_protocol): 1269 break 1270 else: 1271 return NotImplemented 1272 return True 1273 if '__subclasshook__' not in cls.__dict__: 1274 cls.__subclasshook__ = _proto_hook 1275 1276 def __instancecheck__(self, instance): 1277 # We need this method for situations where attributes are 1278 # assigned in __init__. 1279 if ((not getattr(self, '_is_protocol', False) or 1280 _is_callable_members_only(self)) and 1281 issubclass(instance.__class__, self)): 1282 return True 1283 if self._is_protocol: 1284 if all(hasattr(instance, attr) and 1285 (not callable(getattr(self, attr, None)) or 1286 getattr(instance, attr) is not None) 1287 for attr in _get_protocol_attrs(self)): 1288 return True 1289 return super(GenericMeta, self).__instancecheck__(instance) 1290 1291 def __subclasscheck__(self, cls): 1292 if self.__origin__ is not None: 1293 if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools']: 1294 raise TypeError("Parameterized generics cannot be used with class " 1295 "or instance checks") 1296 return False 1297 if (self.__dict__.get('_is_protocol', None) and 1298 not self.__dict__.get('_is_runtime_protocol', None)): 1299 if sys._getframe(1).f_globals['__name__'] in ['abc', 1300 'functools', 1301 'typing']: 1302 return False 1303 raise TypeError("Instance and class checks can only be used with" 1304 " @runtime protocols") 1305 if (self.__dict__.get('_is_runtime_protocol', None) and 1306 not _is_callable_members_only(self)): 1307 if sys._getframe(1).f_globals['__name__'] in ['abc', 1308 'functools', 1309 'typing']: 1310 return super(GenericMeta, self).__subclasscheck__(cls) 1311 raise TypeError("Protocols with non-method members" 1312 " don't support issubclass()") 1313 return super(GenericMeta, self).__subclasscheck__(cls) 1314 1315 if not OLD_GENERICS: 1316 @_tp_cache 1317 def __getitem__(self, params): 1318 # We also need to copy this from GenericMeta.__getitem__ to get 1319 # special treatment of "Protocol". (Comments removed for brevity.) 1320 if not isinstance(params, tuple): 1321 params = (params,) 1322 if not params and _gorg(self) is not Tuple: 1323 raise TypeError( 1324 "Parameter list to %s[...] cannot be empty" % self.__qualname__) 1325 msg = "Parameters to generic types must be types." 1326 params = tuple(_type_check(p, msg) for p in params) 1327 if self in (Generic, Protocol): 1328 if not all(isinstance(p, TypeVar) for p in params): 1329 raise TypeError( 1330 "Parameters to %r[...] must all be type variables" % self) 1331 if len(set(params)) != len(params): 1332 raise TypeError( 1333 "Parameters to %r[...] must all be unique" % self) 1334 tvars = params 1335 args = params 1336 elif self in (Tuple, Callable): 1337 tvars = _type_vars(params) 1338 args = params 1339 elif self.__origin__ in (Generic, Protocol): 1340 raise TypeError("Cannot subscript already-subscripted %s" % 1341 repr(self)) 1342 else: 1343 _check_generic(self, params) 1344 tvars = _type_vars(params) 1345 args = params 1346 1347 prepend = (self,) if self.__origin__ is None else () 1348 return self.__class__(self.__name__, 1349 prepend + self.__bases__, 1350 _no_slots_copy(self.__dict__), 1351 tvars=tvars, 1352 args=args, 1353 origin=self, 1354 extra=self.__extra__, 1355 orig_bases=self.__orig_bases__) 1356 1357 class Protocol(metaclass=_ProtocolMeta): 1358 """Base class for protocol classes. Protocol classes are defined as:: 1359 1360 class Proto(Protocol): 1361 def meth(self) -> int: 1362 ... 1363 1364 Such classes are primarily used with static type checkers that recognize 1365 structural subtyping (static duck-typing), for example:: 1366 1367 class C: 1368 def meth(self) -> int: 1369 return 0 1370 1371 def func(x: Proto) -> int: 1372 return x.meth() 1373 1374 func(C()) # Passes static type check 1375 1376 See PEP 544 for details. Protocol classes decorated with 1377 @typing_extensions.runtime act as simple-minded runtime protocol that checks 1378 only the presence of given attributes, ignoring their type signatures. 1379 1380 Protocol classes can be generic, they are defined as:: 1381 1382 class GenProto({bases}): 1383 def meth(self) -> T: 1384 ... 1385 """ 1386 __slots__ = () 1387 _is_protocol = True 1388 1389 def __new__(cls, *args, **kwds): 1390 if _gorg(cls) is Protocol: 1391 raise TypeError("Type Protocol cannot be instantiated; " 1392 "it can be used only as a base class") 1393 if OLD_GENERICS: 1394 return _generic_new(_next_in_mro(cls), cls, *args, **kwds) 1395 return _generic_new(cls.__next_in_mro__, cls, *args, **kwds) 1396 if Protocol.__doc__ is not None: 1397 Protocol.__doc__ = Protocol.__doc__.format(bases="Protocol, Generic[T]" if 1398 OLD_GENERICS else "Protocol[T]") 1399 1400 1401elif PEP_560: 1402 from typing import _type_check, _GenericAlias, _collect_type_vars # noqa 1403 1404 def _no_init(self, *args, **kwargs): 1405 if type(self)._is_protocol: 1406 raise TypeError('Protocols cannot be instantiated') 1407 1408 class _ProtocolMeta(abc.ABCMeta): 1409 # This metaclass is a bit unfortunate and exists only because of the lack 1410 # of __instancehook__. 1411 def __instancecheck__(cls, instance): 1412 # We need this method for situations where attributes are 1413 # assigned in __init__. 1414 if ((not getattr(cls, '_is_protocol', False) or 1415 _is_callable_members_only(cls)) and 1416 issubclass(instance.__class__, cls)): 1417 return True 1418 if cls._is_protocol: 1419 if all(hasattr(instance, attr) and 1420 (not callable(getattr(cls, attr, None)) or 1421 getattr(instance, attr) is not None) 1422 for attr in _get_protocol_attrs(cls)): 1423 return True 1424 return super().__instancecheck__(instance) 1425 1426 class Protocol(metaclass=_ProtocolMeta): 1427 # There is quite a lot of overlapping code with typing.Generic. 1428 # Unfortunately it is hard to avoid this while these live in two different 1429 # modules. The duplicated code will be removed when Protocol is moved to typing. 1430 """Base class for protocol classes. Protocol classes are defined as:: 1431 1432 class Proto(Protocol): 1433 def meth(self) -> int: 1434 ... 1435 1436 Such classes are primarily used with static type checkers that recognize 1437 structural subtyping (static duck-typing), for example:: 1438 1439 class C: 1440 def meth(self) -> int: 1441 return 0 1442 1443 def func(x: Proto) -> int: 1444 return x.meth() 1445 1446 func(C()) # Passes static type check 1447 1448 See PEP 544 for details. Protocol classes decorated with 1449 @typing_extensions.runtime act as simple-minded runtime protocol that checks 1450 only the presence of given attributes, ignoring their type signatures. 1451 1452 Protocol classes can be generic, they are defined as:: 1453 1454 class GenProto(Protocol[T]): 1455 def meth(self) -> T: 1456 ... 1457 """ 1458 __slots__ = () 1459 _is_protocol = True 1460 1461 def __new__(cls, *args, **kwds): 1462 if cls is Protocol: 1463 raise TypeError("Type Protocol cannot be instantiated; " 1464 "it can only be used as a base class") 1465 return super().__new__(cls) 1466 1467 @_tp_cache 1468 def __class_getitem__(cls, params): 1469 if not isinstance(params, tuple): 1470 params = (params,) 1471 if not params and cls is not Tuple: 1472 raise TypeError( 1473 "Parameter list to {}[...] cannot be empty".format(cls.__qualname__)) 1474 msg = "Parameters to generic types must be types." 1475 params = tuple(_type_check(p, msg) for p in params) 1476 if cls is Protocol: 1477 # Generic can only be subscripted with unique type variables. 1478 if not all(isinstance(p, TypeVar) for p in params): 1479 i = 0 1480 while isinstance(params[i], TypeVar): 1481 i += 1 1482 raise TypeError( 1483 "Parameters to Protocol[...] must all be type variables." 1484 " Parameter {} is {}".format(i + 1, params[i])) 1485 if len(set(params)) != len(params): 1486 raise TypeError( 1487 "Parameters to Protocol[...] must all be unique") 1488 else: 1489 # Subscripting a regular Generic subclass. 1490 _check_generic(cls, params) 1491 return _GenericAlias(cls, params) 1492 1493 def __init_subclass__(cls, *args, **kwargs): 1494 tvars = [] 1495 if '__orig_bases__' in cls.__dict__: 1496 error = Generic in cls.__orig_bases__ 1497 else: 1498 error = Generic in cls.__bases__ 1499 if error: 1500 raise TypeError("Cannot inherit from plain Generic") 1501 if '__orig_bases__' in cls.__dict__: 1502 tvars = _collect_type_vars(cls.__orig_bases__) 1503 # Look for Generic[T1, ..., Tn] or Protocol[T1, ..., Tn]. 1504 # If found, tvars must be a subset of it. 1505 # If not found, tvars is it. 1506 # Also check for and reject plain Generic, 1507 # and reject multiple Generic[...] and/or Protocol[...]. 1508 gvars = None 1509 for base in cls.__orig_bases__: 1510 if (isinstance(base, _GenericAlias) and 1511 base.__origin__ in (Generic, Protocol)): 1512 # for error messages 1513 the_base = 'Generic' if base.__origin__ is Generic else 'Protocol' 1514 if gvars is not None: 1515 raise TypeError( 1516 "Cannot inherit from Generic[...]" 1517 " and/or Protocol[...] multiple types.") 1518 gvars = base.__parameters__ 1519 if gvars is None: 1520 gvars = tvars 1521 else: 1522 tvarset = set(tvars) 1523 gvarset = set(gvars) 1524 if not tvarset <= gvarset: 1525 s_vars = ', '.join(str(t) for t in tvars if t not in gvarset) 1526 s_args = ', '.join(str(g) for g in gvars) 1527 raise TypeError("Some type variables ({}) are" 1528 " not listed in {}[{}]".format(s_vars, 1529 the_base, s_args)) 1530 tvars = gvars 1531 cls.__parameters__ = tuple(tvars) 1532 1533 # Determine if this is a protocol or a concrete subclass. 1534 if not cls.__dict__.get('_is_protocol', None): 1535 cls._is_protocol = any(b is Protocol for b in cls.__bases__) 1536 1537 # Set (or override) the protocol subclass hook. 1538 def _proto_hook(other): 1539 if not cls.__dict__.get('_is_protocol', None): 1540 return NotImplemented 1541 if not getattr(cls, '_is_runtime_protocol', False): 1542 if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']: 1543 return NotImplemented 1544 raise TypeError("Instance and class checks can only be used with" 1545 " @runtime protocols") 1546 if not _is_callable_members_only(cls): 1547 if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']: 1548 return NotImplemented 1549 raise TypeError("Protocols with non-method members" 1550 " don't support issubclass()") 1551 if not isinstance(other, type): 1552 # Same error as for issubclass(1, int) 1553 raise TypeError('issubclass() arg 1 must be a class') 1554 for attr in _get_protocol_attrs(cls): 1555 for base in other.__mro__: 1556 if attr in base.__dict__: 1557 if base.__dict__[attr] is None: 1558 return NotImplemented 1559 break 1560 annotations = getattr(base, '__annotations__', {}) 1561 if (isinstance(annotations, typing.Mapping) and 1562 attr in annotations and 1563 isinstance(other, _ProtocolMeta) and 1564 other._is_protocol): 1565 break 1566 else: 1567 return NotImplemented 1568 return True 1569 if '__subclasshook__' not in cls.__dict__: 1570 cls.__subclasshook__ = _proto_hook 1571 1572 # We have nothing more to do for non-protocols. 1573 if not cls._is_protocol: 1574 return 1575 1576 # Check consistency of bases. 1577 for base in cls.__bases__: 1578 if not (base in (object, Generic) or 1579 base.__module__ == 'collections.abc' and 1580 base.__name__ in _PROTO_WHITELIST or 1581 isinstance(base, _ProtocolMeta) and base._is_protocol): 1582 raise TypeError('Protocols can only inherit from other' 1583 ' protocols, got %r' % base) 1584 cls.__init__ = _no_init 1585 1586 1587if hasattr(typing, 'runtime_checkable'): 1588 runtime_checkable = typing.runtime_checkable 1589elif HAVE_PROTOCOLS: 1590 def runtime_checkable(cls): 1591 """Mark a protocol class as a runtime protocol, so that it 1592 can be used with isinstance() and issubclass(). Raise TypeError 1593 if applied to a non-protocol class. 1594 1595 This allows a simple-minded structural check very similar to the 1596 one-offs in collections.abc such as Hashable. 1597 """ 1598 if not isinstance(cls, _ProtocolMeta) or not cls._is_protocol: 1599 raise TypeError('@runtime_checkable can be only applied to protocol classes,' 1600 ' got %r' % cls) 1601 cls._is_runtime_protocol = True 1602 return cls 1603 1604 1605if HAVE_PROTOCOLS: 1606 # Exists for backwards compatibility. 1607 runtime = runtime_checkable 1608 1609 1610if hasattr(typing, 'SupportsIndex'): 1611 SupportsIndex = typing.SupportsIndex 1612elif HAVE_PROTOCOLS: 1613 @runtime_checkable 1614 class SupportsIndex(Protocol): 1615 __slots__ = () 1616 1617 @abc.abstractmethod 1618 def __index__(self) -> int: 1619 pass 1620 1621 1622if sys.version_info >= (3, 9, 2): 1623 # The standard library TypedDict in Python 3.8 does not store runtime information 1624 # about which (if any) keys are optional. See https://bugs.python.org/issue38834 1625 # The standard library TypedDict in Python 3.9.0/1 does not honour the "total" 1626 # keyword with old-style TypedDict(). See https://bugs.python.org/issue42059 1627 TypedDict = typing.TypedDict 1628else: 1629 def _check_fails(cls, other): 1630 try: 1631 if sys._getframe(1).f_globals['__name__'] not in ['abc', 1632 'functools', 1633 'typing']: 1634 # Typed dicts are only for static structural subtyping. 1635 raise TypeError('TypedDict does not support instance and class checks') 1636 except (AttributeError, ValueError): 1637 pass 1638 return False 1639 1640 def _dict_new(*args, **kwargs): 1641 if not args: 1642 raise TypeError('TypedDict.__new__(): not enough arguments') 1643 _, args = args[0], args[1:] # allow the "cls" keyword be passed 1644 return dict(*args, **kwargs) 1645 1646 _dict_new.__text_signature__ = '($cls, _typename, _fields=None, /, **kwargs)' 1647 1648 def _typeddict_new(*args, total=True, **kwargs): 1649 if not args: 1650 raise TypeError('TypedDict.__new__(): not enough arguments') 1651 _, args = args[0], args[1:] # allow the "cls" keyword be passed 1652 if args: 1653 typename, args = args[0], args[1:] # allow the "_typename" keyword be passed 1654 elif '_typename' in kwargs: 1655 typename = kwargs.pop('_typename') 1656 import warnings 1657 warnings.warn("Passing '_typename' as keyword argument is deprecated", 1658 DeprecationWarning, stacklevel=2) 1659 else: 1660 raise TypeError("TypedDict.__new__() missing 1 required positional " 1661 "argument: '_typename'") 1662 if args: 1663 try: 1664 fields, = args # allow the "_fields" keyword be passed 1665 except ValueError: 1666 raise TypeError('TypedDict.__new__() takes from 2 to 3 ' 1667 'positional arguments but {} ' 1668 'were given'.format(len(args) + 2)) 1669 elif '_fields' in kwargs and len(kwargs) == 1: 1670 fields = kwargs.pop('_fields') 1671 import warnings 1672 warnings.warn("Passing '_fields' as keyword argument is deprecated", 1673 DeprecationWarning, stacklevel=2) 1674 else: 1675 fields = None 1676 1677 if fields is None: 1678 fields = kwargs 1679 elif kwargs: 1680 raise TypeError("TypedDict takes either a dict or keyword arguments," 1681 " but not both") 1682 1683 ns = {'__annotations__': dict(fields)} 1684 try: 1685 # Setting correct module is necessary to make typed dict classes pickleable. 1686 ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__') 1687 except (AttributeError, ValueError): 1688 pass 1689 1690 return _TypedDictMeta(typename, (), ns, total=total) 1691 1692 _typeddict_new.__text_signature__ = ('($cls, _typename, _fields=None,' 1693 ' /, *, total=True, **kwargs)') 1694 1695 class _TypedDictMeta(type): 1696 def __init__(cls, name, bases, ns, total=True): 1697 # In Python 3.4 and 3.5 the __init__ method also needs to support the keyword arguments. 1698 # See https://www.python.org/dev/peps/pep-0487/#implementation-details 1699 super(_TypedDictMeta, cls).__init__(name, bases, ns) 1700 1701 def __new__(cls, name, bases, ns, total=True): 1702 # Create new typed dict class object. 1703 # This method is called directly when TypedDict is subclassed, 1704 # or via _typeddict_new when TypedDict is instantiated. This way 1705 # TypedDict supports all three syntaxes described in its docstring. 1706 # Subclasses and instances of TypedDict return actual dictionaries 1707 # via _dict_new. 1708 ns['__new__'] = _typeddict_new if name == 'TypedDict' else _dict_new 1709 tp_dict = super(_TypedDictMeta, cls).__new__(cls, name, (dict,), ns) 1710 1711 annotations = {} 1712 own_annotations = ns.get('__annotations__', {}) 1713 own_annotation_keys = set(own_annotations.keys()) 1714 msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type" 1715 own_annotations = { 1716 n: typing._type_check(tp, msg) for n, tp in own_annotations.items() 1717 } 1718 required_keys = set() 1719 optional_keys = set() 1720 1721 for base in bases: 1722 annotations.update(base.__dict__.get('__annotations__', {})) 1723 required_keys.update(base.__dict__.get('__required_keys__', ())) 1724 optional_keys.update(base.__dict__.get('__optional_keys__', ())) 1725 1726 annotations.update(own_annotations) 1727 if total: 1728 required_keys.update(own_annotation_keys) 1729 else: 1730 optional_keys.update(own_annotation_keys) 1731 1732 tp_dict.__annotations__ = annotations 1733 tp_dict.__required_keys__ = frozenset(required_keys) 1734 tp_dict.__optional_keys__ = frozenset(optional_keys) 1735 if not hasattr(tp_dict, '__total__'): 1736 tp_dict.__total__ = total 1737 return tp_dict 1738 1739 __instancecheck__ = __subclasscheck__ = _check_fails 1740 1741 TypedDict = _TypedDictMeta('TypedDict', (dict,), {}) 1742 TypedDict.__module__ = __name__ 1743 TypedDict.__doc__ = \ 1744 """A simple typed name space. At runtime it is equivalent to a plain dict. 1745 1746 TypedDict creates a dictionary type that expects all of its 1747 instances to have a certain set of keys, with each key 1748 associated with a value of a consistent type. This expectation 1749 is not checked at runtime but is only enforced by type checkers. 1750 Usage:: 1751 1752 class Point2D(TypedDict): 1753 x: int 1754 y: int 1755 label: str 1756 1757 a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK 1758 b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check 1759 1760 assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first') 1761 1762 The type info can be accessed via the Point2D.__annotations__ dict, and 1763 the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets. 1764 TypedDict supports two additional equivalent forms:: 1765 1766 Point2D = TypedDict('Point2D', x=int, y=int, label=str) 1767 Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) 1768 1769 The class syntax is only supported in Python 3.6+, while two other 1770 syntax forms work for Python 2.7 and 3.2+ 1771 """ 1772 1773 1774# Python 3.9+ has PEP 593 (Annotated and modified get_type_hints) 1775if hasattr(typing, 'Annotated'): 1776 Annotated = typing.Annotated 1777 get_type_hints = typing.get_type_hints 1778 # Not exported and not a public API, but needed for get_origin() and get_args() 1779 # to work. 1780 _AnnotatedAlias = typing._AnnotatedAlias 1781elif PEP_560: 1782 class _AnnotatedAlias(typing._GenericAlias, _root=True): 1783 """Runtime representation of an annotated type. 1784 1785 At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't' 1786 with extra annotations. The alias behaves like a normal typing alias, 1787 instantiating is the same as instantiating the underlying type, binding 1788 it to types is also the same. 1789 """ 1790 def __init__(self, origin, metadata): 1791 if isinstance(origin, _AnnotatedAlias): 1792 metadata = origin.__metadata__ + metadata 1793 origin = origin.__origin__ 1794 super().__init__(origin, origin) 1795 self.__metadata__ = metadata 1796 1797 def copy_with(self, params): 1798 assert len(params) == 1 1799 new_type = params[0] 1800 return _AnnotatedAlias(new_type, self.__metadata__) 1801 1802 def __repr__(self): 1803 return "typing_extensions.Annotated[{}, {}]".format( 1804 typing._type_repr(self.__origin__), 1805 ", ".join(repr(a) for a in self.__metadata__) 1806 ) 1807 1808 def __reduce__(self): 1809 return operator.getitem, ( 1810 Annotated, (self.__origin__,) + self.__metadata__ 1811 ) 1812 1813 def __eq__(self, other): 1814 if not isinstance(other, _AnnotatedAlias): 1815 return NotImplemented 1816 if self.__origin__ != other.__origin__: 1817 return False 1818 return self.__metadata__ == other.__metadata__ 1819 1820 def __hash__(self): 1821 return hash((self.__origin__, self.__metadata__)) 1822 1823 class Annotated: 1824 """Add context specific metadata to a type. 1825 1826 Example: Annotated[int, runtime_check.Unsigned] indicates to the 1827 hypothetical runtime_check module that this type is an unsigned int. 1828 Every other consumer of this type can ignore this metadata and treat 1829 this type as int. 1830 1831 The first argument to Annotated must be a valid type (and will be in 1832 the __origin__ field), the remaining arguments are kept as a tuple in 1833 the __extra__ field. 1834 1835 Details: 1836 1837 - It's an error to call `Annotated` with less than two arguments. 1838 - Nested Annotated are flattened:: 1839 1840 Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3] 1841 1842 - Instantiating an annotated type is equivalent to instantiating the 1843 underlying type:: 1844 1845 Annotated[C, Ann1](5) == C(5) 1846 1847 - Annotated can be used as a generic type alias:: 1848 1849 Optimized = Annotated[T, runtime.Optimize()] 1850 Optimized[int] == Annotated[int, runtime.Optimize()] 1851 1852 OptimizedList = Annotated[List[T], runtime.Optimize()] 1853 OptimizedList[int] == Annotated[List[int], runtime.Optimize()] 1854 """ 1855 1856 __slots__ = () 1857 1858 def __new__(cls, *args, **kwargs): 1859 raise TypeError("Type Annotated cannot be instantiated.") 1860 1861 @_tp_cache 1862 def __class_getitem__(cls, params): 1863 if not isinstance(params, tuple) or len(params) < 2: 1864 raise TypeError("Annotated[...] should be used " 1865 "with at least two arguments (a type and an " 1866 "annotation).") 1867 msg = "Annotated[t, ...]: t must be a type." 1868 origin = typing._type_check(params[0], msg) 1869 metadata = tuple(params[1:]) 1870 return _AnnotatedAlias(origin, metadata) 1871 1872 def __init_subclass__(cls, *args, **kwargs): 1873 raise TypeError( 1874 "Cannot subclass {}.Annotated".format(cls.__module__) 1875 ) 1876 1877 def _strip_annotations(t): 1878 """Strips the annotations from a given type. 1879 """ 1880 if isinstance(t, _AnnotatedAlias): 1881 return _strip_annotations(t.__origin__) 1882 if isinstance(t, typing._GenericAlias): 1883 stripped_args = tuple(_strip_annotations(a) for a in t.__args__) 1884 if stripped_args == t.__args__: 1885 return t 1886 res = t.copy_with(stripped_args) 1887 res._special = t._special 1888 return res 1889 return t 1890 1891 def get_type_hints(obj, globalns=None, localns=None, include_extras=False): 1892 """Return type hints for an object. 1893 1894 This is often the same as obj.__annotations__, but it handles 1895 forward references encoded as string literals, adds Optional[t] if a 1896 default value equal to None is set and recursively replaces all 1897 'Annotated[T, ...]' with 'T' (unless 'include_extras=True'). 1898 1899 The argument may be a module, class, method, or function. The annotations 1900 are returned as a dictionary. For classes, annotations include also 1901 inherited members. 1902 1903 TypeError is raised if the argument is not of a type that can contain 1904 annotations, and an empty dictionary is returned if no annotations are 1905 present. 1906 1907 BEWARE -- the behavior of globalns and localns is counterintuitive 1908 (unless you are familiar with how eval() and exec() work). The 1909 search order is locals first, then globals. 1910 1911 - If no dict arguments are passed, an attempt is made to use the 1912 globals from obj (or the respective module's globals for classes), 1913 and these are also used as the locals. If the object does not appear 1914 to have globals, an empty dictionary is used. 1915 1916 - If one dict argument is passed, it is used for both globals and 1917 locals. 1918 1919 - If two dict arguments are passed, they specify globals and 1920 locals, respectively. 1921 """ 1922 hint = typing.get_type_hints(obj, globalns=globalns, localns=localns) 1923 if include_extras: 1924 return hint 1925 return {k: _strip_annotations(t) for k, t in hint.items()} 1926 1927elif HAVE_ANNOTATED: 1928 1929 def _is_dunder(name): 1930 """Returns True if name is a __dunder_variable_name__.""" 1931 return len(name) > 4 and name.startswith('__') and name.endswith('__') 1932 1933 # Prior to Python 3.7 types did not have `copy_with`. A lot of the equality 1934 # checks, argument expansion etc. are done on the _subs_tre. As a result we 1935 # can't provide a get_type_hints function that strips out annotations. 1936 1937 class AnnotatedMeta(typing.GenericMeta): 1938 """Metaclass for Annotated""" 1939 1940 def __new__(cls, name, bases, namespace, **kwargs): 1941 if any(b is not object for b in bases): 1942 raise TypeError("Cannot subclass " + str(Annotated)) 1943 return super().__new__(cls, name, bases, namespace, **kwargs) 1944 1945 @property 1946 def __metadata__(self): 1947 return self._subs_tree()[2] 1948 1949 def _tree_repr(self, tree): 1950 cls, origin, metadata = tree 1951 if not isinstance(origin, tuple): 1952 tp_repr = typing._type_repr(origin) 1953 else: 1954 tp_repr = origin[0]._tree_repr(origin) 1955 metadata_reprs = ", ".join(repr(arg) for arg in metadata) 1956 return '%s[%s, %s]' % (cls, tp_repr, metadata_reprs) 1957 1958 def _subs_tree(self, tvars=None, args=None): # noqa 1959 if self is Annotated: 1960 return Annotated 1961 res = super()._subs_tree(tvars=tvars, args=args) 1962 # Flatten nested Annotated 1963 if isinstance(res[1], tuple) and res[1][0] is Annotated: 1964 sub_tp = res[1][1] 1965 sub_annot = res[1][2] 1966 return (Annotated, sub_tp, sub_annot + res[2]) 1967 return res 1968 1969 def _get_cons(self): 1970 """Return the class used to create instance of this type.""" 1971 if self.__origin__ is None: 1972 raise TypeError("Cannot get the underlying type of a " 1973 "non-specialized Annotated type.") 1974 tree = self._subs_tree() 1975 while isinstance(tree, tuple) and tree[0] is Annotated: 1976 tree = tree[1] 1977 if isinstance(tree, tuple): 1978 return tree[0] 1979 else: 1980 return tree 1981 1982 @_tp_cache 1983 def __getitem__(self, params): 1984 if not isinstance(params, tuple): 1985 params = (params,) 1986 if self.__origin__ is not None: # specializing an instantiated type 1987 return super().__getitem__(params) 1988 elif not isinstance(params, tuple) or len(params) < 2: 1989 raise TypeError("Annotated[...] should be instantiated " 1990 "with at least two arguments (a type and an " 1991 "annotation).") 1992 else: 1993 msg = "Annotated[t, ...]: t must be a type." 1994 tp = typing._type_check(params[0], msg) 1995 metadata = tuple(params[1:]) 1996 return self.__class__( 1997 self.__name__, 1998 self.__bases__, 1999 _no_slots_copy(self.__dict__), 2000 tvars=_type_vars((tp,)), 2001 # Metadata is a tuple so it won't be touched by _replace_args et al. 2002 args=(tp, metadata), 2003 origin=self, 2004 ) 2005 2006 def __call__(self, *args, **kwargs): 2007 cons = self._get_cons() 2008 result = cons(*args, **kwargs) 2009 try: 2010 result.__orig_class__ = self 2011 except AttributeError: 2012 pass 2013 return result 2014 2015 def __getattr__(self, attr): 2016 # For simplicity we just don't relay all dunder names 2017 if self.__origin__ is not None and not _is_dunder(attr): 2018 return getattr(self._get_cons(), attr) 2019 raise AttributeError(attr) 2020 2021 def __setattr__(self, attr, value): 2022 if _is_dunder(attr) or attr.startswith('_abc_'): 2023 super().__setattr__(attr, value) 2024 elif self.__origin__ is None: 2025 raise AttributeError(attr) 2026 else: 2027 setattr(self._get_cons(), attr, value) 2028 2029 def __instancecheck__(self, obj): 2030 raise TypeError("Annotated cannot be used with isinstance().") 2031 2032 def __subclasscheck__(self, cls): 2033 raise TypeError("Annotated cannot be used with issubclass().") 2034 2035 class Annotated(metaclass=AnnotatedMeta): 2036 """Add context specific metadata to a type. 2037 2038 Example: Annotated[int, runtime_check.Unsigned] indicates to the 2039 hypothetical runtime_check module that this type is an unsigned int. 2040 Every other consumer of this type can ignore this metadata and treat 2041 this type as int. 2042 2043 The first argument to Annotated must be a valid type, the remaining 2044 arguments are kept as a tuple in the __metadata__ field. 2045 2046 Details: 2047 2048 - It's an error to call `Annotated` with less than two arguments. 2049 - Nested Annotated are flattened:: 2050 2051 Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3] 2052 2053 - Instantiating an annotated type is equivalent to instantiating the 2054 underlying type:: 2055 2056 Annotated[C, Ann1](5) == C(5) 2057 2058 - Annotated can be used as a generic type alias:: 2059 2060 Optimized = Annotated[T, runtime.Optimize()] 2061 Optimized[int] == Annotated[int, runtime.Optimize()] 2062 2063 OptimizedList = Annotated[List[T], runtime.Optimize()] 2064 OptimizedList[int] == Annotated[List[int], runtime.Optimize()] 2065 """ 2066 2067# Python 3.8 has get_origin() and get_args() but those implementations aren't 2068# Annotated-aware, so we can't use those, only Python 3.9 versions will do. 2069# Similarly, Python 3.9's implementation doesn't support ParamSpecArgs and 2070# ParamSpecKwargs. 2071if sys.version_info[:2] >= (3, 10): 2072 get_origin = typing.get_origin 2073 get_args = typing.get_args 2074elif PEP_560: 2075 from typing import _GenericAlias 2076 try: 2077 # 3.9+ 2078 from typing import _BaseGenericAlias 2079 except ImportError: 2080 _BaseGenericAlias = _GenericAlias 2081 try: 2082 # 3.9+ 2083 from typing import GenericAlias 2084 except ImportError: 2085 GenericAlias = _GenericAlias 2086 2087 def get_origin(tp): 2088 """Get the unsubscripted version of a type. 2089 2090 This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar 2091 and Annotated. Return None for unsupported types. Examples:: 2092 2093 get_origin(Literal[42]) is Literal 2094 get_origin(int) is None 2095 get_origin(ClassVar[int]) is ClassVar 2096 get_origin(Generic) is Generic 2097 get_origin(Generic[T]) is Generic 2098 get_origin(Union[T, int]) is Union 2099 get_origin(List[Tuple[T, T]][int]) == list 2100 get_origin(P.args) is P 2101 """ 2102 if isinstance(tp, _AnnotatedAlias): 2103 return Annotated 2104 if isinstance(tp, (_GenericAlias, GenericAlias, _BaseGenericAlias, 2105 ParamSpecArgs, ParamSpecKwargs)): 2106 return tp.__origin__ 2107 if tp is Generic: 2108 return Generic 2109 return None 2110 2111 def get_args(tp): 2112 """Get type arguments with all substitutions performed. 2113 2114 For unions, basic simplifications used by Union constructor are performed. 2115 Examples:: 2116 get_args(Dict[str, int]) == (str, int) 2117 get_args(int) == () 2118 get_args(Union[int, Union[T, int], str][int]) == (int, str) 2119 get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int]) 2120 get_args(Callable[[], T][int]) == ([], int) 2121 """ 2122 if isinstance(tp, _AnnotatedAlias): 2123 return (tp.__origin__,) + tp.__metadata__ 2124 if isinstance(tp, (_GenericAlias, GenericAlias)): 2125 if getattr(tp, "_special", False): 2126 return () 2127 res = tp.__args__ 2128 if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis: 2129 res = (list(res[:-1]), res[-1]) 2130 return res 2131 return () 2132 2133 2134if hasattr(typing, 'TypeAlias'): 2135 TypeAlias = typing.TypeAlias 2136elif sys.version_info[:2] >= (3, 9): 2137 class _TypeAliasForm(typing._SpecialForm, _root=True): 2138 def __repr__(self): 2139 return 'typing_extensions.' + self._name 2140 2141 @_TypeAliasForm 2142 def TypeAlias(self, parameters): 2143 """Special marker indicating that an assignment should 2144 be recognized as a proper type alias definition by type 2145 checkers. 2146 2147 For example:: 2148 2149 Predicate: TypeAlias = Callable[..., bool] 2150 2151 It's invalid when used anywhere except as in the example above. 2152 """ 2153 raise TypeError("{} is not subscriptable".format(self)) 2154 2155elif sys.version_info[:2] >= (3, 7): 2156 class _TypeAliasForm(typing._SpecialForm, _root=True): 2157 def __repr__(self): 2158 return 'typing_extensions.' + self._name 2159 2160 TypeAlias = _TypeAliasForm('TypeAlias', 2161 doc="""Special marker indicating that an assignment should 2162 be recognized as a proper type alias definition by type 2163 checkers. 2164 2165 For example:: 2166 2167 Predicate: TypeAlias = Callable[..., bool] 2168 2169 It's invalid when used anywhere except as in the example 2170 above.""") 2171 2172elif hasattr(typing, '_FinalTypingBase'): 2173 class _TypeAliasMeta(typing.TypingMeta): 2174 """Metaclass for TypeAlias""" 2175 2176 def __repr__(self): 2177 return 'typing_extensions.TypeAlias' 2178 2179 class _TypeAliasBase(typing._FinalTypingBase, metaclass=_TypeAliasMeta, _root=True): 2180 """Special marker indicating that an assignment should 2181 be recognized as a proper type alias definition by type 2182 checkers. 2183 2184 For example:: 2185 2186 Predicate: TypeAlias = Callable[..., bool] 2187 2188 It's invalid when used anywhere except as in the example above. 2189 """ 2190 __slots__ = () 2191 2192 def __instancecheck__(self, obj): 2193 raise TypeError("TypeAlias cannot be used with isinstance().") 2194 2195 def __subclasscheck__(self, cls): 2196 raise TypeError("TypeAlias cannot be used with issubclass().") 2197 2198 def __repr__(self): 2199 return 'typing_extensions.TypeAlias' 2200 2201 TypeAlias = _TypeAliasBase(_root=True) 2202else: 2203 class _TypeAliasMeta(typing.TypingMeta): 2204 """Metaclass for TypeAlias""" 2205 2206 def __instancecheck__(self, obj): 2207 raise TypeError("TypeAlias cannot be used with isinstance().") 2208 2209 def __subclasscheck__(self, cls): 2210 raise TypeError("TypeAlias cannot be used with issubclass().") 2211 2212 def __call__(self, *args, **kwargs): 2213 raise TypeError("Cannot instantiate TypeAlias") 2214 2215 class TypeAlias(metaclass=_TypeAliasMeta, _root=True): 2216 """Special marker indicating that an assignment should 2217 be recognized as a proper type alias definition by type 2218 checkers. 2219 2220 For example:: 2221 2222 Predicate: TypeAlias = Callable[..., bool] 2223 2224 It's invalid when used anywhere except as in the example above. 2225 """ 2226 __slots__ = () 2227 2228 2229# Python 3.10+ has PEP 612 2230if hasattr(typing, 'ParamSpecArgs'): 2231 ParamSpecArgs = typing.ParamSpecArgs 2232 ParamSpecKwargs = typing.ParamSpecKwargs 2233else: 2234 class _Immutable: 2235 """Mixin to indicate that object should not be copied.""" 2236 __slots__ = () 2237 2238 def __copy__(self): 2239 return self 2240 2241 def __deepcopy__(self, memo): 2242 return self 2243 2244 class ParamSpecArgs(_Immutable): 2245 """The args for a ParamSpec object. 2246 2247 Given a ParamSpec object P, P.args is an instance of ParamSpecArgs. 2248 2249 ParamSpecArgs objects have a reference back to their ParamSpec: 2250 2251 P.args.__origin__ is P 2252 2253 This type is meant for runtime introspection and has no special meaning to 2254 static type checkers. 2255 """ 2256 def __init__(self, origin): 2257 self.__origin__ = origin 2258 2259 def __repr__(self): 2260 return "{}.args".format(self.__origin__.__name__) 2261 2262 class ParamSpecKwargs(_Immutable): 2263 """The kwargs for a ParamSpec object. 2264 2265 Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs. 2266 2267 ParamSpecKwargs objects have a reference back to their ParamSpec: 2268 2269 P.kwargs.__origin__ is P 2270 2271 This type is meant for runtime introspection and has no special meaning to 2272 static type checkers. 2273 """ 2274 def __init__(self, origin): 2275 self.__origin__ = origin 2276 2277 def __repr__(self): 2278 return "{}.kwargs".format(self.__origin__.__name__) 2279 2280if hasattr(typing, 'ParamSpec'): 2281 ParamSpec = typing.ParamSpec 2282else: 2283 2284 # Inherits from list as a workaround for Callable checks in Python < 3.9.2. 2285 class ParamSpec(list): 2286 """Parameter specification variable. 2287 2288 Usage:: 2289 2290 P = ParamSpec('P') 2291 2292 Parameter specification variables exist primarily for the benefit of static 2293 type checkers. They are used to forward the parameter types of one 2294 callable to another callable, a pattern commonly found in higher order 2295 functions and decorators. They are only valid when used in ``Concatenate``, 2296 or s the first argument to ``Callable``. In Python 3.10 and higher, 2297 they are also supported in user-defined Generics at runtime. 2298 See class Generic for more information on generic types. An 2299 example for annotating a decorator:: 2300 2301 T = TypeVar('T') 2302 P = ParamSpec('P') 2303 2304 def add_logging(f: Callable[P, T]) -> Callable[P, T]: 2305 '''A type-safe decorator to add logging to a function.''' 2306 def inner(*args: P.args, **kwargs: P.kwargs) -> T: 2307 logging.info(f'{f.__name__} was called') 2308 return f(*args, **kwargs) 2309 return inner 2310 2311 @add_logging 2312 def add_two(x: float, y: float) -> float: 2313 '''Add two numbers together.''' 2314 return x + y 2315 2316 Parameter specification variables defined with covariant=True or 2317 contravariant=True can be used to declare covariant or contravariant 2318 generic types. These keyword arguments are valid, but their actual semantics 2319 are yet to be decided. See PEP 612 for details. 2320 2321 Parameter specification variables can be introspected. e.g.: 2322 2323 P.__name__ == 'T' 2324 P.__bound__ == None 2325 P.__covariant__ == False 2326 P.__contravariant__ == False 2327 2328 Note that only parameter specification variables defined in global scope can 2329 be pickled. 2330 """ 2331 2332 @property 2333 def args(self): 2334 return ParamSpecArgs(self) 2335 2336 @property 2337 def kwargs(self): 2338 return ParamSpecKwargs(self) 2339 2340 def __init__(self, name, *, bound=None, covariant=False, contravariant=False): 2341 super().__init__([self]) 2342 self.__name__ = name 2343 self.__covariant__ = bool(covariant) 2344 self.__contravariant__ = bool(contravariant) 2345 if bound: 2346 self.__bound__ = typing._type_check(bound, 'Bound must be a type.') 2347 else: 2348 self.__bound__ = None 2349 2350 # for pickling: 2351 try: 2352 def_mod = sys._getframe(1).f_globals.get('__name__', '__main__') 2353 except (AttributeError, ValueError): 2354 def_mod = None 2355 if def_mod != 'typing_extensions': 2356 self.__module__ = def_mod 2357 2358 def __repr__(self): 2359 if self.__covariant__: 2360 prefix = '+' 2361 elif self.__contravariant__: 2362 prefix = '-' 2363 else: 2364 prefix = '~' 2365 return prefix + self.__name__ 2366 2367 def __hash__(self): 2368 return object.__hash__(self) 2369 2370 def __eq__(self, other): 2371 return self is other 2372 2373 def __reduce__(self): 2374 return self.__name__ 2375 2376 # Hack to get typing._type_check to pass. 2377 def __call__(self, *args, **kwargs): 2378 pass 2379 2380 # Note: Can't fake ParamSpec as a TypeVar to get it to work 2381 # with Generics. ParamSpec isn't an instance of TypeVar in 3.10. 2382 # So encouraging code like isinstance(ParamSpec('P'), TypeVar)) 2383 # will lead to breakage in 3.10. 2384 # This also means no accurate __parameters__ for GenericAliases. 2385 2386# Inherits from list as a workaround for Callable checks in Python < 3.9.2. 2387class _ConcatenateGenericAlias(list): 2388 def __init__(self, origin, args): 2389 super().__init__(args) 2390 self.__origin__ = origin 2391 self.__args__ = args 2392 2393 def __repr__(self): 2394 _type_repr = typing._type_repr 2395 return '{origin}[{args}]' \ 2396 .format(origin=_type_repr(self.__origin__), 2397 args=', '.join(_type_repr(arg) for arg in self.__args__)) 2398 2399 def __hash__(self): 2400 return hash((self.__origin__, self.__args__)) 2401 2402@_tp_cache 2403def _concatenate_getitem(self, parameters): 2404 if parameters == (): 2405 raise TypeError("Cannot take a Concatenate of no types.") 2406 if not isinstance(parameters, tuple): 2407 parameters = (parameters,) 2408 if not isinstance(parameters[-1], ParamSpec): 2409 raise TypeError("The last parameter to Concatenate should be a " 2410 "ParamSpec variable.") 2411 msg = "Concatenate[arg, ...]: each arg must be a type." 2412 parameters = tuple(typing._type_check(p, msg) for p in parameters) 2413 return _ConcatenateGenericAlias(self, parameters) 2414 2415 2416if hasattr(typing, 'Concatenate'): 2417 Concatenate = typing.Concatenate 2418 _ConcatenateGenericAlias = typing._ConcatenateGenericAlias # noqa 2419elif sys.version_info[:2] >= (3, 9): 2420 @_TypeAliasForm 2421 def Concatenate(self, parameters): 2422 """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a 2423 higher order function which adds, removes or transforms parameters of a 2424 callable. 2425 2426 For example:: 2427 2428 Callable[Concatenate[int, P], int] 2429 2430 See PEP 612 for detailed information. 2431 """ 2432 return _concatenate_getitem(self, parameters) 2433 2434elif sys.version_info[:2] >= (3, 7): 2435 class _ConcatenateForm(typing._SpecialForm, _root=True): 2436 def __repr__(self): 2437 return 'typing_extensions.' + self._name 2438 2439 def __getitem__(self, parameters): 2440 return _concatenate_getitem(self, parameters) 2441 2442 Concatenate = _ConcatenateForm('Concatenate', 2443 doc="""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a 2444 higher order function which adds, removes or transforms parameters of a 2445 callable. 2446 2447 For example:: 2448 2449 Callable[Concatenate[int, P], int] 2450 2451 See PEP 612 for detailed information. 2452 """) 2453 2454elif hasattr(typing, '_FinalTypingBase'): 2455 class _ConcatenateAliasMeta(typing.TypingMeta): 2456 """Metaclass for Concatenate.""" 2457 2458 def __repr__(self): 2459 return 'typing_extensions.Concatenate' 2460 2461 class _ConcatenateAliasBase(typing._FinalTypingBase, 2462 metaclass=_ConcatenateAliasMeta, 2463 _root=True): 2464 """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a 2465 higher order function which adds, removes or transforms parameters of a 2466 callable. 2467 2468 For example:: 2469 2470 Callable[Concatenate[int, P], int] 2471 2472 See PEP 612 for detailed information. 2473 """ 2474 __slots__ = () 2475 2476 def __instancecheck__(self, obj): 2477 raise TypeError("Concatenate cannot be used with isinstance().") 2478 2479 def __subclasscheck__(self, cls): 2480 raise TypeError("Concatenate cannot be used with issubclass().") 2481 2482 def __repr__(self): 2483 return 'typing_extensions.Concatenate' 2484 2485 def __getitem__(self, parameters): 2486 return _concatenate_getitem(self, parameters) 2487 2488 Concatenate = _ConcatenateAliasBase(_root=True) 2489# For 3.5.0 - 3.5.2 2490else: 2491 class _ConcatenateAliasMeta(typing.TypingMeta): 2492 """Metaclass for Concatenate.""" 2493 2494 def __instancecheck__(self, obj): 2495 raise TypeError("TypeAlias cannot be used with isinstance().") 2496 2497 def __subclasscheck__(self, cls): 2498 raise TypeError("TypeAlias cannot be used with issubclass().") 2499 2500 def __call__(self, *args, **kwargs): 2501 raise TypeError("Cannot instantiate TypeAlias") 2502 2503 def __getitem__(self, parameters): 2504 return _concatenate_getitem(self, parameters) 2505 2506 class Concatenate(metaclass=_ConcatenateAliasMeta, _root=True): 2507 """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a 2508 higher order function which adds, removes or transforms parameters of a 2509 callable. 2510 2511 For example:: 2512 2513 Callable[Concatenate[int, P], int] 2514 2515 See PEP 612 for detailed information. 2516 """ 2517 __slots__ = () 2518 2519if hasattr(typing, 'TypeGuard'): 2520 TypeGuard = typing.TypeGuard 2521elif sys.version_info[:2] >= (3, 9): 2522 class _TypeGuardForm(typing._SpecialForm, _root=True): 2523 def __repr__(self): 2524 return 'typing_extensions.' + self._name 2525 2526 @_TypeGuardForm 2527 def TypeGuard(self, parameters): 2528 """Special typing form used to annotate the return type of a user-defined 2529 type guard function. ``TypeGuard`` only accepts a single type argument. 2530 At runtime, functions marked this way should return a boolean. 2531 2532 ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static 2533 type checkers to determine a more precise type of an expression within a 2534 program's code flow. Usually type narrowing is done by analyzing 2535 conditional code flow and applying the narrowing to a block of code. The 2536 conditional expression here is sometimes referred to as a "type guard". 2537 2538 Sometimes it would be convenient to use a user-defined boolean function 2539 as a type guard. Such a function should use ``TypeGuard[...]`` as its 2540 return type to alert static type checkers to this intention. 2541 2542 Using ``-> TypeGuard`` tells the static type checker that for a given 2543 function: 2544 2545 1. The return value is a boolean. 2546 2. If the return value is ``True``, the type of its argument 2547 is the type inside ``TypeGuard``. 2548 2549 For example:: 2550 2551 def is_str(val: Union[str, float]): 2552 # "isinstance" type guard 2553 if isinstance(val, str): 2554 # Type of ``val`` is narrowed to ``str`` 2555 ... 2556 else: 2557 # Else, type of ``val`` is narrowed to ``float``. 2558 ... 2559 2560 Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower 2561 form of ``TypeA`` (it can even be a wider form) and this may lead to 2562 type-unsafe results. The main reason is to allow for things like 2563 narrowing ``List[object]`` to ``List[str]`` even though the latter is not 2564 a subtype of the former, since ``List`` is invariant. The responsibility of 2565 writing type-safe type guards is left to the user. 2566 2567 ``TypeGuard`` also works with type variables. For more information, see 2568 PEP 647 (User-Defined Type Guards). 2569 """ 2570 item = typing._type_check(parameters, '{} accepts only single type.'.format(self)) 2571 return _GenericAlias(self, (item,)) 2572 2573elif sys.version_info[:2] >= (3, 7): 2574 class _TypeGuardForm(typing._SpecialForm, _root=True): 2575 2576 def __repr__(self): 2577 return 'typing_extensions.' + self._name 2578 2579 def __getitem__(self, parameters): 2580 item = typing._type_check(parameters, 2581 '{} accepts only a single type'.format(self._name)) 2582 return _GenericAlias(self, (item,)) 2583 2584 TypeGuard = _TypeGuardForm( 2585 'TypeGuard', 2586 doc="""Special typing form used to annotate the return type of a user-defined 2587 type guard function. ``TypeGuard`` only accepts a single type argument. 2588 At runtime, functions marked this way should return a boolean. 2589 2590 ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static 2591 type checkers to determine a more precise type of an expression within a 2592 program's code flow. Usually type narrowing is done by analyzing 2593 conditional code flow and applying the narrowing to a block of code. The 2594 conditional expression here is sometimes referred to as a "type guard". 2595 2596 Sometimes it would be convenient to use a user-defined boolean function 2597 as a type guard. Such a function should use ``TypeGuard[...]`` as its 2598 return type to alert static type checkers to this intention. 2599 2600 Using ``-> TypeGuard`` tells the static type checker that for a given 2601 function: 2602 2603 1. The return value is a boolean. 2604 2. If the return value is ``True``, the type of its argument 2605 is the type inside ``TypeGuard``. 2606 2607 For example:: 2608 2609 def is_str(val: Union[str, float]): 2610 # "isinstance" type guard 2611 if isinstance(val, str): 2612 # Type of ``val`` is narrowed to ``str`` 2613 ... 2614 else: 2615 # Else, type of ``val`` is narrowed to ``float``. 2616 ... 2617 2618 Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower 2619 form of ``TypeA`` (it can even be a wider form) and this may lead to 2620 type-unsafe results. The main reason is to allow for things like 2621 narrowing ``List[object]`` to ``List[str]`` even though the latter is not 2622 a subtype of the former, since ``List`` is invariant. The responsibility of 2623 writing type-safe type guards is left to the user. 2624 2625 ``TypeGuard`` also works with type variables. For more information, see 2626 PEP 647 (User-Defined Type Guards). 2627 """) 2628elif hasattr(typing, '_FinalTypingBase'): 2629 class _TypeGuard(typing._FinalTypingBase, _root=True): 2630 """Special typing form used to annotate the return type of a user-defined 2631 type guard function. ``TypeGuard`` only accepts a single type argument. 2632 At runtime, functions marked this way should return a boolean. 2633 2634 ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static 2635 type checkers to determine a more precise type of an expression within a 2636 program's code flow. Usually type narrowing is done by analyzing 2637 conditional code flow and applying the narrowing to a block of code. The 2638 conditional expression here is sometimes referred to as a "type guard". 2639 2640 Sometimes it would be convenient to use a user-defined boolean function 2641 as a type guard. Such a function should use ``TypeGuard[...]`` as its 2642 return type to alert static type checkers to this intention. 2643 2644 Using ``-> TypeGuard`` tells the static type checker that for a given 2645 function: 2646 2647 1. The return value is a boolean. 2648 2. If the return value is ``True``, the type of its argument 2649 is the type inside ``TypeGuard``. 2650 2651 For example:: 2652 2653 def is_str(val: Union[str, float]): 2654 # "isinstance" type guard 2655 if isinstance(val, str): 2656 # Type of ``val`` is narrowed to ``str`` 2657 ... 2658 else: 2659 # Else, type of ``val`` is narrowed to ``float``. 2660 ... 2661 2662 Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower 2663 form of ``TypeA`` (it can even be a wider form) and this may lead to 2664 type-unsafe results. The main reason is to allow for things like 2665 narrowing ``List[object]`` to ``List[str]`` even though the latter is not 2666 a subtype of the former, since ``List`` is invariant. The responsibility of 2667 writing type-safe type guards is left to the user. 2668 2669 ``TypeGuard`` also works with type variables. For more information, see 2670 PEP 647 (User-Defined Type Guards). 2671 """ 2672 2673 __slots__ = ('__type__',) 2674 2675 def __init__(self, tp=None, **kwds): 2676 self.__type__ = tp 2677 2678 def __getitem__(self, item): 2679 cls = type(self) 2680 if self.__type__ is None: 2681 return cls(typing._type_check(item, 2682 '{} accepts only a single type.'.format(cls.__name__[1:])), 2683 _root=True) 2684 raise TypeError('{} cannot be further subscripted' 2685 .format(cls.__name__[1:])) 2686 2687 def _eval_type(self, globalns, localns): 2688 new_tp = typing._eval_type(self.__type__, globalns, localns) 2689 if new_tp == self.__type__: 2690 return self 2691 return type(self)(new_tp, _root=True) 2692 2693 def __repr__(self): 2694 r = super().__repr__() 2695 if self.__type__ is not None: 2696 r += '[{}]'.format(typing._type_repr(self.__type__)) 2697 return r 2698 2699 def __hash__(self): 2700 return hash((type(self).__name__, self.__type__)) 2701 2702 def __eq__(self, other): 2703 if not isinstance(other, _TypeGuard): 2704 return NotImplemented 2705 if self.__type__ is not None: 2706 return self.__type__ == other.__type__ 2707 return self is other 2708 2709 TypeGuard = _TypeGuard(_root=True) 2710else: 2711 class _TypeGuardMeta(typing.TypingMeta): 2712 """Metaclass for TypeGuard""" 2713 2714 def __new__(cls, name, bases, namespace, tp=None, _root=False): 2715 self = super().__new__(cls, name, bases, namespace, _root=_root) 2716 if tp is not None: 2717 self.__type__ = tp 2718 return self 2719 2720 def __instancecheck__(self, obj): 2721 raise TypeError("TypeGuard cannot be used with isinstance().") 2722 2723 def __subclasscheck__(self, cls): 2724 raise TypeError("TypeGuard cannot be used with issubclass().") 2725 2726 def __getitem__(self, item): 2727 cls = type(self) 2728 if self.__type__ is not None: 2729 raise TypeError('{} cannot be further subscripted' 2730 .format(cls.__name__[1:])) 2731 2732 param = typing._type_check( 2733 item, 2734 '{} accepts only single type.'.format(cls.__name__[1:])) 2735 return cls(self.__name__, self.__bases__, 2736 dict(self.__dict__), tp=param, _root=True) 2737 2738 def _eval_type(self, globalns, localns): 2739 new_tp = typing._eval_type(self.__type__, globalns, localns) 2740 if new_tp == self.__type__: 2741 return self 2742 return type(self)(self.__name__, self.__bases__, 2743 dict(self.__dict__), tp=self.__type__, 2744 _root=True) 2745 2746 def __repr__(self): 2747 r = super().__repr__() 2748 if self.__type__ is not None: 2749 r += '[{}]'.format(typing._type_repr(self.__type__)) 2750 return r 2751 2752 def __hash__(self): 2753 return hash((type(self).__name__, self.__type__)) 2754 2755 def __eq__(self, other): 2756 if not hasattr(other, "__type__"): 2757 return NotImplemented 2758 if self.__type__ is not None: 2759 return self.__type__ == other.__type__ 2760 return self is other 2761 2762 class TypeGuard(typing.Final, metaclass=_TypeGuardMeta, _root=True): 2763 """Special typing form used to annotate the return type of a user-defined 2764 type guard function. ``TypeGuard`` only accepts a single type argument. 2765 At runtime, functions marked this way should return a boolean. 2766 2767 ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static 2768 type checkers to determine a more precise type of an expression within a 2769 program's code flow. Usually type narrowing is done by analyzing 2770 conditional code flow and applying the narrowing to a block of code. The 2771 conditional expression here is sometimes referred to as a "type guard". 2772 2773 Sometimes it would be convenient to use a user-defined boolean function 2774 as a type guard. Such a function should use ``TypeGuard[...]`` as its 2775 return type to alert static type checkers to this intention. 2776 2777 Using ``-> TypeGuard`` tells the static type checker that for a given 2778 function: 2779 2780 1. The return value is a boolean. 2781 2. If the return value is ``True``, the type of its argument 2782 is the type inside ``TypeGuard``. 2783 2784 For example:: 2785 2786 def is_str(val: Union[str, float]): 2787 # "isinstance" type guard 2788 if isinstance(val, str): 2789 # Type of ``val`` is narrowed to ``str`` 2790 ... 2791 else: 2792 # Else, type of ``val`` is narrowed to ``float``. 2793 ... 2794 2795 Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower 2796 form of ``TypeA`` (it can even be a wider form) and this may lead to 2797 type-unsafe results. The main reason is to allow for things like 2798 narrowing ``List[object]`` to ``List[str]`` even though the latter is not 2799 a subtype of the former, since ``List`` is invariant. The responsibility of 2800 writing type-safe type guards is left to the user. 2801 2802 ``TypeGuard`` also works with type variables. For more information, see 2803 PEP 647 (User-Defined Type Guards). 2804 """ 2805 __type__ = None 2806