1======================================== 2:mod:`typing` --- Support for type hints 3======================================== 4 5.. module:: typing 6 :synopsis: Support for type hints (see :pep:`484`). 7 8.. versionadded:: 3.5 9 10**Source code:** :source:`Lib/typing.py` 11 12.. note:: 13 14 The Python runtime does not enforce function and variable type annotations. 15 They can be used by third party tools such as type checkers, IDEs, linters, 16 etc. 17 18-------------- 19 20This module provides runtime support for type hints as specified by 21:pep:`484`, :pep:`526`, :pep:`544`, :pep:`586`, :pep:`589`, and :pep:`591`. 22The most fundamental support consists of the types :data:`Any`, :data:`Union`, 23:data:`Tuple`, :data:`Callable`, :class:`TypeVar`, and 24:class:`Generic`. For full specification please see :pep:`484`. For 25a simplified introduction to type hints see :pep:`483`. 26 27 28The function below takes and returns a string and is annotated as follows:: 29 30 def greeting(name: str) -> str: 31 return 'Hello ' + name 32 33In the function ``greeting``, the argument ``name`` is expected to be of type 34:class:`str` and the return type :class:`str`. Subtypes are accepted as 35arguments. 36 37Type aliases 38============ 39 40A type alias is defined by assigning the type to the alias. In this example, 41``Vector`` and ``list[float]`` will be treated as interchangeable synonyms:: 42 43 Vector = list[float] 44 45 def scale(scalar: float, vector: Vector) -> Vector: 46 return [scalar * num for num in vector] 47 48 # typechecks; a list of floats qualifies as a Vector. 49 new_vector = scale(2.0, [1.0, -4.2, 5.4]) 50 51Type aliases are useful for simplifying complex type signatures. For example:: 52 53 from collections.abc import Sequence 54 55 ConnectionOptions = dict[str, str] 56 Address = tuple[str, int] 57 Server = tuple[Address, ConnectionOptions] 58 59 def broadcast_message(message: str, servers: Sequence[Server]) -> None: 60 ... 61 62 # The static type checker will treat the previous type signature as 63 # being exactly equivalent to this one. 64 def broadcast_message( 65 message: str, 66 servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: 67 ... 68 69Note that ``None`` as a type hint is a special case and is replaced by 70``type(None)``. 71 72.. _distinct: 73 74NewType 75======= 76 77Use the :func:`NewType` helper function to create distinct types:: 78 79 from typing import NewType 80 81 UserId = NewType('UserId', int) 82 some_id = UserId(524313) 83 84The static type checker will treat the new type as if it were a subclass 85of the original type. This is useful in helping catch logical errors:: 86 87 def get_user_name(user_id: UserId) -> str: 88 ... 89 90 # typechecks 91 user_a = get_user_name(UserId(42351)) 92 93 # does not typecheck; an int is not a UserId 94 user_b = get_user_name(-1) 95 96You may still perform all ``int`` operations on a variable of type ``UserId``, 97but the result will always be of type ``int``. This lets you pass in a 98``UserId`` wherever an ``int`` might be expected, but will prevent you from 99accidentally creating a ``UserId`` in an invalid way:: 100 101 # 'output' is of type 'int', not 'UserId' 102 output = UserId(23413) + UserId(54341) 103 104Note that these checks are enforced only by the static type checker. At runtime, 105the statement ``Derived = NewType('Derived', Base)`` will make ``Derived`` a 106function that immediately returns whatever parameter you pass it. That means 107the expression ``Derived(some_value)`` does not create a new class or introduce 108any overhead beyond that of a regular function call. 109 110More precisely, the expression ``some_value is Derived(some_value)`` is always 111true at runtime. 112 113This also means that it is not possible to create a subtype of ``Derived`` 114since it is an identity function at runtime, not an actual type:: 115 116 from typing import NewType 117 118 UserId = NewType('UserId', int) 119 120 # Fails at runtime and does not typecheck 121 class AdminUserId(UserId): pass 122 123However, it is possible to create a :func:`NewType` based on a 'derived' ``NewType``:: 124 125 from typing import NewType 126 127 UserId = NewType('UserId', int) 128 129 ProUserId = NewType('ProUserId', UserId) 130 131and typechecking for ``ProUserId`` will work as expected. 132 133See :pep:`484` for more details. 134 135.. note:: 136 137 Recall that the use of a type alias declares two types to be *equivalent* to 138 one another. Doing ``Alias = Original`` will make the static type checker 139 treat ``Alias`` as being *exactly equivalent* to ``Original`` in all cases. 140 This is useful when you want to simplify complex type signatures. 141 142 In contrast, ``NewType`` declares one type to be a *subtype* of another. 143 Doing ``Derived = NewType('Derived', Original)`` will make the static type 144 checker treat ``Derived`` as a *subclass* of ``Original``, which means a 145 value of type ``Original`` cannot be used in places where a value of type 146 ``Derived`` is expected. This is useful when you want to prevent logic 147 errors with minimal runtime cost. 148 149.. versionadded:: 3.5.2 150 151Callable 152======== 153 154Frameworks expecting callback functions of specific signatures might be 155type hinted using ``Callable[[Arg1Type, Arg2Type], ReturnType]``. 156 157For example:: 158 159 from collections.abc import Callable 160 161 def feeder(get_next_item: Callable[[], str]) -> None: 162 # Body 163 164 def async_query(on_success: Callable[[int], None], 165 on_error: Callable[[int, Exception], None]) -> None: 166 # Body 167 168It is possible to declare the return type of a callable without specifying 169the call signature by substituting a literal ellipsis 170for the list of arguments in the type hint: ``Callable[..., ReturnType]``. 171 172.. _generics: 173 174Generics 175======== 176 177Since type information about objects kept in containers cannot be statically 178inferred in a generic way, abstract base classes have been extended to support 179subscription to denote expected types for container elements. 180 181:: 182 183 from collections.abc import Mapping, Sequence 184 185 def notify_by_email(employees: Sequence[Employee], 186 overrides: Mapping[str, str]) -> None: ... 187 188Generics can be parameterized by using a new factory available in typing 189called :class:`TypeVar`. 190 191:: 192 193 from collections.abc import Sequence 194 from typing import TypeVar 195 196 T = TypeVar('T') # Declare type variable 197 198 def first(l: Sequence[T]) -> T: # Generic function 199 return l[0] 200 201 202User-defined generic types 203========================== 204 205A user-defined class can be defined as a generic class. 206 207:: 208 209 from typing import TypeVar, Generic 210 from logging import Logger 211 212 T = TypeVar('T') 213 214 class LoggedVar(Generic[T]): 215 def __init__(self, value: T, name: str, logger: Logger) -> None: 216 self.name = name 217 self.logger = logger 218 self.value = value 219 220 def set(self, new: T) -> None: 221 self.log('Set ' + repr(self.value)) 222 self.value = new 223 224 def get(self) -> T: 225 self.log('Get ' + repr(self.value)) 226 return self.value 227 228 def log(self, message: str) -> None: 229 self.logger.info('%s: %s', self.name, message) 230 231``Generic[T]`` as a base class defines that the class ``LoggedVar`` takes a 232single type parameter ``T`` . This also makes ``T`` valid as a type within the 233class body. 234 235The :class:`Generic` base class defines :meth:`__class_getitem__` so that 236``LoggedVar[t]`` is valid as a type:: 237 238 from collections.abc import Iterable 239 240 def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None: 241 for var in vars: 242 var.set(0) 243 244A generic type can have any number of type variables, and type variables may 245be constrained:: 246 247 from typing import TypeVar, Generic 248 ... 249 250 T = TypeVar('T') 251 S = TypeVar('S', int, str) 252 253 class StrangePair(Generic[T, S]): 254 ... 255 256Each type variable argument to :class:`Generic` must be distinct. 257This is thus invalid:: 258 259 from typing import TypeVar, Generic 260 ... 261 262 T = TypeVar('T') 263 264 class Pair(Generic[T, T]): # INVALID 265 ... 266 267You can use multiple inheritance with :class:`Generic`:: 268 269 from collections.abc import Sized 270 from typing import TypeVar, Generic 271 272 T = TypeVar('T') 273 274 class LinkedList(Sized, Generic[T]): 275 ... 276 277When inheriting from generic classes, some type variables could be fixed:: 278 279 from collections.abc import Mapping 280 from typing import TypeVar 281 282 T = TypeVar('T') 283 284 class MyDict(Mapping[str, T]): 285 ... 286 287In this case ``MyDict`` has a single parameter, ``T``. 288 289Using a generic class without specifying type parameters assumes 290:data:`Any` for each position. In the following example, ``MyIterable`` is 291not generic but implicitly inherits from ``Iterable[Any]``:: 292 293 from collections.abc import Iterable 294 295 class MyIterable(Iterable): # Same as Iterable[Any] 296 297User defined generic type aliases are also supported. Examples:: 298 299 from collections.abc import Iterable 300 from typing import TypeVar, Union 301 S = TypeVar('S') 302 Response = Union[Iterable[S], int] 303 304 # Return type here is same as Union[Iterable[str], int] 305 def response(query: str) -> Response[str]: 306 ... 307 308 T = TypeVar('T', int, float, complex) 309 Vec = Iterable[tuple[T, T]] 310 311 def inproduct(v: Vec[T]) -> T: # Same as Iterable[tuple[T, T]] 312 return sum(x*y for x, y in v) 313 314.. versionchanged:: 3.7 315 :class:`Generic` no longer has a custom metaclass. 316 317A user-defined generic class can have ABCs as base classes without a metaclass 318conflict. Generic metaclasses are not supported. The outcome of parameterizing 319generics is cached, and most types in the typing module are hashable and 320comparable for equality. 321 322 323The :data:`Any` type 324==================== 325 326A special kind of type is :data:`Any`. A static type checker will treat 327every type as being compatible with :data:`Any` and :data:`Any` as being 328compatible with every type. 329 330This means that it is possible to perform any operation or method call on a 331value of type :data:`Any` and assign it to any variable:: 332 333 from typing import Any 334 335 a = None # type: Any 336 a = [] # OK 337 a = 2 # OK 338 339 s = '' # type: str 340 s = a # OK 341 342 def foo(item: Any) -> int: 343 # Typechecks; 'item' could be any type, 344 # and that type might have a 'bar' method 345 item.bar() 346 ... 347 348Notice that no typechecking is performed when assigning a value of type 349:data:`Any` to a more precise type. For example, the static type checker did 350not report an error when assigning ``a`` to ``s`` even though ``s`` was 351declared to be of type :class:`str` and receives an :class:`int` value at 352runtime! 353 354Furthermore, all functions without a return type or parameter types will 355implicitly default to using :data:`Any`:: 356 357 def legacy_parser(text): 358 ... 359 return data 360 361 # A static type checker will treat the above 362 # as having the same signature as: 363 def legacy_parser(text: Any) -> Any: 364 ... 365 return data 366 367This behavior allows :data:`Any` to be used as an *escape hatch* when you 368need to mix dynamically and statically typed code. 369 370Contrast the behavior of :data:`Any` with the behavior of :class:`object`. 371Similar to :data:`Any`, every type is a subtype of :class:`object`. However, 372unlike :data:`Any`, the reverse is not true: :class:`object` is *not* a 373subtype of every other type. 374 375That means when the type of a value is :class:`object`, a type checker will 376reject almost all operations on it, and assigning it to a variable (or using 377it as a return value) of a more specialized type is a type error. For example:: 378 379 def hash_a(item: object) -> int: 380 # Fails; an object does not have a 'magic' method. 381 item.magic() 382 ... 383 384 def hash_b(item: Any) -> int: 385 # Typechecks 386 item.magic() 387 ... 388 389 # Typechecks, since ints and strs are subclasses of object 390 hash_a(42) 391 hash_a("foo") 392 393 # Typechecks, since Any is compatible with all types 394 hash_b(42) 395 hash_b("foo") 396 397Use :class:`object` to indicate that a value could be any type in a typesafe 398manner. Use :data:`Any` to indicate that a value is dynamically typed. 399 400 401Nominal vs structural subtyping 402=============================== 403 404Initially :pep:`484` defined Python static type system as using 405*nominal subtyping*. This means that a class ``A`` is allowed where 406a class ``B`` is expected if and only if ``A`` is a subclass of ``B``. 407 408This requirement previously also applied to abstract base classes, such as 409:class:`~collections.abc.Iterable`. The problem with this approach is that a class had 410to be explicitly marked to support them, which is unpythonic and unlike 411what one would normally do in idiomatic dynamically typed Python code. 412For example, this conforms to :pep:`484`:: 413 414 from collections.abc import Sized, Iterable, Iterator 415 416 class Bucket(Sized, Iterable[int]): 417 ... 418 def __len__(self) -> int: ... 419 def __iter__(self) -> Iterator[int]: ... 420 421:pep:`544` allows to solve this problem by allowing users to write 422the above code without explicit base classes in the class definition, 423allowing ``Bucket`` to be implicitly considered a subtype of both ``Sized`` 424and ``Iterable[int]`` by static type checkers. This is known as 425*structural subtyping* (or static duck-typing):: 426 427 from collections.abc import Iterator, Iterable 428 429 class Bucket: # Note: no base classes 430 ... 431 def __len__(self) -> int: ... 432 def __iter__(self) -> Iterator[int]: ... 433 434 def collect(items: Iterable[int]) -> int: ... 435 result = collect(Bucket()) # Passes type check 436 437Moreover, by subclassing a special class :class:`Protocol`, a user 438can define new custom protocols to fully enjoy structural subtyping 439(see examples below). 440 441Module contents 442=============== 443 444The module defines the following classes, functions and decorators. 445 446.. note:: 447 448 This module defines several types that are subclasses of pre-existing 449 standard library classes which also extend :class:`Generic` 450 to support type variables inside ``[]``. 451 These types became redundant in Python 3.9 when the 452 corresponding pre-existing classes were enhanced to support ``[]``. 453 454 The redundant types are deprecated as of Python 3.9 but no 455 deprecation warnings will be issued by the interpreter. 456 It is expected that type checkers will flag the deprecated types 457 when the checked program targets Python 3.9 or newer. 458 459 The deprecated types will be removed from the :mod:`typing` module 460 in the first Python version released 5 years after the release of Python 3.9.0. 461 See details in :pep:`585`—*Type Hinting Generics In Standard Collections*. 462 463 464Special typing primitives 465------------------------- 466 467Special types 468""""""""""""" 469 470These can be used as types in annotations and do not support ``[]``. 471 472.. data:: Any 473 474 Special type indicating an unconstrained type. 475 476 * Every type is compatible with :data:`Any`. 477 * :data:`Any` is compatible with every type. 478 479.. data:: NoReturn 480 481 Special type indicating that a function never returns. 482 For example:: 483 484 from typing import NoReturn 485 486 def stop() -> NoReturn: 487 raise RuntimeError('no way') 488 489 .. versionadded:: 3.5.4 490 .. versionadded:: 3.6.2 491 492Special forms 493""""""""""""" 494 495These can be used as types in annotations using ``[]``, each having a unique syntax. 496 497.. data:: Tuple 498 499 Tuple type; ``Tuple[X, Y]`` is the type of a tuple of two items 500 with the first item of type X and the second of type Y. The type of 501 the empty tuple can be written as ``Tuple[()]``. 502 503 Example: ``Tuple[T1, T2]`` is a tuple of two elements corresponding 504 to type variables T1 and T2. ``Tuple[int, float, str]`` is a tuple 505 of an int, a float and a string. 506 507 To specify a variable-length tuple of homogeneous type, 508 use literal ellipsis, e.g. ``Tuple[int, ...]``. A plain :data:`Tuple` 509 is equivalent to ``Tuple[Any, ...]``, and in turn to :class:`tuple`. 510 511 .. deprecated:: 3.9 512 :class:`builtins.tuple <tuple>` now supports ``[]``. See :pep:`585` and 513 :ref:`types-genericalias`. 514 515.. data:: Union 516 517 Union type; ``Union[X, Y]`` means either X or Y. 518 519 To define a union, use e.g. ``Union[int, str]``. Details: 520 521 * The arguments must be types and there must be at least one. 522 523 * Unions of unions are flattened, e.g.:: 524 525 Union[Union[int, str], float] == Union[int, str, float] 526 527 * Unions of a single argument vanish, e.g.:: 528 529 Union[int] == int # The constructor actually returns int 530 531 * Redundant arguments are skipped, e.g.:: 532 533 Union[int, str, int] == Union[int, str] 534 535 * When comparing unions, the argument order is ignored, e.g.:: 536 537 Union[int, str] == Union[str, int] 538 539 * You cannot subclass or instantiate a union. 540 541 * You cannot write ``Union[X][Y]``. 542 543 * You can use ``Optional[X]`` as a shorthand for ``Union[X, None]``. 544 545 .. versionchanged:: 3.7 546 Don't remove explicit subclasses from unions at runtime. 547 548.. data:: Optional 549 550 Optional type. 551 552 ``Optional[X]`` is equivalent to ``Union[X, None]``. 553 554 Note that this is not the same concept as an optional argument, 555 which is one that has a default. An optional argument with a 556 default does not require the ``Optional`` qualifier on its type 557 annotation just because it is optional. For example:: 558 559 def foo(arg: int = 0) -> None: 560 ... 561 562 On the other hand, if an explicit value of ``None`` is allowed, the 563 use of ``Optional`` is appropriate, whether the argument is optional 564 or not. For example:: 565 566 def foo(arg: Optional[int] = None) -> None: 567 ... 568 569.. data:: Callable 570 571 Callable type; ``Callable[[int], str]`` is a function of (int) -> str. 572 573 The subscription syntax must always be used with exactly two 574 values: the argument list and the return type. The argument list 575 must be a list of types or an ellipsis; the return type must be 576 a single type. 577 578 There is no syntax to indicate optional or keyword arguments; 579 such function types are rarely used as callback types. 580 ``Callable[..., ReturnType]`` (literal ellipsis) can be used to 581 type hint a callable taking any number of arguments and returning 582 ``ReturnType``. A plain :data:`Callable` is equivalent to 583 ``Callable[..., Any]``, and in turn to 584 :class:`collections.abc.Callable`. 585 586 .. deprecated:: 3.9 587 :class:`collections.abc.Callable` now supports ``[]``. See :pep:`585` and 588 :ref:`types-genericalias`. 589 590.. class:: Type(Generic[CT_co]) 591 592 A variable annotated with ``C`` may accept a value of type ``C``. In 593 contrast, a variable annotated with ``Type[C]`` may accept values that are 594 classes themselves -- specifically, it will accept the *class object* of 595 ``C``. For example:: 596 597 a = 3 # Has type 'int' 598 b = int # Has type 'Type[int]' 599 c = type(a) # Also has type 'Type[int]' 600 601 Note that ``Type[C]`` is covariant:: 602 603 class User: ... 604 class BasicUser(User): ... 605 class ProUser(User): ... 606 class TeamUser(User): ... 607 608 # Accepts User, BasicUser, ProUser, TeamUser, ... 609 def make_new_user(user_class: Type[User]) -> User: 610 # ... 611 return user_class() 612 613 The fact that ``Type[C]`` is covariant implies that all subclasses of 614 ``C`` should implement the same constructor signature and class method 615 signatures as ``C``. The type checker should flag violations of this, 616 but should also allow constructor calls in subclasses that match the 617 constructor calls in the indicated base class. How the type checker is 618 required to handle this particular case may change in future revisions of 619 :pep:`484`. 620 621 The only legal parameters for :class:`Type` are classes, :data:`Any`, 622 :ref:`type variables <generics>`, and unions of any of these types. 623 For example:: 624 625 def new_non_team_user(user_class: Type[Union[BasicUser, ProUser]]): ... 626 627 ``Type[Any]`` is equivalent to ``Type`` which in turn is equivalent 628 to ``type``, which is the root of Python's metaclass hierarchy. 629 630 .. versionadded:: 3.5.2 631 632 .. deprecated:: 3.9 633 :class:`builtins.type <type>` now supports ``[]``. See :pep:`585` and 634 :ref:`types-genericalias`. 635 636.. data:: Literal 637 638 A type that can be used to indicate to type checkers that the 639 corresponding variable or function parameter has a value equivalent to 640 the provided literal (or one of several literals). For example:: 641 642 def validate_simple(data: Any) -> Literal[True]: # always returns True 643 ... 644 645 MODE = Literal['r', 'rb', 'w', 'wb'] 646 def open_helper(file: str, mode: MODE) -> str: 647 ... 648 649 open_helper('/some/path', 'r') # Passes type check 650 open_helper('/other/path', 'typo') # Error in type checker 651 652 ``Literal[...]`` cannot be subclassed. At runtime, an arbitrary value 653 is allowed as type argument to ``Literal[...]``, but type checkers may 654 impose restrictions. See :pep:`586` for more details about literal types. 655 656 .. versionadded:: 3.8 657 658 .. versionchanged:: 3.9.1 659 ``Literal`` now de-duplicates parameters. Equality comparison of 660 ``Literal`` objects are no longer order dependent. ``Literal`` objects 661 will now raise a :exc:`TypeError` exception during equality comparisons 662 if one of their parameters are not :term:`immutable`. 663 664.. data:: ClassVar 665 666 Special type construct to mark class variables. 667 668 As introduced in :pep:`526`, a variable annotation wrapped in ClassVar 669 indicates that a given attribute is intended to be used as a class variable 670 and should not be set on instances of that class. Usage:: 671 672 class Starship: 673 stats: ClassVar[dict[str, int]] = {} # class variable 674 damage: int = 10 # instance variable 675 676 :data:`ClassVar` accepts only types and cannot be further subscribed. 677 678 :data:`ClassVar` is not a class itself, and should not 679 be used with :func:`isinstance` or :func:`issubclass`. 680 :data:`ClassVar` does not change Python runtime behavior, but 681 it can be used by third-party type checkers. For example, a type checker 682 might flag the following code as an error:: 683 684 enterprise_d = Starship(3000) 685 enterprise_d.stats = {} # Error, setting class variable on instance 686 Starship.stats = {} # This is OK 687 688 .. versionadded:: 3.5.3 689 690.. data:: Final 691 692 A special typing construct to indicate to type checkers that a name 693 cannot be re-assigned or overridden in a subclass. For example:: 694 695 MAX_SIZE: Final = 9000 696 MAX_SIZE += 1 # Error reported by type checker 697 698 class Connection: 699 TIMEOUT: Final[int] = 10 700 701 class FastConnector(Connection): 702 TIMEOUT = 1 # Error reported by type checker 703 704 There is no runtime checking of these properties. See :pep:`591` for 705 more details. 706 707 .. versionadded:: 3.8 708 709.. data:: Annotated 710 711 A type, introduced in :pep:`593` (``Flexible function and variable 712 annotations``), to decorate existing types with context-specific metadata 713 (possibly multiple pieces of it, as ``Annotated`` is variadic). 714 Specifically, a type ``T`` can be annotated with metadata ``x`` via the 715 typehint ``Annotated[T, x]``. This metadata can be used for either static 716 analysis or at runtime. If a library (or tool) encounters a typehint 717 ``Annotated[T, x]`` and has no special logic for metadata ``x``, it 718 should ignore it and simply treat the type as ``T``. Unlike the 719 ``no_type_check`` functionality that currently exists in the ``typing`` 720 module which completely disables typechecking annotations on a function 721 or a class, the ``Annotated`` type allows for both static typechecking 722 of ``T`` (e.g., via mypy or Pyre, which can safely ignore ``x``) 723 together with runtime access to ``x`` within a specific application. 724 725 Ultimately, the responsibility of how to interpret the annotations (if 726 at all) is the responsibility of the tool or library encountering the 727 ``Annotated`` type. A tool or library encountering an ``Annotated`` type 728 can scan through the annotations to determine if they are of interest 729 (e.g., using ``isinstance()``). 730 731 When a tool or a library does not support annotations or encounters an 732 unknown annotation it should just ignore it and treat annotated type as 733 the underlying type. 734 735 It's up to the tool consuming the annotations to decide whether the 736 client is allowed to have several annotations on one type and how to 737 merge those annotations. 738 739 Since the ``Annotated`` type allows you to put several annotations of 740 the same (or different) type(s) on any node, the tools or libraries 741 consuming those annotations are in charge of dealing with potential 742 duplicates. For example, if you are doing value range analysis you might 743 allow this:: 744 745 T1 = Annotated[int, ValueRange(-10, 5)] 746 T2 = Annotated[T1, ValueRange(-20, 3)] 747 748 Passing ``include_extras=True`` to :func:`get_type_hints` lets one 749 access the extra annotations at runtime. 750 751 The details of the syntax: 752 753 * The first argument to ``Annotated`` must be a valid type 754 755 * Multiple type annotations are supported (``Annotated`` supports variadic 756 arguments):: 757 758 Annotated[int, ValueRange(3, 10), ctype("char")] 759 760 * ``Annotated`` must be called with at least two arguments ( 761 ``Annotated[int]`` is not valid) 762 763 * The order of the annotations is preserved and matters for equality 764 checks:: 765 766 Annotated[int, ValueRange(3, 10), ctype("char")] != Annotated[ 767 int, ctype("char"), ValueRange(3, 10) 768 ] 769 770 * Nested ``Annotated`` types are flattened, with metadata ordered 771 starting with the innermost annotation:: 772 773 Annotated[Annotated[int, ValueRange(3, 10)], ctype("char")] == Annotated[ 774 int, ValueRange(3, 10), ctype("char") 775 ] 776 777 * Duplicated annotations are not removed:: 778 779 Annotated[int, ValueRange(3, 10)] != Annotated[ 780 int, ValueRange(3, 10), ValueRange(3, 10) 781 ] 782 783 * ``Annotated`` can be used with nested and generic aliases:: 784 785 T = TypeVar('T') 786 Vec = Annotated[list[tuple[T, T]], MaxLen(10)] 787 V = Vec[int] 788 789 V == Annotated[list[tuple[int, int]], MaxLen(10)] 790 791 .. versionadded:: 3.9 792 793Building generic types 794"""""""""""""""""""""" 795 796These are not used in annotations. They are building blocks for creating generic types. 797 798.. class:: Generic 799 800 Abstract base class for generic types. 801 802 A generic type is typically declared by inheriting from an 803 instantiation of this class with one or more type variables. 804 For example, a generic mapping type might be defined as:: 805 806 class Mapping(Generic[KT, VT]): 807 def __getitem__(self, key: KT) -> VT: 808 ... 809 # Etc. 810 811 This class can then be used as follows:: 812 813 X = TypeVar('X') 814 Y = TypeVar('Y') 815 816 def lookup_name(mapping: Mapping[X, Y], key: X, default: Y) -> Y: 817 try: 818 return mapping[key] 819 except KeyError: 820 return default 821 822.. class:: TypeVar 823 824 Type variable. 825 826 Usage:: 827 828 T = TypeVar('T') # Can be anything 829 A = TypeVar('A', str, bytes) # Must be str or bytes 830 831 Type variables exist primarily for the benefit of static type 832 checkers. They serve as the parameters for generic types as well 833 as for generic function definitions. See :class:`Generic` for more 834 information on generic types. Generic functions work as follows:: 835 836 def repeat(x: T, n: int) -> Sequence[T]: 837 """Return a list containing n references to x.""" 838 return [x]*n 839 840 def longest(x: A, y: A) -> A: 841 """Return the longest of two strings.""" 842 return x if len(x) >= len(y) else y 843 844 The latter example's signature is essentially the overloading 845 of ``(str, str) -> str`` and ``(bytes, bytes) -> bytes``. Also note 846 that if the arguments are instances of some subclass of :class:`str`, 847 the return type is still plain :class:`str`. 848 849 At runtime, ``isinstance(x, T)`` will raise :exc:`TypeError`. In general, 850 :func:`isinstance` and :func:`issubclass` should not be used with types. 851 852 Type variables may be marked covariant or contravariant by passing 853 ``covariant=True`` or ``contravariant=True``. See :pep:`484` for more 854 details. By default type variables are invariant. Alternatively, 855 a type variable may specify an upper bound using ``bound=<type>``. 856 This means that an actual type substituted (explicitly or implicitly) 857 for the type variable must be a subclass of the boundary type, 858 see :pep:`484`. 859 860.. data:: AnyStr 861 862 ``AnyStr`` is a type variable defined as 863 ``AnyStr = TypeVar('AnyStr', str, bytes)``. 864 865 It is meant to be used for functions that may accept any kind of string 866 without allowing different kinds of strings to mix. For example:: 867 868 def concat(a: AnyStr, b: AnyStr) -> AnyStr: 869 return a + b 870 871 concat(u"foo", u"bar") # Ok, output has type 'unicode' 872 concat(b"foo", b"bar") # Ok, output has type 'bytes' 873 concat(u"foo", b"bar") # Error, cannot mix unicode and bytes 874 875.. class:: Protocol(Generic) 876 877 Base class for protocol classes. Protocol classes are defined like this:: 878 879 class Proto(Protocol): 880 def meth(self) -> int: 881 ... 882 883 Such classes are primarily used with static type checkers that recognize 884 structural subtyping (static duck-typing), for example:: 885 886 class C: 887 def meth(self) -> int: 888 return 0 889 890 def func(x: Proto) -> int: 891 return x.meth() 892 893 func(C()) # Passes static type check 894 895 See :pep:`544` for details. Protocol classes decorated with 896 :func:`runtime_checkable` (described later) act as simple-minded runtime 897 protocols that check only the presence of given attributes, ignoring their 898 type signatures. 899 900 Protocol classes can be generic, for example:: 901 902 class GenProto(Protocol[T]): 903 def meth(self) -> T: 904 ... 905 906 .. versionadded:: 3.8 907 908.. decorator:: runtime_checkable 909 910 Mark a protocol class as a runtime protocol. 911 912 Such a protocol can be used with :func:`isinstance` and :func:`issubclass`. 913 This raises :exc:`TypeError` when applied to a non-protocol class. This 914 allows a simple-minded structural check, very similar to "one trick ponies" 915 in :mod:`collections.abc` such as :class:`~collections.abc.Iterable`. For example:: 916 917 @runtime_checkable 918 class Closable(Protocol): 919 def close(self): ... 920 921 assert isinstance(open('/some/file'), Closable) 922 923 .. note:: 924 925 :func:`runtime_checkable` will check only the presence of the required methods, 926 not their type signatures! For example, :class:`builtins.complex <complex>` 927 implements :func:`__float__`, therefore it passes an :func:`issubclass` check 928 against :class:`SupportsFloat`. However, the ``complex.__float__`` method 929 exists only to raise a :class:`TypeError` with a more informative message. 930 931 .. versionadded:: 3.8 932 933Other special directives 934"""""""""""""""""""""""" 935 936These are not used in annotations. They are building blocks for declaring types. 937 938.. class:: NamedTuple 939 940 Typed version of :func:`collections.namedtuple`. 941 942 Usage:: 943 944 class Employee(NamedTuple): 945 name: str 946 id: int 947 948 This is equivalent to:: 949 950 Employee = collections.namedtuple('Employee', ['name', 'id']) 951 952 To give a field a default value, you can assign to it in the class body:: 953 954 class Employee(NamedTuple): 955 name: str 956 id: int = 3 957 958 employee = Employee('Guido') 959 assert employee.id == 3 960 961 Fields with a default value must come after any fields without a default. 962 963 The resulting class has an extra attribute ``__annotations__`` giving a 964 dict that maps the field names to the field types. (The field names are in 965 the ``_fields`` attribute and the default values are in the 966 ``_field_defaults`` attribute both of which are part of the namedtuple 967 API.) 968 969 ``NamedTuple`` subclasses can also have docstrings and methods:: 970 971 class Employee(NamedTuple): 972 """Represents an employee.""" 973 name: str 974 id: int = 3 975 976 def __repr__(self) -> str: 977 return f'<Employee {self.name}, id={self.id}>' 978 979 Backward-compatible usage:: 980 981 Employee = NamedTuple('Employee', [('name', str), ('id', int)]) 982 983 .. versionchanged:: 3.6 984 Added support for :pep:`526` variable annotation syntax. 985 986 .. versionchanged:: 3.6.1 987 Added support for default values, methods, and docstrings. 988 989 .. versionchanged:: 3.8 990 The ``_field_types`` and ``__annotations__`` attributes are 991 now regular dictionaries instead of instances of ``OrderedDict``. 992 993 .. versionchanged:: 3.9 994 Removed the ``_field_types`` attribute in favor of the more 995 standard ``__annotations__`` attribute which has the same information. 996 997.. function:: NewType(name, tp) 998 999 A helper function to indicate a distinct type to a typechecker, 1000 see :ref:`distinct`. At runtime it returns a function that returns 1001 its argument. Usage:: 1002 1003 UserId = NewType('UserId', int) 1004 first_user = UserId(1) 1005 1006 .. versionadded:: 3.5.2 1007 1008.. class:: TypedDict(dict) 1009 1010 Special construct to add type hints to a dictionary. 1011 At runtime it is a plain :class:`dict`. 1012 1013 ``TypedDict`` declares a dictionary type that expects all of its 1014 instances to have a certain set of keys, where each key is 1015 associated with a value of a consistent type. This expectation 1016 is not checked at runtime but is only enforced by type checkers. 1017 Usage:: 1018 1019 class Point2D(TypedDict): 1020 x: int 1021 y: int 1022 label: str 1023 1024 a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK 1025 b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check 1026 1027 assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first') 1028 1029 The type info for introspection can be accessed via ``Point2D.__annotations__`` 1030 and ``Point2D.__total__``. To allow using this feature with older versions 1031 of Python that do not support :pep:`526`, ``TypedDict`` supports two additional 1032 equivalent syntactic forms:: 1033 1034 Point2D = TypedDict('Point2D', x=int, y=int, label=str) 1035 Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) 1036 1037 By default, all keys must be present in a TypedDict. It is possible 1038 to override this by specifying totality. 1039 Usage:: 1040 1041 class point2D(TypedDict, total=False): 1042 x: int 1043 y: int 1044 1045 This means that a point2D TypedDict can have any of the keys omitted. A type 1046 checker is only expected to support a literal False or True as the value of 1047 the total argument. True is the default, and makes all items defined in the 1048 class body be required. 1049 1050 See :pep:`589` for more examples and detailed rules of using ``TypedDict``. 1051 1052 .. versionadded:: 3.8 1053 1054Generic concrete collections 1055---------------------------- 1056 1057Corresponding to built-in types 1058""""""""""""""""""""""""""""""" 1059 1060.. class:: Dict(dict, MutableMapping[KT, VT]) 1061 1062 A generic version of :class:`dict`. 1063 Useful for annotating return types. To annotate arguments it is preferred 1064 to use an abstract collection type such as :class:`Mapping`. 1065 1066 This type can be used as follows:: 1067 1068 def count_words(text: str) -> Dict[str, int]: 1069 ... 1070 1071 .. deprecated:: 3.9 1072 :class:`builtins.dict <dict>` now supports ``[]``. See :pep:`585` and 1073 :ref:`types-genericalias`. 1074 1075.. class:: List(list, MutableSequence[T]) 1076 1077 Generic version of :class:`list`. 1078 Useful for annotating return types. To annotate arguments it is preferred 1079 to use an abstract collection type such as :class:`Sequence` or 1080 :class:`Iterable`. 1081 1082 This type may be used as follows:: 1083 1084 T = TypeVar('T', int, float) 1085 1086 def vec2(x: T, y: T) -> List[T]: 1087 return [x, y] 1088 1089 def keep_positives(vector: Sequence[T]) -> List[T]: 1090 return [item for item in vector if item > 0] 1091 1092 .. deprecated:: 3.9 1093 :class:`builtins.list <list>` now supports ``[]``. See :pep:`585` and 1094 :ref:`types-genericalias`. 1095 1096.. class:: Set(set, MutableSet[T]) 1097 1098 A generic version of :class:`builtins.set <set>`. 1099 Useful for annotating return types. To annotate arguments it is preferred 1100 to use an abstract collection type such as :class:`AbstractSet`. 1101 1102 .. deprecated:: 3.9 1103 :class:`builtins.set <set>` now supports ``[]``. See :pep:`585` and 1104 :ref:`types-genericalias`. 1105 1106.. class:: FrozenSet(frozenset, AbstractSet[T_co]) 1107 1108 A generic version of :class:`builtins.frozenset <frozenset>`. 1109 1110 .. deprecated:: 3.9 1111 :class:`builtins.frozenset <frozenset>` now supports ``[]``. See 1112 :pep:`585` and :ref:`types-genericalias`. 1113 1114.. note:: :data:`Tuple` is a special form. 1115 1116Corresponding to types in :mod:`collections` 1117"""""""""""""""""""""""""""""""""""""""""""" 1118 1119.. class:: DefaultDict(collections.defaultdict, MutableMapping[KT, VT]) 1120 1121 A generic version of :class:`collections.defaultdict`. 1122 1123 .. versionadded:: 3.5.2 1124 1125 .. deprecated:: 3.9 1126 :class:`collections.defaultdict` now supports ``[]``. See :pep:`585` and 1127 :ref:`types-genericalias`. 1128 1129.. class:: OrderedDict(collections.OrderedDict, MutableMapping[KT, VT]) 1130 1131 A generic version of :class:`collections.OrderedDict`. 1132 1133 .. versionadded:: 3.7.2 1134 1135 .. deprecated:: 3.9 1136 :class:`collections.OrderedDict` now supports ``[]``. See :pep:`585` and 1137 :ref:`types-genericalias`. 1138 1139.. class:: ChainMap(collections.ChainMap, MutableMapping[KT, VT]) 1140 1141 A generic version of :class:`collections.ChainMap`. 1142 1143 .. versionadded:: 3.5.4 1144 .. versionadded:: 3.6.1 1145 1146 .. deprecated:: 3.9 1147 :class:`collections.ChainMap` now supports ``[]``. See :pep:`585` and 1148 :ref:`types-genericalias`. 1149 1150.. class:: Counter(collections.Counter, Dict[T, int]) 1151 1152 A generic version of :class:`collections.Counter`. 1153 1154 .. versionadded:: 3.5.4 1155 .. versionadded:: 3.6.1 1156 1157 .. deprecated:: 3.9 1158 :class:`collections.Counter` now supports ``[]``. See :pep:`585` and 1159 :ref:`types-genericalias`. 1160 1161.. class:: Deque(deque, MutableSequence[T]) 1162 1163 A generic version of :class:`collections.deque`. 1164 1165 .. versionadded:: 3.5.4 1166 .. versionadded:: 3.6.1 1167 1168 .. deprecated:: 3.9 1169 :class:`collections.deque` now supports ``[]``. See :pep:`585` and 1170 :ref:`types-genericalias`. 1171 1172Other concrete types 1173"""""""""""""""""""" 1174 1175.. class:: IO 1176 TextIO 1177 BinaryIO 1178 1179 Generic type ``IO[AnyStr]`` and its subclasses ``TextIO(IO[str])`` 1180 and ``BinaryIO(IO[bytes])`` 1181 represent the types of I/O streams such as returned by 1182 :func:`open`. These types are also in the ``typing.io`` namespace. 1183 1184.. class:: Pattern 1185 Match 1186 1187 These type aliases 1188 correspond to the return types from :func:`re.compile` and 1189 :func:`re.match`. These types (and the corresponding functions) 1190 are generic in ``AnyStr`` and can be made specific by writing 1191 ``Pattern[str]``, ``Pattern[bytes]``, ``Match[str]``, or 1192 ``Match[bytes]``. These types are also in the ``typing.re`` namespace. 1193 1194 .. deprecated:: 3.9 1195 Classes ``Pattern`` and ``Match`` from :mod:`re` now support ``[]``. 1196 See :pep:`585` and :ref:`types-genericalias`. 1197 1198.. class:: Text 1199 1200 ``Text`` is an alias for ``str``. It is provided to supply a forward 1201 compatible path for Python 2 code: in Python 2, ``Text`` is an alias for 1202 ``unicode``. 1203 1204 Use ``Text`` to indicate that a value must contain a unicode string in 1205 a manner that is compatible with both Python 2 and Python 3:: 1206 1207 def add_unicode_checkmark(text: Text) -> Text: 1208 return text + u' \u2713' 1209 1210 .. versionadded:: 3.5.2 1211 1212Abstract Base Classes 1213--------------------- 1214 1215Corresponding to collections in :mod:`collections.abc` 1216"""""""""""""""""""""""""""""""""""""""""""""""""""""" 1217 1218.. class:: AbstractSet(Sized, Collection[T_co]) 1219 1220 A generic version of :class:`collections.abc.Set`. 1221 1222 .. deprecated:: 3.9 1223 :class:`collections.abc.Set` now supports ``[]``. See :pep:`585` and 1224 :ref:`types-genericalias`. 1225 1226.. class:: ByteString(Sequence[int]) 1227 1228 A generic version of :class:`collections.abc.ByteString`. 1229 1230 This type represents the types :class:`bytes`, :class:`bytearray`, 1231 and :class:`memoryview` of byte sequences. 1232 1233 As a shorthand for this type, :class:`bytes` can be used to 1234 annotate arguments of any of the types mentioned above. 1235 1236 .. deprecated:: 3.9 1237 :class:`collections.abc.ByteString` now supports ``[]``. See :pep:`585` 1238 and :ref:`types-genericalias`. 1239 1240.. class:: Collection(Sized, Iterable[T_co], Container[T_co]) 1241 1242 A generic version of :class:`collections.abc.Collection` 1243 1244 .. versionadded:: 3.6.0 1245 1246 .. deprecated:: 3.9 1247 :class:`collections.abc.Collection` now supports ``[]``. See :pep:`585` 1248 and :ref:`types-genericalias`. 1249 1250.. class:: Container(Generic[T_co]) 1251 1252 A generic version of :class:`collections.abc.Container`. 1253 1254 .. deprecated:: 3.9 1255 :class:`collections.abc.Container` now supports ``[]``. See :pep:`585` 1256 and :ref:`types-genericalias`. 1257 1258.. class:: ItemsView(MappingView, Generic[KT_co, VT_co]) 1259 1260 A generic version of :class:`collections.abc.ItemsView`. 1261 1262 .. deprecated:: 3.9 1263 :class:`collections.abc.ItemsView` now supports ``[]``. See :pep:`585` 1264 and :ref:`types-genericalias`. 1265 1266.. class:: KeysView(MappingView[KT_co], AbstractSet[KT_co]) 1267 1268 A generic version of :class:`collections.abc.KeysView`. 1269 1270 .. deprecated:: 3.9 1271 :class:`collections.abc.KeysView` now supports ``[]``. See :pep:`585` 1272 and :ref:`types-genericalias`. 1273 1274.. class:: Mapping(Sized, Collection[KT], Generic[VT_co]) 1275 1276 A generic version of :class:`collections.abc.Mapping`. 1277 This type can be used as follows:: 1278 1279 def get_position_in_index(word_list: Mapping[str, int], word: str) -> int: 1280 return word_list[word] 1281 1282 .. deprecated:: 3.9 1283 :class:`collections.abc.Mapping` now supports ``[]``. See :pep:`585` 1284 and :ref:`types-genericalias`. 1285 1286.. class:: MappingView(Sized, Iterable[T_co]) 1287 1288 A generic version of :class:`collections.abc.MappingView`. 1289 1290 .. deprecated:: 3.9 1291 :class:`collections.abc.MappingView` now supports ``[]``. See :pep:`585` 1292 and :ref:`types-genericalias`. 1293 1294.. class:: MutableMapping(Mapping[KT, VT]) 1295 1296 A generic version of :class:`collections.abc.MutableMapping`. 1297 1298 .. deprecated:: 3.9 1299 :class:`collections.abc.MutableMapping` now supports ``[]``. See 1300 :pep:`585` and :ref:`types-genericalias`. 1301 1302.. class:: MutableSequence(Sequence[T]) 1303 1304 A generic version of :class:`collections.abc.MutableSequence`. 1305 1306 .. deprecated:: 3.9 1307 :class:`collections.abc.MutableSequence` now supports ``[]``. See 1308 :pep:`585` and :ref:`types-genericalias`. 1309 1310.. class:: MutableSet(AbstractSet[T]) 1311 1312 A generic version of :class:`collections.abc.MutableSet`. 1313 1314 .. deprecated:: 3.9 1315 :class:`collections.abc.MutableSet` now supports ``[]``. See :pep:`585` 1316 and :ref:`types-genericalias`. 1317 1318.. class:: Sequence(Reversible[T_co], Collection[T_co]) 1319 1320 A generic version of :class:`collections.abc.Sequence`. 1321 1322 .. deprecated:: 3.9 1323 :class:`collections.abc.Sequence` now supports ``[]``. See :pep:`585` 1324 and :ref:`types-genericalias`. 1325 1326.. class:: ValuesView(MappingView[VT_co]) 1327 1328 A generic version of :class:`collections.abc.ValuesView`. 1329 1330 .. deprecated:: 3.9 1331 :class:`collections.abc.ValuesView` now supports ``[]``. See :pep:`585` 1332 and :ref:`types-genericalias`. 1333 1334Corresponding to other types in :mod:`collections.abc` 1335"""""""""""""""""""""""""""""""""""""""""""""""""""""" 1336 1337.. class:: Iterable(Generic[T_co]) 1338 1339 A generic version of :class:`collections.abc.Iterable`. 1340 1341 .. deprecated:: 3.9 1342 :class:`collections.abc.Iterable` now supports ``[]``. See :pep:`585` 1343 and :ref:`types-genericalias`. 1344 1345.. class:: Iterator(Iterable[T_co]) 1346 1347 A generic version of :class:`collections.abc.Iterator`. 1348 1349 .. deprecated:: 3.9 1350 :class:`collections.abc.Iterator` now supports ``[]``. See :pep:`585` 1351 and :ref:`types-genericalias`. 1352 1353.. class:: Generator(Iterator[T_co], Generic[T_co, T_contra, V_co]) 1354 1355 A generator can be annotated by the generic type 1356 ``Generator[YieldType, SendType, ReturnType]``. For example:: 1357 1358 def echo_round() -> Generator[int, float, str]: 1359 sent = yield 0 1360 while sent >= 0: 1361 sent = yield round(sent) 1362 return 'Done' 1363 1364 Note that unlike many other generics in the typing module, the ``SendType`` 1365 of :class:`Generator` behaves contravariantly, not covariantly or 1366 invariantly. 1367 1368 If your generator will only yield values, set the ``SendType`` and 1369 ``ReturnType`` to ``None``:: 1370 1371 def infinite_stream(start: int) -> Generator[int, None, None]: 1372 while True: 1373 yield start 1374 start += 1 1375 1376 Alternatively, annotate your generator as having a return type of 1377 either ``Iterable[YieldType]`` or ``Iterator[YieldType]``:: 1378 1379 def infinite_stream(start: int) -> Iterator[int]: 1380 while True: 1381 yield start 1382 start += 1 1383 1384 .. deprecated:: 3.9 1385 :class:`collections.abc.Generator` now supports ``[]``. See :pep:`585` 1386 and :ref:`types-genericalias`. 1387 1388.. class:: Hashable 1389 1390 An alias to :class:`collections.abc.Hashable` 1391 1392.. class:: Reversible(Iterable[T_co]) 1393 1394 A generic version of :class:`collections.abc.Reversible`. 1395 1396 .. deprecated:: 3.9 1397 :class:`collections.abc.Reversible` now supports ``[]``. See :pep:`585` 1398 and :ref:`types-genericalias`. 1399 1400.. class:: Sized 1401 1402 An alias to :class:`collections.abc.Sized` 1403 1404Asynchronous programming 1405"""""""""""""""""""""""" 1406 1407.. class:: Coroutine(Awaitable[V_co], Generic[T_co, T_contra, V_co]) 1408 1409 A generic version of :class:`collections.abc.Coroutine`. 1410 The variance and order of type variables 1411 correspond to those of :class:`Generator`, for example:: 1412 1413 from collections.abc import Coroutine 1414 c = None # type: Coroutine[list[str], str, int] 1415 ... 1416 x = c.send('hi') # type: list[str] 1417 async def bar() -> None: 1418 x = await c # type: int 1419 1420 .. versionadded:: 3.5.3 1421 1422 .. deprecated:: 3.9 1423 :class:`collections.abc.Coroutine` now supports ``[]``. See :pep:`585` 1424 and :ref:`types-genericalias`. 1425 1426.. class:: AsyncGenerator(AsyncIterator[T_co], Generic[T_co, T_contra]) 1427 1428 An async generator can be annotated by the generic type 1429 ``AsyncGenerator[YieldType, SendType]``. For example:: 1430 1431 async def echo_round() -> AsyncGenerator[int, float]: 1432 sent = yield 0 1433 while sent >= 0.0: 1434 rounded = await round(sent) 1435 sent = yield rounded 1436 1437 Unlike normal generators, async generators cannot return a value, so there 1438 is no ``ReturnType`` type parameter. As with :class:`Generator`, the 1439 ``SendType`` behaves contravariantly. 1440 1441 If your generator will only yield values, set the ``SendType`` to 1442 ``None``:: 1443 1444 async def infinite_stream(start: int) -> AsyncGenerator[int, None]: 1445 while True: 1446 yield start 1447 start = await increment(start) 1448 1449 Alternatively, annotate your generator as having a return type of 1450 either ``AsyncIterable[YieldType]`` or ``AsyncIterator[YieldType]``:: 1451 1452 async def infinite_stream(start: int) -> AsyncIterator[int]: 1453 while True: 1454 yield start 1455 start = await increment(start) 1456 1457 .. versionadded:: 3.6.1 1458 1459 .. deprecated:: 3.9 1460 :class:`collections.abc.AsyncGenerator` now supports ``[]``. See 1461 :pep:`585` and :ref:`types-genericalias`. 1462 1463.. class:: AsyncIterable(Generic[T_co]) 1464 1465 A generic version of :class:`collections.abc.AsyncIterable`. 1466 1467 .. versionadded:: 3.5.2 1468 1469 .. deprecated:: 3.9 1470 :class:`collections.abc.AsyncIterable` now supports ``[]``. See :pep:`585` 1471 and :ref:`types-genericalias`. 1472 1473.. class:: AsyncIterator(AsyncIterable[T_co]) 1474 1475 A generic version of :class:`collections.abc.AsyncIterator`. 1476 1477 .. versionadded:: 3.5.2 1478 1479 .. deprecated:: 3.9 1480 :class:`collections.abc.AsyncIterator` now supports ``[]``. See :pep:`585` 1481 and :ref:`types-genericalias`. 1482 1483.. class:: Awaitable(Generic[T_co]) 1484 1485 A generic version of :class:`collections.abc.Awaitable`. 1486 1487 .. versionadded:: 3.5.2 1488 1489 .. deprecated:: 3.9 1490 :class:`collections.abc.Awaitable` now supports ``[]``. See :pep:`585` 1491 and :ref:`types-genericalias`. 1492 1493 1494Context manager types 1495""""""""""""""""""""" 1496 1497.. class:: ContextManager(Generic[T_co]) 1498 1499 A generic version of :class:`contextlib.AbstractContextManager`. 1500 1501 .. versionadded:: 3.5.4 1502 .. versionadded:: 3.6.0 1503 1504 .. deprecated:: 3.9 1505 :class:`contextlib.AbstractContextManager` now supports ``[]``. See 1506 :pep:`585` and :ref:`types-genericalias`. 1507 1508.. class:: AsyncContextManager(Generic[T_co]) 1509 1510 A generic version of :class:`contextlib.AbstractAsyncContextManager`. 1511 1512 .. versionadded:: 3.5.4 1513 .. versionadded:: 3.6.2 1514 1515 .. deprecated:: 3.9 1516 :class:`contextlib.AbstractAsyncContextManager` now supports ``[]``. See 1517 :pep:`585` and :ref:`types-genericalias`. 1518 1519Protocols 1520--------- 1521 1522These protocols are decorated with :func:`runtime_checkable`. 1523 1524.. class:: SupportsAbs 1525 1526 An ABC with one abstract method ``__abs__`` that is covariant 1527 in its return type. 1528 1529.. class:: SupportsBytes 1530 1531 An ABC with one abstract method ``__bytes__``. 1532 1533.. class:: SupportsComplex 1534 1535 An ABC with one abstract method ``__complex__``. 1536 1537.. class:: SupportsFloat 1538 1539 An ABC with one abstract method ``__float__``. 1540 1541.. class:: SupportsIndex 1542 1543 An ABC with one abstract method ``__index__``. 1544 1545 .. versionadded:: 3.8 1546 1547.. class:: SupportsInt 1548 1549 An ABC with one abstract method ``__int__``. 1550 1551.. class:: SupportsRound 1552 1553 An ABC with one abstract method ``__round__`` 1554 that is covariant in its return type. 1555 1556Functions and decorators 1557------------------------ 1558 1559.. function:: cast(typ, val) 1560 1561 Cast a value to a type. 1562 1563 This returns the value unchanged. To the type checker this 1564 signals that the return value has the designated type, but at 1565 runtime we intentionally don't check anything (we want this 1566 to be as fast as possible). 1567 1568.. decorator:: overload 1569 1570 The ``@overload`` decorator allows describing functions and methods 1571 that support multiple different combinations of argument types. A series 1572 of ``@overload``-decorated definitions must be followed by exactly one 1573 non-``@overload``-decorated definition (for the same function/method). 1574 The ``@overload``-decorated definitions are for the benefit of the 1575 type checker only, since they will be overwritten by the 1576 non-``@overload``-decorated definition, while the latter is used at 1577 runtime but should be ignored by a type checker. At runtime, calling 1578 a ``@overload``-decorated function directly will raise 1579 :exc:`NotImplementedError`. An example of overload that gives a more 1580 precise type than can be expressed using a union or a type variable:: 1581 1582 @overload 1583 def process(response: None) -> None: 1584 ... 1585 @overload 1586 def process(response: int) -> tuple[int, str]: 1587 ... 1588 @overload 1589 def process(response: bytes) -> str: 1590 ... 1591 def process(response): 1592 <actual implementation> 1593 1594 See :pep:`484` for details and comparison with other typing semantics. 1595 1596.. decorator:: final 1597 1598 A decorator to indicate to type checkers that the decorated method 1599 cannot be overridden, and the decorated class cannot be subclassed. 1600 For example:: 1601 1602 class Base: 1603 @final 1604 def done(self) -> None: 1605 ... 1606 class Sub(Base): 1607 def done(self) -> None: # Error reported by type checker 1608 ... 1609 1610 @final 1611 class Leaf: 1612 ... 1613 class Other(Leaf): # Error reported by type checker 1614 ... 1615 1616 There is no runtime checking of these properties. See :pep:`591` for 1617 more details. 1618 1619 .. versionadded:: 3.8 1620 1621.. decorator:: no_type_check 1622 1623 Decorator to indicate that annotations are not type hints. 1624 1625 This works as class or function :term:`decorator`. With a class, it 1626 applies recursively to all methods defined in that class (but not 1627 to methods defined in its superclasses or subclasses). 1628 1629 This mutates the function(s) in place. 1630 1631.. decorator:: no_type_check_decorator 1632 1633 Decorator to give another decorator the :func:`no_type_check` effect. 1634 1635 This wraps the decorator with something that wraps the decorated 1636 function in :func:`no_type_check`. 1637 1638.. decorator:: type_check_only 1639 1640 Decorator to mark a class or function to be unavailable at runtime. 1641 1642 This decorator is itself not available at runtime. It is mainly 1643 intended to mark classes that are defined in type stub files if 1644 an implementation returns an instance of a private class:: 1645 1646 @type_check_only 1647 class Response: # private or not available at runtime 1648 code: int 1649 def get_header(self, name: str) -> str: ... 1650 1651 def fetch_response() -> Response: ... 1652 1653 Note that returning instances of private classes is not recommended. 1654 It is usually preferable to make such classes public. 1655 1656Introspection helpers 1657--------------------- 1658 1659.. function:: get_type_hints(obj, globalns=None, localns=None, include_extras=False) 1660 1661 Return a dictionary containing type hints for a function, method, module 1662 or class object. 1663 1664 This is often the same as ``obj.__annotations__``. In addition, 1665 forward references encoded as string literals are handled by evaluating 1666 them in ``globals`` and ``locals`` namespaces. If necessary, 1667 ``Optional[t]`` is added for function and method annotations if a default 1668 value equal to ``None`` is set. For a class ``C``, return 1669 a dictionary constructed by merging all the ``__annotations__`` along 1670 ``C.__mro__`` in reverse order. 1671 1672 The function recursively replaces all ``Annotated[T, ...]`` with ``T``, 1673 unless ``include_extras`` is set to ``True`` (see :class:`Annotated` for 1674 more information). For example:: 1675 1676 class Student(NamedTuple): 1677 name: Annotated[str, 'some marker'] 1678 1679 get_type_hints(Student) == {'name': str} 1680 get_type_hints(Student, include_extras=False) == {'name': str} 1681 get_type_hints(Student, include_extras=True) == { 1682 'name': Annotated[str, 'some marker'] 1683 } 1684 1685 .. versionchanged:: 3.9 1686 Added ``include_extras`` parameter as part of :pep:`593`. 1687 1688.. function:: get_args(tp) 1689.. function:: get_origin(tp) 1690 1691 Provide basic introspection for generic types and special typing forms. 1692 1693 For a typing object of the form ``X[Y, Z, ...]`` these functions return 1694 ``X`` and ``(Y, Z, ...)``. If ``X`` is a generic alias for a builtin or 1695 :mod:`collections` class, it gets normalized to the original class. 1696 If ``X`` is a :class:`Union` or :class:`Literal` contained in another 1697 generic type, the order of ``(Y, Z, ...)`` may be different from the order 1698 of the original arguments ``[Y, Z, ...]`` due to type caching. 1699 For unsupported objects return ``None`` and ``()`` correspondingly. 1700 Examples:: 1701 1702 assert get_origin(Dict[str, int]) is dict 1703 assert get_args(Dict[int, str]) == (int, str) 1704 1705 assert get_origin(Union[int, str]) is Union 1706 assert get_args(Union[int, str]) == (int, str) 1707 1708 .. versionadded:: 3.8 1709 1710.. class:: ForwardRef 1711 1712 A class used for internal typing representation of string forward references. 1713 For example, ``list["SomeClass"]`` is implicitly transformed into 1714 ``list[ForwardRef("SomeClass")]``. This class should not be instantiated by 1715 a user, but may be used by introspection tools. 1716 1717Constant 1718-------- 1719 1720.. data:: TYPE_CHECKING 1721 1722 A special constant that is assumed to be ``True`` by 3rd party static 1723 type checkers. It is ``False`` at runtime. Usage:: 1724 1725 if TYPE_CHECKING: 1726 import expensive_mod 1727 1728 def fun(arg: 'expensive_mod.SomeType') -> None: 1729 local_var: expensive_mod.AnotherType = other_fun() 1730 1731 The first type annotation must be enclosed in quotes, making it a 1732 "forward reference", to hide the ``expensive_mod`` reference from the 1733 interpreter runtime. Type annotations for local variables are not 1734 evaluated, so the second annotation does not need to be enclosed in quotes. 1735 1736 .. note:: 1737 1738 If ``from __future__ import annotations`` is used in Python 3.7 or later, 1739 annotations are not evaluated at function definition time. 1740 Instead, they are stored as strings in ``__annotations__``, 1741 This makes it unnecessary to use quotes around the annotation. 1742 (see :pep:`563`). 1743 1744 .. versionadded:: 3.5.2 1745 1746