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