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