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