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