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 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 39For a summary of deprecated features and a deprecation timeline, please see 40`Deprecation Timeline of Major Features`_. 41 42.. seealso:: 43 44 For a quick overview of type hints, refer to 45 `this cheat sheet <https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html>`_. 46 47 The "Type System Reference" section of https://mypy.readthedocs.io/ -- since 48 the Python typing system is standardised via PEPs, this reference should 49 broadly apply to most Python type checkers, although some parts may still be 50 specific to mypy. 51 52 The documentation at https://typing.readthedocs.io/ serves as useful reference 53 for type system features, useful typing related tools and typing best practices. 54 55.. _relevant-peps: 56 57Relevant PEPs 58============= 59 60Since the initial introduction of type hints in :pep:`484` and :pep:`483`, a 61number of PEPs have modified and enhanced Python's framework for type 62annotations. These include: 63 64* :pep:`526`: Syntax for Variable Annotations 65 *Introducing* syntax for annotating variables outside of function 66 definitions, and :data:`ClassVar` 67* :pep:`544`: Protocols: Structural subtyping (static duck typing) 68 *Introducing* :class:`Protocol` and the 69 :func:`@runtime_checkable<runtime_checkable>` decorator 70* :pep:`585`: Type Hinting Generics In Standard Collections 71 *Introducing* :class:`types.GenericAlias` and the ability to use standard 72 library classes as :ref:`generic types<types-genericalias>` 73* :pep:`586`: Literal Types 74 *Introducing* :data:`Literal` 75* :pep:`589`: TypedDict: Type Hints for Dictionaries with a Fixed Set of Keys 76 *Introducing* :class:`TypedDict` 77* :pep:`591`: Adding a final qualifier to typing 78 *Introducing* :data:`Final` and the :func:`@final<final>` decorator 79* :pep:`593`: Flexible function and variable annotations 80 *Introducing* :data:`Annotated` 81* :pep:`604`: Allow writing union types as ``X | Y`` 82 *Introducing* :data:`types.UnionType` and the ability to use 83 the binary-or operator ``|`` to signify a 84 :ref:`union of types<types-union>` 85* :pep:`612`: Parameter Specification Variables 86 *Introducing* :class:`ParamSpec` and :data:`Concatenate` 87* :pep:`613`: Explicit Type Aliases 88 *Introducing* :data:`TypeAlias` 89* :pep:`646`: Variadic Generics 90 *Introducing* :data:`TypeVarTuple` 91* :pep:`647`: User-Defined Type Guards 92 *Introducing* :data:`TypeGuard` 93* :pep:`655`: Marking individual TypedDict items as required or potentially missing 94 *Introducing* :data:`Required` and :data:`NotRequired` 95* :pep:`673`: Self type 96 *Introducing* :data:`Self` 97* :pep:`675`: Arbitrary Literal String Type 98 *Introducing* :data:`LiteralString` 99* :pep:`681`: Data Class Transforms 100 *Introducing* the :func:`@dataclass_transform<dataclass_transform>` decorator 101 102.. _type-aliases: 103 104Type aliases 105============ 106 107A type alias is defined by assigning the type to the alias. In this example, 108``Vector`` and ``list[float]`` will be treated as interchangeable synonyms:: 109 110 Vector = list[float] 111 112 def scale(scalar: float, vector: Vector) -> Vector: 113 return [scalar * num for num in vector] 114 115 # passes type checking; a list of floats qualifies as a Vector. 116 new_vector = scale(2.0, [1.0, -4.2, 5.4]) 117 118Type aliases are useful for simplifying complex type signatures. For example:: 119 120 from collections.abc import Sequence 121 122 ConnectionOptions = dict[str, str] 123 Address = tuple[str, int] 124 Server = tuple[Address, ConnectionOptions] 125 126 def broadcast_message(message: str, servers: Sequence[Server]) -> None: 127 ... 128 129 # The static type checker will treat the previous type signature as 130 # being exactly equivalent to this one. 131 def broadcast_message( 132 message: str, 133 servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: 134 ... 135 136Note that ``None`` as a type hint is a special case and is replaced by 137``type(None)``. 138 139Type aliases may be marked with :data:`TypeAlias` to make it explicit that 140the statement is a type alias declaration, not a normal variable assignment:: 141 142 from typing import TypeAlias 143 144 Vector: TypeAlias = list[float] 145 146.. _distinct: 147 148NewType 149======= 150 151Use the :class:`NewType` helper to create distinct types:: 152 153 from typing import NewType 154 155 UserId = NewType('UserId', int) 156 some_id = UserId(524313) 157 158The static type checker will treat the new type as if it were a subclass 159of the original type. This is useful in helping catch logical errors:: 160 161 def get_user_name(user_id: UserId) -> str: 162 ... 163 164 # passes type checking 165 user_a = get_user_name(UserId(42351)) 166 167 # fails type checking; an int is not a UserId 168 user_b = get_user_name(-1) 169 170You may still perform all ``int`` operations on a variable of type ``UserId``, 171but the result will always be of type ``int``. This lets you pass in a 172``UserId`` wherever an ``int`` might be expected, but will prevent you from 173accidentally creating a ``UserId`` in an invalid way:: 174 175 # 'output' is of type 'int', not 'UserId' 176 output = UserId(23413) + UserId(54341) 177 178Note that these checks are enforced only by the static type checker. At runtime, 179the statement ``Derived = NewType('Derived', Base)`` will make ``Derived`` a 180callable that immediately returns whatever parameter you pass it. That means 181the expression ``Derived(some_value)`` does not create a new class or introduce 182much overhead beyond that of a regular function call. 183 184More precisely, the expression ``some_value is Derived(some_value)`` is always 185true at runtime. 186 187It is invalid to create a subtype of ``Derived``:: 188 189 from typing import NewType 190 191 UserId = NewType('UserId', int) 192 193 # Fails at runtime and does not pass type checking 194 class AdminUserId(UserId): pass 195 196However, it is possible to create a :class:`NewType` based on a 'derived' ``NewType``:: 197 198 from typing import NewType 199 200 UserId = NewType('UserId', int) 201 202 ProUserId = NewType('ProUserId', UserId) 203 204and typechecking for ``ProUserId`` will work as expected. 205 206See :pep:`484` for more details. 207 208.. note:: 209 210 Recall that the use of a type alias declares two types to be *equivalent* to 211 one another. Doing ``Alias = Original`` will make the static type checker 212 treat ``Alias`` as being *exactly equivalent* to ``Original`` in all cases. 213 This is useful when you want to simplify complex type signatures. 214 215 In contrast, ``NewType`` declares one type to be a *subtype* of another. 216 Doing ``Derived = NewType('Derived', Original)`` will make the static type 217 checker treat ``Derived`` as a *subclass* of ``Original``, which means a 218 value of type ``Original`` cannot be used in places where a value of type 219 ``Derived`` is expected. This is useful when you want to prevent logic 220 errors with minimal runtime cost. 221 222.. versionadded:: 3.5.2 223 224.. versionchanged:: 3.10 225 ``NewType`` is now a class rather than a function. There is some additional 226 runtime cost when calling ``NewType`` over a regular function. However, this 227 cost will be reduced in 3.11.0. 228 229 230Callable 231======== 232 233Frameworks expecting callback functions of specific signatures might be 234type hinted using ``Callable[[Arg1Type, Arg2Type], ReturnType]``. 235 236For example:: 237 238 from collections.abc import Callable 239 240 def feeder(get_next_item: Callable[[], str]) -> None: 241 # Body 242 243 def async_query(on_success: Callable[[int], None], 244 on_error: Callable[[int, Exception], None]) -> None: 245 # Body 246 247 async def on_update(value: str) -> None: 248 # Body 249 callback: Callable[[str], Awaitable[None]] = on_update 250 251It is possible to declare the return type of a callable without specifying 252the call signature by substituting a literal ellipsis 253for the list of arguments in the type hint: ``Callable[..., ReturnType]``. 254 255Callables which take other callables as arguments may indicate that their 256parameter types are dependent on each other using :class:`ParamSpec`. 257Additionally, if that callable adds or removes arguments from other 258callables, the :data:`Concatenate` operator may be used. They 259take the form ``Callable[ParamSpecVariable, ReturnType]`` and 260``Callable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], ReturnType]`` 261respectively. 262 263.. versionchanged:: 3.10 264 ``Callable`` now supports :class:`ParamSpec` and :data:`Concatenate`. 265 See :pep:`612` for more details. 266 267.. seealso:: 268 The documentation for :class:`ParamSpec` and :class:`Concatenate` provides 269 examples of usage in ``Callable``. 270 271.. _generics: 272 273Generics 274======== 275 276Since type information about objects kept in containers cannot be statically 277inferred in a generic way, abstract base classes have been extended to support 278subscription to denote expected types for container elements. 279 280:: 281 282 from collections.abc import Mapping, Sequence 283 284 def notify_by_email(employees: Sequence[Employee], 285 overrides: Mapping[str, str]) -> None: ... 286 287Generics can be parameterized by using a factory available in typing 288called :class:`TypeVar`. 289 290:: 291 292 from collections.abc import Sequence 293 from typing import TypeVar 294 295 T = TypeVar('T') # Declare type variable 296 297 def first(l: Sequence[T]) -> T: # Generic function 298 return l[0] 299 300.. _user-defined-generics: 301 302User-defined generic types 303========================== 304 305A user-defined class can be defined as a generic class. 306 307:: 308 309 from typing import TypeVar, Generic 310 from logging import Logger 311 312 T = TypeVar('T') 313 314 class LoggedVar(Generic[T]): 315 def __init__(self, value: T, name: str, logger: Logger) -> None: 316 self.name = name 317 self.logger = logger 318 self.value = value 319 320 def set(self, new: T) -> None: 321 self.log('Set ' + repr(self.value)) 322 self.value = new 323 324 def get(self) -> T: 325 self.log('Get ' + repr(self.value)) 326 return self.value 327 328 def log(self, message: str) -> None: 329 self.logger.info('%s: %s', self.name, message) 330 331``Generic[T]`` as a base class defines that the class ``LoggedVar`` takes a 332single type parameter ``T`` . This also makes ``T`` valid as a type within the 333class body. 334 335The :class:`Generic` base class defines :meth:`~object.__class_getitem__` so 336that ``LoggedVar[T]`` is valid as a type:: 337 338 from collections.abc import Iterable 339 340 def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None: 341 for var in vars: 342 var.set(0) 343 344A generic type can have any number of type variables. All varieties of 345:class:`TypeVar` are permissible as parameters for a generic type:: 346 347 from typing import TypeVar, Generic, Sequence 348 349 T = TypeVar('T', contravariant=True) 350 B = TypeVar('B', bound=Sequence[bytes], covariant=True) 351 S = TypeVar('S', int, str) 352 353 class WeirdTrio(Generic[T, B, S]): 354 ... 355 356Each type variable argument to :class:`Generic` must be distinct. 357This is thus invalid:: 358 359 from typing import TypeVar, Generic 360 ... 361 362 T = TypeVar('T') 363 364 class Pair(Generic[T, T]): # INVALID 365 ... 366 367You can use multiple inheritance with :class:`Generic`:: 368 369 from collections.abc import Sized 370 from typing import TypeVar, Generic 371 372 T = TypeVar('T') 373 374 class LinkedList(Sized, Generic[T]): 375 ... 376 377When inheriting from generic classes, some type parameters could be fixed:: 378 379 from collections.abc import Mapping 380 from typing import TypeVar 381 382 T = TypeVar('T') 383 384 class MyDict(Mapping[str, T]): 385 ... 386 387In this case ``MyDict`` has a single parameter, ``T``. 388 389Using a generic class without specifying type parameters assumes 390:data:`Any` for each position. In the following example, ``MyIterable`` is 391not generic but implicitly inherits from ``Iterable[Any]``:: 392 393 from collections.abc import Iterable 394 395 class MyIterable(Iterable): # Same as Iterable[Any] 396 397User-defined generic type aliases are also supported. Examples:: 398 399 from collections.abc import Iterable 400 from typing import TypeVar 401 S = TypeVar('S') 402 Response = Iterable[S] | int 403 404 # Return type here is same as Iterable[str] | int 405 def response(query: str) -> Response[str]: 406 ... 407 408 T = TypeVar('T', int, float, complex) 409 Vec = Iterable[tuple[T, T]] 410 411 def inproduct(v: Vec[T]) -> T: # Same as Iterable[tuple[T, T]] 412 return sum(x*y for x, y in v) 413 414.. versionchanged:: 3.7 415 :class:`Generic` no longer has a custom metaclass. 416 417User-defined generics for parameter expressions are also supported via parameter 418specification variables in the form ``Generic[P]``. The behavior is consistent 419with type variables' described above as parameter specification variables are 420treated by the typing module as a specialized type variable. The one exception 421to this is that a list of types can be used to substitute a :class:`ParamSpec`:: 422 423 >>> from typing import Generic, ParamSpec, TypeVar 424 425 >>> T = TypeVar('T') 426 >>> P = ParamSpec('P') 427 428 >>> class Z(Generic[T, P]): ... 429 ... 430 >>> Z[int, [dict, float]] 431 __main__.Z[int, (<class 'dict'>, <class 'float'>)] 432 433Furthermore, a generic with only one parameter specification variable will accept 434parameter lists in the forms ``X[[Type1, Type2, ...]]`` and also 435``X[Type1, Type2, ...]`` for aesthetic reasons. Internally, the latter is converted 436to the former, so the following are equivalent:: 437 438 >>> class X(Generic[P]): ... 439 ... 440 >>> X[int, str] 441 __main__.X[(<class 'int'>, <class 'str'>)] 442 >>> X[[int, str]] 443 __main__.X[(<class 'int'>, <class 'str'>)] 444 445Do note that generics with :class:`ParamSpec` may not have correct 446``__parameters__`` after substitution in some cases because they 447are intended primarily for static type checking. 448 449.. versionchanged:: 3.10 450 :class:`Generic` can now be parameterized over parameter expressions. 451 See :class:`ParamSpec` and :pep:`612` for more details. 452 453A user-defined generic class can have ABCs as base classes without a metaclass 454conflict. Generic metaclasses are not supported. The outcome of parameterizing 455generics is cached, and most types in the typing module are :term:`hashable` and 456comparable for equality. 457 458 459The :data:`Any` type 460==================== 461 462A special kind of type is :data:`Any`. A static type checker will treat 463every type as being compatible with :data:`Any` and :data:`Any` as being 464compatible with every type. 465 466This means that it is possible to perform any operation or method call on a 467value of type :data:`Any` and assign it to any variable:: 468 469 from typing import Any 470 471 a: Any = None 472 a = [] # OK 473 a = 2 # OK 474 475 s: str = '' 476 s = a # OK 477 478 def foo(item: Any) -> int: 479 # Passes type checking; 'item' could be any type, 480 # and that type might have a 'bar' method 481 item.bar() 482 ... 483 484Notice that no type checking is performed when assigning a value of type 485:data:`Any` to a more precise type. For example, the static type checker did 486not report an error when assigning ``a`` to ``s`` even though ``s`` was 487declared to be of type :class:`str` and receives an :class:`int` value at 488runtime! 489 490Furthermore, all functions without a return type or parameter types will 491implicitly default to using :data:`Any`:: 492 493 def legacy_parser(text): 494 ... 495 return data 496 497 # A static type checker will treat the above 498 # as having the same signature as: 499 def legacy_parser(text: Any) -> Any: 500 ... 501 return data 502 503This behavior allows :data:`Any` to be used as an *escape hatch* when you 504need to mix dynamically and statically typed code. 505 506Contrast the behavior of :data:`Any` with the behavior of :class:`object`. 507Similar to :data:`Any`, every type is a subtype of :class:`object`. However, 508unlike :data:`Any`, the reverse is not true: :class:`object` is *not* a 509subtype of every other type. 510 511That means when the type of a value is :class:`object`, a type checker will 512reject almost all operations on it, and assigning it to a variable (or using 513it as a return value) of a more specialized type is a type error. For example:: 514 515 def hash_a(item: object) -> int: 516 # Fails type checking; an object does not have a 'magic' method. 517 item.magic() 518 ... 519 520 def hash_b(item: Any) -> int: 521 # Passes type checking 522 item.magic() 523 ... 524 525 # Passes type checking, since ints and strs are subclasses of object 526 hash_a(42) 527 hash_a("foo") 528 529 # Passes type checking, since Any is compatible with all types 530 hash_b(42) 531 hash_b("foo") 532 533Use :class:`object` to indicate that a value could be any type in a typesafe 534manner. Use :data:`Any` to indicate that a value is dynamically typed. 535 536 537Nominal vs structural subtyping 538=============================== 539 540Initially :pep:`484` defined the Python static type system as using 541*nominal subtyping*. This means that a class ``A`` is allowed where 542a class ``B`` is expected if and only if ``A`` is a subclass of ``B``. 543 544This requirement previously also applied to abstract base classes, such as 545:class:`~collections.abc.Iterable`. The problem with this approach is that a class had 546to be explicitly marked to support them, which is unpythonic and unlike 547what one would normally do in idiomatic dynamically typed Python code. 548For example, this conforms to :pep:`484`:: 549 550 from collections.abc import Sized, Iterable, Iterator 551 552 class Bucket(Sized, Iterable[int]): 553 ... 554 def __len__(self) -> int: ... 555 def __iter__(self) -> Iterator[int]: ... 556 557:pep:`544` allows to solve this problem by allowing users to write 558the above code without explicit base classes in the class definition, 559allowing ``Bucket`` to be implicitly considered a subtype of both ``Sized`` 560and ``Iterable[int]`` by static type checkers. This is known as 561*structural subtyping* (or static duck-typing):: 562 563 from collections.abc import Iterator, Iterable 564 565 class Bucket: # Note: no base classes 566 ... 567 def __len__(self) -> int: ... 568 def __iter__(self) -> Iterator[int]: ... 569 570 def collect(items: Iterable[int]) -> int: ... 571 result = collect(Bucket()) # Passes type check 572 573Moreover, by subclassing a special class :class:`Protocol`, a user 574can define new custom protocols to fully enjoy structural subtyping 575(see examples below). 576 577Module contents 578=============== 579 580The module defines the following classes, functions and decorators. 581 582.. note:: 583 584 This module defines several types that are subclasses of pre-existing 585 standard library classes which also extend :class:`Generic` 586 to support type variables inside ``[]``. 587 These types became redundant in Python 3.9 when the 588 corresponding pre-existing classes were enhanced to support ``[]``. 589 590 The redundant types are deprecated as of Python 3.9 but no 591 deprecation warnings will be issued by the interpreter. 592 It is expected that type checkers will flag the deprecated types 593 when the checked program targets Python 3.9 or newer. 594 595 The deprecated types will be removed from the :mod:`typing` module 596 no sooner than the first Python version released 5 years after the release of Python 3.9.0. 597 See details in :pep:`585`—*Type Hinting Generics In Standard Collections*. 598 599 600Special typing primitives 601------------------------- 602 603Special types 604""""""""""""" 605 606These can be used as types in annotations and do not support ``[]``. 607 608.. data:: Any 609 610 Special type indicating an unconstrained type. 611 612 * Every type is compatible with :data:`Any`. 613 * :data:`Any` is compatible with every type. 614 615 .. versionchanged:: 3.11 616 :data:`Any` can now be used as a base class. This can be useful for 617 avoiding type checker errors with classes that can duck type anywhere or 618 are highly dynamic. 619 620.. data:: AnyStr 621 622 ``AnyStr`` is a :ref:`constrained type variable <typing-constrained-typevar>` defined as 623 ``AnyStr = TypeVar('AnyStr', str, bytes)``. 624 625 It is meant to be used for functions that may accept any kind of string 626 without allowing different kinds of strings to mix. For example:: 627 628 def concat(a: AnyStr, b: AnyStr) -> AnyStr: 629 return a + b 630 631 concat(u"foo", u"bar") # Ok, output has type 'unicode' 632 concat(b"foo", b"bar") # Ok, output has type 'bytes' 633 concat(u"foo", b"bar") # Error, cannot mix unicode and bytes 634 635.. data:: LiteralString 636 637 Special type that includes only literal strings. A string 638 literal is compatible with ``LiteralString``, as is another 639 ``LiteralString``, but an object typed as just ``str`` is not. 640 A string created by composing ``LiteralString``-typed objects 641 is also acceptable as a ``LiteralString``. 642 643 Example:: 644 645 def run_query(sql: LiteralString) -> ... 646 ... 647 648 def caller(arbitrary_string: str, literal_string: LiteralString) -> None: 649 run_query("SELECT * FROM students") # ok 650 run_query(literal_string) # ok 651 run_query("SELECT * FROM " + literal_string) # ok 652 run_query(arbitrary_string) # type checker error 653 run_query( # type checker error 654 f"SELECT * FROM students WHERE name = {arbitrary_string}" 655 ) 656 657 This is useful for sensitive APIs where arbitrary user-generated 658 strings could generate problems. For example, the two cases above 659 that generate type checker errors could be vulnerable to an SQL 660 injection attack. 661 662 See :pep:`675` for more details. 663 664 .. versionadded:: 3.11 665 666.. data:: Never 667 668 The `bottom type <https://en.wikipedia.org/wiki/Bottom_type>`_, 669 a type that has no members. 670 671 This can be used to define a function that should never be 672 called, or a function that never returns:: 673 674 from typing import Never 675 676 def never_call_me(arg: Never) -> None: 677 pass 678 679 def int_or_str(arg: int | str) -> None: 680 never_call_me(arg) # type checker error 681 match arg: 682 case int(): 683 print("It's an int") 684 case str(): 685 print("It's a str") 686 case _: 687 never_call_me(arg) # ok, arg is of type Never 688 689 .. versionadded:: 3.11 690 691 On older Python versions, :data:`NoReturn` may be used to express the 692 same concept. ``Never`` was added to make the intended meaning more explicit. 693 694.. data:: NoReturn 695 696 Special type indicating that a function never returns. 697 For example:: 698 699 from typing import NoReturn 700 701 def stop() -> NoReturn: 702 raise RuntimeError('no way') 703 704 ``NoReturn`` can also be used as a 705 `bottom type <https://en.wikipedia.org/wiki/Bottom_type>`_, a type that 706 has no values. Starting in Python 3.11, the :data:`Never` type should 707 be used for this concept instead. Type checkers should treat the two 708 equivalently. 709 710 .. versionadded:: 3.5.4 711 .. versionadded:: 3.6.2 712 713.. data:: Self 714 715 Special type to represent the current enclosed class. 716 For example:: 717 718 from typing import Self 719 720 class Foo: 721 def return_self(self) -> Self: 722 ... 723 return self 724 725 726 This annotation is semantically equivalent to the following, 727 albeit in a more succinct fashion:: 728 729 from typing import TypeVar 730 731 Self = TypeVar("Self", bound="Foo") 732 733 class Foo: 734 def return_self(self: Self) -> Self: 735 ... 736 return self 737 738 In general if something currently follows the pattern of:: 739 740 class Foo: 741 def return_self(self) -> "Foo": 742 ... 743 return self 744 745 You should use :data:`Self` as calls to ``SubclassOfFoo.return_self`` would have 746 ``Foo`` as the return type and not ``SubclassOfFoo``. 747 748 Other common use cases include: 749 750 - :class:`classmethod`\s that are used as alternative constructors and return instances 751 of the ``cls`` parameter. 752 - Annotating an :meth:`~object.__enter__` method which returns self. 753 754 See :pep:`673` for more details. 755 756 .. versionadded:: 3.11 757 758.. data:: TypeAlias 759 760 Special annotation for explicitly declaring a :ref:`type alias <type-aliases>`. 761 For example:: 762 763 from typing import TypeAlias 764 765 Factors: TypeAlias = list[int] 766 767 See :pep:`613` for more details about explicit type aliases. 768 769 .. versionadded:: 3.10 770 771Special forms 772""""""""""""" 773 774These can be used as types in annotations using ``[]``, each having a unique syntax. 775 776.. data:: Tuple 777 778 Tuple type; ``Tuple[X, Y]`` is the type of a tuple of two items 779 with the first item of type X and the second of type Y. The type of 780 the empty tuple can be written as ``Tuple[()]``. 781 782 Example: ``Tuple[T1, T2]`` is a tuple of two elements corresponding 783 to type variables T1 and T2. ``Tuple[int, float, str]`` is a tuple 784 of an int, a float and a string. 785 786 To specify a variable-length tuple of homogeneous type, 787 use literal ellipsis, e.g. ``Tuple[int, ...]``. A plain :data:`Tuple` 788 is equivalent to ``Tuple[Any, ...]``, and in turn to :class:`tuple`. 789 790 .. deprecated:: 3.9 791 :class:`builtins.tuple <tuple>` now supports subscripting (``[]``). 792 See :pep:`585` and :ref:`types-genericalias`. 793 794.. data:: Union 795 796 Union type; ``Union[X, Y]`` is equivalent to ``X | Y`` and means either X or Y. 797 798 To define a union, use e.g. ``Union[int, str]`` or the shorthand ``int | str``. Using that shorthand is recommended. Details: 799 800 * The arguments must be types and there must be at least one. 801 802 * Unions of unions are flattened, e.g.:: 803 804 Union[Union[int, str], float] == Union[int, str, float] 805 806 * Unions of a single argument vanish, e.g.:: 807 808 Union[int] == int # The constructor actually returns int 809 810 * Redundant arguments are skipped, e.g.:: 811 812 Union[int, str, int] == Union[int, str] == int | str 813 814 * When comparing unions, the argument order is ignored, e.g.:: 815 816 Union[int, str] == Union[str, int] 817 818 * You cannot subclass or instantiate a ``Union``. 819 820 * You cannot write ``Union[X][Y]``. 821 822 .. versionchanged:: 3.7 823 Don't remove explicit subclasses from unions at runtime. 824 825 .. versionchanged:: 3.10 826 Unions can now be written as ``X | Y``. See 827 :ref:`union type expressions<types-union>`. 828 829.. data:: Optional 830 831 Optional type. 832 833 ``Optional[X]`` is equivalent to ``X | None`` (or ``Union[X, None]``). 834 835 Note that this is not the same concept as an optional argument, 836 which is one that has a default. An optional argument with a 837 default does not require the ``Optional`` qualifier on its type 838 annotation just because it is optional. For example:: 839 840 def foo(arg: int = 0) -> None: 841 ... 842 843 On the other hand, if an explicit value of ``None`` is allowed, the 844 use of ``Optional`` is appropriate, whether the argument is optional 845 or not. For example:: 846 847 def foo(arg: Optional[int] = None) -> None: 848 ... 849 850 .. versionchanged:: 3.10 851 Optional can now be written as ``X | None``. See 852 :ref:`union type expressions<types-union>`. 853 854.. data:: Callable 855 856 Callable type; ``Callable[[int], str]`` is a function of (int) -> str. 857 858 The subscription syntax must always be used with exactly two 859 values: the argument list and the return type. The argument list 860 must be a list of types or an ellipsis; the return type must be 861 a single type. 862 863 There is no syntax to indicate optional or keyword arguments; 864 such function types are rarely used as callback types. 865 ``Callable[..., ReturnType]`` (literal ellipsis) can be used to 866 type hint a callable taking any number of arguments and returning 867 ``ReturnType``. A plain :data:`Callable` is equivalent to 868 ``Callable[..., Any]``, and in turn to 869 :class:`collections.abc.Callable`. 870 871 Callables which take other callables as arguments may indicate that their 872 parameter types are dependent on each other using :class:`ParamSpec`. 873 Additionally, if that callable adds or removes arguments from other 874 callables, the :data:`Concatenate` operator may be used. They 875 take the form ``Callable[ParamSpecVariable, ReturnType]`` and 876 ``Callable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], ReturnType]`` 877 respectively. 878 879 .. deprecated:: 3.9 880 :class:`collections.abc.Callable` now supports subscripting (``[]``). 881 See :pep:`585` and :ref:`types-genericalias`. 882 883 .. versionchanged:: 3.10 884 ``Callable`` now supports :class:`ParamSpec` and :data:`Concatenate`. 885 See :pep:`612` for more details. 886 887 .. seealso:: 888 The documentation for :class:`ParamSpec` and :class:`Concatenate` provide 889 examples of usage with ``Callable``. 890 891.. data:: Concatenate 892 893 Used with :data:`Callable` and :class:`ParamSpec` to type annotate a higher 894 order callable which adds, removes, or transforms parameters of another 895 callable. Usage is in the form 896 ``Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable]``. ``Concatenate`` 897 is currently only valid when used as the first argument to a :data:`Callable`. 898 The last parameter to ``Concatenate`` must be a :class:`ParamSpec` or 899 ellipsis (``...``). 900 901 For example, to annotate a decorator ``with_lock`` which provides a 902 :class:`threading.Lock` to the decorated function, ``Concatenate`` can be 903 used to indicate that ``with_lock`` expects a callable which takes in a 904 ``Lock`` as the first argument, and returns a callable with a different type 905 signature. In this case, the :class:`ParamSpec` indicates that the returned 906 callable's parameter types are dependent on the parameter types of the 907 callable being passed in:: 908 909 from collections.abc import Callable 910 from threading import Lock 911 from typing import Concatenate, ParamSpec, TypeVar 912 913 P = ParamSpec('P') 914 R = TypeVar('R') 915 916 # Use this lock to ensure that only one thread is executing a function 917 # at any time. 918 my_lock = Lock() 919 920 def with_lock(f: Callable[Concatenate[Lock, P], R]) -> Callable[P, R]: 921 '''A type-safe decorator which provides a lock.''' 922 def inner(*args: P.args, **kwargs: P.kwargs) -> R: 923 # Provide the lock as the first argument. 924 return f(my_lock, *args, **kwargs) 925 return inner 926 927 @with_lock 928 def sum_threadsafe(lock: Lock, numbers: list[float]) -> float: 929 '''Add a list of numbers together in a thread-safe manner.''' 930 with lock: 931 return sum(numbers) 932 933 # We don't need to pass in the lock ourselves thanks to the decorator. 934 sum_threadsafe([1.1, 2.2, 3.3]) 935 936 .. versionadded:: 3.10 937 938 .. seealso:: 939 940 * :pep:`612` -- Parameter Specification Variables (the PEP which introduced 941 ``ParamSpec`` and ``Concatenate``). 942 * :class:`ParamSpec` and :class:`Callable`. 943 944 945.. class:: Type(Generic[CT_co]) 946 947 A variable annotated with ``C`` may accept a value of type ``C``. In 948 contrast, a variable annotated with ``Type[C]`` may accept values that are 949 classes themselves -- specifically, it will accept the *class object* of 950 ``C``. For example:: 951 952 a = 3 # Has type 'int' 953 b = int # Has type 'Type[int]' 954 c = type(a) # Also has type 'Type[int]' 955 956 Note that ``Type[C]`` is covariant:: 957 958 class User: ... 959 class BasicUser(User): ... 960 class ProUser(User): ... 961 class TeamUser(User): ... 962 963 # Accepts User, BasicUser, ProUser, TeamUser, ... 964 def make_new_user(user_class: Type[User]) -> User: 965 # ... 966 return user_class() 967 968 The fact that ``Type[C]`` is covariant implies that all subclasses of 969 ``C`` should implement the same constructor signature and class method 970 signatures as ``C``. The type checker should flag violations of this, 971 but should also allow constructor calls in subclasses that match the 972 constructor calls in the indicated base class. How the type checker is 973 required to handle this particular case may change in future revisions of 974 :pep:`484`. 975 976 The only legal parameters for :class:`Type` are classes, :data:`Any`, 977 :ref:`type variables <generics>`, and unions of any of these types. 978 For example:: 979 980 def new_non_team_user(user_class: Type[BasicUser | ProUser]): ... 981 982 ``Type[Any]`` is equivalent to ``Type`` which in turn is equivalent 983 to ``type``, which is the root of Python's metaclass hierarchy. 984 985 .. versionadded:: 3.5.2 986 987 .. deprecated:: 3.9 988 :class:`builtins.type <type>` now supports subscripting (``[]``). 989 See :pep:`585` and :ref:`types-genericalias`. 990 991.. data:: Literal 992 993 A type that can be used to indicate to type checkers that the 994 corresponding variable or function parameter has a value equivalent to 995 the provided literal (or one of several literals). For example:: 996 997 def validate_simple(data: Any) -> Literal[True]: # always returns True 998 ... 999 1000 MODE = Literal['r', 'rb', 'w', 'wb'] 1001 def open_helper(file: str, mode: MODE) -> str: 1002 ... 1003 1004 open_helper('/some/path', 'r') # Passes type check 1005 open_helper('/other/path', 'typo') # Error in type checker 1006 1007 ``Literal[...]`` cannot be subclassed. At runtime, an arbitrary value 1008 is allowed as type argument to ``Literal[...]``, but type checkers may 1009 impose restrictions. See :pep:`586` for more details about literal types. 1010 1011 .. versionadded:: 3.8 1012 1013 .. versionchanged:: 3.9.1 1014 ``Literal`` now de-duplicates parameters. Equality comparisons of 1015 ``Literal`` objects are no longer order dependent. ``Literal`` objects 1016 will now raise a :exc:`TypeError` exception during equality comparisons 1017 if one of their parameters are not :term:`hashable`. 1018 1019.. data:: ClassVar 1020 1021 Special type construct to mark class variables. 1022 1023 As introduced in :pep:`526`, a variable annotation wrapped in ClassVar 1024 indicates that a given attribute is intended to be used as a class variable 1025 and should not be set on instances of that class. Usage:: 1026 1027 class Starship: 1028 stats: ClassVar[dict[str, int]] = {} # class variable 1029 damage: int = 10 # instance variable 1030 1031 :data:`ClassVar` accepts only types and cannot be further subscribed. 1032 1033 :data:`ClassVar` is not a class itself, and should not 1034 be used with :func:`isinstance` or :func:`issubclass`. 1035 :data:`ClassVar` does not change Python runtime behavior, but 1036 it can be used by third-party type checkers. For example, a type checker 1037 might flag the following code as an error:: 1038 1039 enterprise_d = Starship(3000) 1040 enterprise_d.stats = {} # Error, setting class variable on instance 1041 Starship.stats = {} # This is OK 1042 1043 .. versionadded:: 3.5.3 1044 1045.. data:: Final 1046 1047 A special typing construct to indicate to type checkers that a name 1048 cannot be re-assigned or overridden in a subclass. For example:: 1049 1050 MAX_SIZE: Final = 9000 1051 MAX_SIZE += 1 # Error reported by type checker 1052 1053 class Connection: 1054 TIMEOUT: Final[int] = 10 1055 1056 class FastConnector(Connection): 1057 TIMEOUT = 1 # Error reported by type checker 1058 1059 There is no runtime checking of these properties. See :pep:`591` for 1060 more details. 1061 1062 .. versionadded:: 3.8 1063 1064.. data:: Required 1065 1066.. data:: NotRequired 1067 1068 Special typing constructs that mark individual keys of a :class:`TypedDict` 1069 as either required or non-required respectively. 1070 1071 See :class:`TypedDict` and :pep:`655` for more details. 1072 1073 .. versionadded:: 3.11 1074 1075.. data:: Annotated 1076 1077 A type, introduced in :pep:`593` (``Flexible function and variable 1078 annotations``), to decorate existing types with context-specific metadata 1079 (possibly multiple pieces of it, as ``Annotated`` is variadic). 1080 Specifically, a type ``T`` can be annotated with metadata ``x`` via the 1081 typehint ``Annotated[T, x]``. This metadata can be used for either static 1082 analysis or at runtime. If a library (or tool) encounters a typehint 1083 ``Annotated[T, x]`` and has no special logic for metadata ``x``, it 1084 should ignore it and simply treat the type as ``T``. Unlike the 1085 ``no_type_check`` functionality that currently exists in the ``typing`` 1086 module which completely disables typechecking annotations on a function 1087 or a class, the ``Annotated`` type allows for both static typechecking 1088 of ``T`` (which can safely ignore ``x``) 1089 together with runtime access to ``x`` within a specific application. 1090 1091 Ultimately, the responsibility of how to interpret the annotations (if 1092 at all) is the responsibility of the tool or library encountering the 1093 ``Annotated`` type. A tool or library encountering an ``Annotated`` type 1094 can scan through the annotations to determine if they are of interest 1095 (e.g., using ``isinstance()``). 1096 1097 When a tool or a library does not support annotations or encounters an 1098 unknown annotation it should just ignore it and treat annotated type as 1099 the underlying type. 1100 1101 It's up to the tool consuming the annotations to decide whether the 1102 client is allowed to have several annotations on one type and how to 1103 merge those annotations. 1104 1105 Since the ``Annotated`` type allows you to put several annotations of 1106 the same (or different) type(s) on any node, the tools or libraries 1107 consuming those annotations are in charge of dealing with potential 1108 duplicates. For example, if you are doing value range analysis you might 1109 allow this:: 1110 1111 T1 = Annotated[int, ValueRange(-10, 5)] 1112 T2 = Annotated[T1, ValueRange(-20, 3)] 1113 1114 Passing ``include_extras=True`` to :func:`get_type_hints` lets one 1115 access the extra annotations at runtime. 1116 1117 The details of the syntax: 1118 1119 * The first argument to ``Annotated`` must be a valid type 1120 1121 * Multiple type annotations are supported (``Annotated`` supports variadic 1122 arguments):: 1123 1124 Annotated[int, ValueRange(3, 10), ctype("char")] 1125 1126 * ``Annotated`` must be called with at least two arguments ( 1127 ``Annotated[int]`` is not valid) 1128 1129 * The order of the annotations is preserved and matters for equality 1130 checks:: 1131 1132 Annotated[int, ValueRange(3, 10), ctype("char")] != Annotated[ 1133 int, ctype("char"), ValueRange(3, 10) 1134 ] 1135 1136 * Nested ``Annotated`` types are flattened, with metadata ordered 1137 starting with the innermost annotation:: 1138 1139 Annotated[Annotated[int, ValueRange(3, 10)], ctype("char")] == Annotated[ 1140 int, ValueRange(3, 10), ctype("char") 1141 ] 1142 1143 * Duplicated annotations are not removed:: 1144 1145 Annotated[int, ValueRange(3, 10)] != Annotated[ 1146 int, ValueRange(3, 10), ValueRange(3, 10) 1147 ] 1148 1149 * ``Annotated`` can be used with nested and generic aliases:: 1150 1151 T = TypeVar('T') 1152 Vec = Annotated[list[tuple[T, T]], MaxLen(10)] 1153 V = Vec[int] 1154 1155 V == Annotated[list[tuple[int, int]], MaxLen(10)] 1156 1157 .. versionadded:: 3.9 1158 1159 1160.. data:: TypeGuard 1161 1162 Special typing form used to annotate the return type of a user-defined 1163 type guard function. ``TypeGuard`` only accepts a single type argument. 1164 At runtime, functions marked this way should return a boolean. 1165 1166 ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static 1167 type checkers to determine a more precise type of an expression within a 1168 program's code flow. Usually type narrowing is done by analyzing 1169 conditional code flow and applying the narrowing to a block of code. The 1170 conditional expression here is sometimes referred to as a "type guard":: 1171 1172 def is_str(val: str | float): 1173 # "isinstance" type guard 1174 if isinstance(val, str): 1175 # Type of ``val`` is narrowed to ``str`` 1176 ... 1177 else: 1178 # Else, type of ``val`` is narrowed to ``float``. 1179 ... 1180 1181 Sometimes it would be convenient to use a user-defined boolean function 1182 as a type guard. Such a function should use ``TypeGuard[...]`` as its 1183 return type to alert static type checkers to this intention. 1184 1185 Using ``-> TypeGuard`` tells the static type checker that for a given 1186 function: 1187 1188 1. The return value is a boolean. 1189 2. If the return value is ``True``, the type of its argument 1190 is the type inside ``TypeGuard``. 1191 1192 For example:: 1193 1194 def is_str_list(val: list[object]) -> TypeGuard[list[str]]: 1195 '''Determines whether all objects in the list are strings''' 1196 return all(isinstance(x, str) for x in val) 1197 1198 def func1(val: list[object]): 1199 if is_str_list(val): 1200 # Type of ``val`` is narrowed to ``list[str]``. 1201 print(" ".join(val)) 1202 else: 1203 # Type of ``val`` remains as ``list[object]``. 1204 print("Not a list of strings!") 1205 1206 If ``is_str_list`` is a class or instance method, then the type in 1207 ``TypeGuard`` maps to the type of the second parameter after ``cls`` or 1208 ``self``. 1209 1210 In short, the form ``def foo(arg: TypeA) -> TypeGuard[TypeB]: ...``, 1211 means that if ``foo(arg)`` returns ``True``, then ``arg`` narrows from 1212 ``TypeA`` to ``TypeB``. 1213 1214 .. note:: 1215 1216 ``TypeB`` need not be a narrower form of ``TypeA`` -- it can even be a 1217 wider form. The main reason is to allow for things like 1218 narrowing ``list[object]`` to ``list[str]`` even though the latter 1219 is not a subtype of the former, since ``list`` is invariant. 1220 The responsibility of writing type-safe type guards is left to the user. 1221 1222 ``TypeGuard`` also works with type variables. See :pep:`647` for more details. 1223 1224 .. versionadded:: 3.10 1225 1226 1227.. data:: Unpack 1228 1229 A typing operator that conceptually marks an object as having been 1230 unpacked. For example, using the unpack operator ``*`` on a 1231 :class:`type variable tuple <TypeVarTuple>` is equivalent to using ``Unpack`` 1232 to mark the type variable tuple as having been unpacked:: 1233 1234 Ts = TypeVarTuple('Ts') 1235 tup: tuple[*Ts] 1236 # Effectively does: 1237 tup: tuple[Unpack[Ts]] 1238 1239 In fact, ``Unpack`` can be used interchangeably with ``*`` in the context 1240 of :class:`typing.TypeVarTuple <TypeVarTuple>` and 1241 :class:`builtins.tuple <tuple>` types. You might see ``Unpack`` being used 1242 explicitly in older versions of Python, where ``*`` couldn't be used in 1243 certain places:: 1244 1245 # In older versions of Python, TypeVarTuple and Unpack 1246 # are located in the `typing_extensions` backports package. 1247 from typing_extensions import TypeVarTuple, Unpack 1248 1249 Ts = TypeVarTuple('Ts') 1250 tup: tuple[*Ts] # Syntax error on Python <= 3.10! 1251 tup: tuple[Unpack[Ts]] # Semantically equivalent, and backwards-compatible 1252 1253 .. versionadded:: 3.11 1254 1255Building generic types 1256"""""""""""""""""""""" 1257 1258The following objects are not used directly in annotations. Instead, they are building blocks 1259for creating generic types. 1260 1261.. class:: Generic 1262 1263 Abstract base class for generic types. 1264 1265 A generic type is typically declared by inheriting from an 1266 instantiation of this class with one or more type variables. 1267 For example, a generic mapping type might be defined as:: 1268 1269 class Mapping(Generic[KT, VT]): 1270 def __getitem__(self, key: KT) -> VT: 1271 ... 1272 # Etc. 1273 1274 This class can then be used as follows:: 1275 1276 X = TypeVar('X') 1277 Y = TypeVar('Y') 1278 1279 def lookup_name(mapping: Mapping[X, Y], key: X, default: Y) -> Y: 1280 try: 1281 return mapping[key] 1282 except KeyError: 1283 return default 1284 1285.. class:: TypeVar(name, *constraints, bound=None, covariant=False, contravariant=False) 1286 1287 Type variable. 1288 1289 Usage:: 1290 1291 T = TypeVar('T') # Can be anything 1292 S = TypeVar('S', bound=str) # Can be any subtype of str 1293 A = TypeVar('A', str, bytes) # Must be exactly str or bytes 1294 1295 Type variables exist primarily for the benefit of static type 1296 checkers. They serve as the parameters for generic types as well 1297 as for generic function and type alias definitions. 1298 See :class:`Generic` for more 1299 information on generic types. Generic functions work as follows:: 1300 1301 def repeat(x: T, n: int) -> Sequence[T]: 1302 """Return a list containing n references to x.""" 1303 return [x]*n 1304 1305 1306 def print_capitalized(x: S) -> S: 1307 """Print x capitalized, and return x.""" 1308 print(x.capitalize()) 1309 return x 1310 1311 1312 def concatenate(x: A, y: A) -> A: 1313 """Add two strings or bytes objects together.""" 1314 return x + y 1315 1316 Note that type variables can be *bound*, *constrained*, or neither, but 1317 cannot be both bound *and* constrained. 1318 1319 Created type variables may be explicitly marked covariant or contravariant by passing 1320 ``covariant=True`` or ``contravariant=True``. 1321 By default, type variables are invariant. 1322 See :pep:`484` and :pep:`695` for more details. 1323 1324 Bound type variables and constrained type variables have different 1325 semantics in several important ways. Using a *bound* type variable means 1326 that the ``TypeVar`` will be solved using the most specific type possible:: 1327 1328 x = print_capitalized('a string') 1329 reveal_type(x) # revealed type is str 1330 1331 class StringSubclass(str): 1332 pass 1333 1334 y = print_capitalized(StringSubclass('another string')) 1335 reveal_type(y) # revealed type is StringSubclass 1336 1337 z = print_capitalized(45) # error: int is not a subtype of str 1338 1339 Type variables can be bound to concrete types, abstract types (ABCs or 1340 protocols), and even unions of types:: 1341 1342 U = TypeVar('U', bound=str|bytes) # Can be any subtype of the union str|bytes 1343 V = TypeVar('V', bound=SupportsAbs) # Can be anything with an __abs__ method 1344 1345 .. _typing-constrained-typevar: 1346 1347 Using a *constrained* type variable, however, means that the ``TypeVar`` 1348 can only ever be solved as being exactly one of the constraints given:: 1349 1350 a = concatenate('one', 'two') 1351 reveal_type(a) # revealed type is str 1352 1353 b = concatenate(StringSubclass('one'), StringSubclass('two')) 1354 reveal_type(b) # revealed type is str, despite StringSubclass being passed in 1355 1356 c = concatenate('one', b'two') # error: type variable 'A' can be either str or bytes in a function call, but not both 1357 1358 At runtime, ``isinstance(x, T)`` will raise :exc:`TypeError`. 1359 1360 .. attribute:: __name__ 1361 1362 The name of the type variable. 1363 1364 .. attribute:: __covariant__ 1365 1366 Whether the type var has been marked as covariant. 1367 1368 .. attribute:: __contravariant__ 1369 1370 Whether the type var has been marked as contravariant. 1371 1372 .. attribute:: __bound__ 1373 1374 The bound of the type variable, if any. 1375 1376 .. attribute:: __constraints__ 1377 1378 A tuple containing the constraints of the type variable, if any. 1379 1380.. class:: TypeVarTuple(name) 1381 1382 Type variable tuple. A specialized form of :class:`type variable <TypeVar>` 1383 that enables *variadic* generics. 1384 1385 Usage:: 1386 1387 T = TypeVar("T") 1388 Ts = TypeVarTuple("Ts") 1389 1390 def move_first_element_to_last(tup: tuple[T, *Ts]) -> tuple[*Ts, T]: 1391 return (*tup[1:], tup[0]) 1392 1393 A normal type variable enables parameterization with a single type. A type 1394 variable tuple, in contrast, allows parameterization with an 1395 *arbitrary* number of types by acting like an *arbitrary* number of type 1396 variables wrapped in a tuple. For example:: 1397 1398 # T is bound to int, Ts is bound to () 1399 # Return value is (1,), which has type tuple[int] 1400 move_first_element_to_last(tup=(1,)) 1401 1402 # T is bound to int, Ts is bound to (str,) 1403 # Return value is ('spam', 1), which has type tuple[str, int] 1404 move_first_element_to_last(tup=(1, 'spam')) 1405 1406 # T is bound to int, Ts is bound to (str, float) 1407 # Return value is ('spam', 3.0, 1), which has type tuple[str, float, int] 1408 move_first_element_to_last(tup=(1, 'spam', 3.0)) 1409 1410 # This fails to type check (and fails at runtime) 1411 # because tuple[()] is not compatible with tuple[T, *Ts] 1412 # (at least one element is required) 1413 move_first_element_to_last(tup=()) 1414 1415 Note the use of the unpacking operator ``*`` in ``tuple[T, *Ts]``. 1416 Conceptually, you can think of ``Ts`` as a tuple of type variables 1417 ``(T1, T2, ...)``. ``tuple[T, *Ts]`` would then become 1418 ``tuple[T, *(T1, T2, ...)]``, which is equivalent to 1419 ``tuple[T, T1, T2, ...]``. (Note that in older versions of Python, you might 1420 see this written using :data:`Unpack <Unpack>` instead, as 1421 ``Unpack[Ts]``.) 1422 1423 Type variable tuples must *always* be unpacked. This helps distinguish type 1424 variable tuples from normal type variables:: 1425 1426 x: Ts # Not valid 1427 x: tuple[Ts] # Not valid 1428 x: tuple[*Ts] # The correct way to do it 1429 1430 Type variable tuples can be used in the same contexts as normal type 1431 variables. For example, in class definitions, arguments, and return types:: 1432 1433 Shape = TypeVarTuple("Shape") 1434 class Array(Generic[*Shape]): 1435 def __getitem__(self, key: tuple[*Shape]) -> float: ... 1436 def __abs__(self) -> "Array[*Shape]": ... 1437 def get_shape(self) -> tuple[*Shape]: ... 1438 1439 Type variable tuples can be happily combined with normal type variables:: 1440 1441 DType = TypeVar('DType') 1442 1443 class Array(Generic[DType, *Shape]): # This is fine 1444 pass 1445 1446 class Array2(Generic[*Shape, DType]): # This would also be fine 1447 pass 1448 1449 float_array_1d: Array[float, Height] = Array() # Totally fine 1450 int_array_2d: Array[int, Height, Width] = Array() # Yup, fine too 1451 1452 However, note that at most one type variable tuple may appear in a single 1453 list of type arguments or type parameters:: 1454 1455 x: tuple[*Ts, *Ts] # Not valid 1456 class Array(Generic[*Shape, *Shape]): # Not valid 1457 pass 1458 1459 Finally, an unpacked type variable tuple can be used as the type annotation 1460 of ``*args``:: 1461 1462 def call_soon( 1463 callback: Callable[[*Ts], None], 1464 *args: *Ts 1465 ) -> None: 1466 ... 1467 callback(*args) 1468 1469 In contrast to non-unpacked annotations of ``*args`` - e.g. ``*args: int``, 1470 which would specify that *all* arguments are ``int`` - ``*args: *Ts`` 1471 enables reference to the types of the *individual* arguments in ``*args``. 1472 Here, this allows us to ensure the types of the ``*args`` passed 1473 to ``call_soon`` match the types of the (positional) arguments of 1474 ``callback``. 1475 1476 See :pep:`646` for more details on type variable tuples. 1477 1478 .. attribute:: __name__ 1479 1480 The name of the type variable tuple. 1481 1482 .. versionadded:: 3.11 1483 1484.. class:: ParamSpec(name, *, bound=None, covariant=False, contravariant=False) 1485 1486 Parameter specification variable. A specialized version of 1487 :class:`type variables <TypeVar>`. 1488 1489 Usage:: 1490 1491 P = ParamSpec('P') 1492 1493 Parameter specification variables exist primarily for the benefit of static 1494 type checkers. They are used to forward the parameter types of one 1495 callable to another callable -- a pattern commonly found in higher order 1496 functions and decorators. They are only valid when used in ``Concatenate``, 1497 or as the first argument to ``Callable``, or as parameters for user-defined 1498 Generics. See :class:`Generic` for more information on generic types. 1499 1500 For example, to add basic logging to a function, one can create a decorator 1501 ``add_logging`` to log function calls. The parameter specification variable 1502 tells the type checker that the callable passed into the decorator and the 1503 new callable returned by it have inter-dependent type parameters:: 1504 1505 from collections.abc import Callable 1506 from typing import TypeVar, ParamSpec 1507 import logging 1508 1509 T = TypeVar('T') 1510 P = ParamSpec('P') 1511 1512 def add_logging(f: Callable[P, T]) -> Callable[P, T]: 1513 '''A type-safe decorator to add logging to a function.''' 1514 def inner(*args: P.args, **kwargs: P.kwargs) -> T: 1515 logging.info(f'{f.__name__} was called') 1516 return f(*args, **kwargs) 1517 return inner 1518 1519 @add_logging 1520 def add_two(x: float, y: float) -> float: 1521 '''Add two numbers together.''' 1522 return x + y 1523 1524 Without ``ParamSpec``, the simplest way to annotate this previously was to 1525 use a :class:`TypeVar` with bound ``Callable[..., Any]``. However this 1526 causes two problems: 1527 1528 1. The type checker can't type check the ``inner`` function because 1529 ``*args`` and ``**kwargs`` have to be typed :data:`Any`. 1530 2. :func:`~cast` may be required in the body of the ``add_logging`` 1531 decorator when returning the ``inner`` function, or the static type 1532 checker must be told to ignore the ``return inner``. 1533 1534 .. attribute:: args 1535 .. attribute:: kwargs 1536 1537 Since ``ParamSpec`` captures both positional and keyword parameters, 1538 ``P.args`` and ``P.kwargs`` can be used to split a ``ParamSpec`` into its 1539 components. ``P.args`` represents the tuple of positional parameters in a 1540 given call and should only be used to annotate ``*args``. ``P.kwargs`` 1541 represents the mapping of keyword parameters to their values in a given call, 1542 and should be only be used to annotate ``**kwargs``. Both 1543 attributes require the annotated parameter to be in scope. At runtime, 1544 ``P.args`` and ``P.kwargs`` are instances respectively of 1545 :class:`ParamSpecArgs` and :class:`ParamSpecKwargs`. 1546 1547 .. attribute:: __name__ 1548 1549 The name of the parameter specification. 1550 1551 Parameter specification variables created with ``covariant=True`` or 1552 ``contravariant=True`` can be used to declare covariant or contravariant 1553 generic types. The ``bound`` argument is also accepted, similar to 1554 :class:`TypeVar`. However the actual semantics of these keywords are yet to 1555 be decided. 1556 1557 .. versionadded:: 3.10 1558 1559 .. note:: 1560 Only parameter specification variables defined in global scope can 1561 be pickled. 1562 1563 .. seealso:: 1564 * :pep:`612` -- Parameter Specification Variables (the PEP which introduced 1565 ``ParamSpec`` and ``Concatenate``). 1566 * :class:`Callable` and :class:`Concatenate`. 1567 1568.. data:: ParamSpecArgs 1569.. data:: ParamSpecKwargs 1570 1571 Arguments and keyword arguments attributes of a :class:`ParamSpec`. The 1572 ``P.args`` attribute of a ``ParamSpec`` is an instance of ``ParamSpecArgs``, 1573 and ``P.kwargs`` is an instance of ``ParamSpecKwargs``. They are intended 1574 for runtime introspection and have no special meaning to static type checkers. 1575 1576 Calling :func:`get_origin` on either of these objects will return the 1577 original ``ParamSpec``:: 1578 1579 P = ParamSpec("P") 1580 get_origin(P.args) # returns P 1581 get_origin(P.kwargs) # returns P 1582 1583 .. versionadded:: 3.10 1584 1585 1586Other special directives 1587"""""""""""""""""""""""" 1588 1589These are not used in annotations. They are building blocks for declaring types. 1590 1591.. class:: NamedTuple 1592 1593 Typed version of :func:`collections.namedtuple`. 1594 1595 Usage:: 1596 1597 class Employee(NamedTuple): 1598 name: str 1599 id: int 1600 1601 This is equivalent to:: 1602 1603 Employee = collections.namedtuple('Employee', ['name', 'id']) 1604 1605 To give a field a default value, you can assign to it in the class body:: 1606 1607 class Employee(NamedTuple): 1608 name: str 1609 id: int = 3 1610 1611 employee = Employee('Guido') 1612 assert employee.id == 3 1613 1614 Fields with a default value must come after any fields without a default. 1615 1616 The resulting class has an extra attribute ``__annotations__`` giving a 1617 dict that maps the field names to the field types. (The field names are in 1618 the ``_fields`` attribute and the default values are in the 1619 ``_field_defaults`` attribute, both of which are part of the :func:`~collections.namedtuple` 1620 API.) 1621 1622 ``NamedTuple`` subclasses can also have docstrings and methods:: 1623 1624 class Employee(NamedTuple): 1625 """Represents an employee.""" 1626 name: str 1627 id: int = 3 1628 1629 def __repr__(self) -> str: 1630 return f'<Employee {self.name}, id={self.id}>' 1631 1632 ``NamedTuple`` subclasses can be generic:: 1633 1634 class Group(NamedTuple, Generic[T]): 1635 key: T 1636 group: list[T] 1637 1638 Backward-compatible usage:: 1639 1640 Employee = NamedTuple('Employee', [('name', str), ('id', int)]) 1641 1642 .. versionchanged:: 3.6 1643 Added support for :pep:`526` variable annotation syntax. 1644 1645 .. versionchanged:: 3.6.1 1646 Added support for default values, methods, and docstrings. 1647 1648 .. versionchanged:: 3.8 1649 The ``_field_types`` and ``__annotations__`` attributes are 1650 now regular dictionaries instead of instances of ``OrderedDict``. 1651 1652 .. versionchanged:: 3.9 1653 Removed the ``_field_types`` attribute in favor of the more 1654 standard ``__annotations__`` attribute which has the same information. 1655 1656 .. versionchanged:: 3.11 1657 Added support for generic namedtuples. 1658 1659.. class:: NewType(name, tp) 1660 1661 A helper class to indicate a distinct type to a typechecker, 1662 see :ref:`distinct`. At runtime it returns an object that returns 1663 its argument when called. 1664 Usage:: 1665 1666 UserId = NewType('UserId', int) 1667 first_user = UserId(1) 1668 1669 .. attribute:: __module__ 1670 1671 The module in which the new type is defined. 1672 1673 .. attribute:: __name__ 1674 1675 The name of the new type. 1676 1677 .. attribute:: __supertype__ 1678 1679 The type that the new type is based on. 1680 1681 .. versionadded:: 3.5.2 1682 1683 .. versionchanged:: 3.10 1684 ``NewType`` is now a class rather than a function. 1685 1686.. class:: Protocol(Generic) 1687 1688 Base class for protocol classes. Protocol classes are defined like this:: 1689 1690 class Proto(Protocol): 1691 def meth(self) -> int: 1692 ... 1693 1694 Such classes are primarily used with static type checkers that recognize 1695 structural subtyping (static duck-typing), for example:: 1696 1697 class C: 1698 def meth(self) -> int: 1699 return 0 1700 1701 def func(x: Proto) -> int: 1702 return x.meth() 1703 1704 func(C()) # Passes static type check 1705 1706 See :pep:`544` for more details. Protocol classes decorated with 1707 :func:`runtime_checkable` (described later) act as simple-minded runtime 1708 protocols that check only the presence of given attributes, ignoring their 1709 type signatures. 1710 1711 Protocol classes can be generic, for example:: 1712 1713 T = TypeVar("T") 1714 1715 class GenProto(Protocol[T]): 1716 def meth(self) -> T: 1717 ... 1718 1719 .. versionadded:: 3.8 1720 1721.. decorator:: runtime_checkable 1722 1723 Mark a protocol class as a runtime protocol. 1724 1725 Such a protocol can be used with :func:`isinstance` and :func:`issubclass`. 1726 This raises :exc:`TypeError` when applied to a non-protocol class. This 1727 allows a simple-minded structural check, very similar to "one trick ponies" 1728 in :mod:`collections.abc` such as :class:`~collections.abc.Iterable`. For example:: 1729 1730 @runtime_checkable 1731 class Closable(Protocol): 1732 def close(self): ... 1733 1734 assert isinstance(open('/some/file'), Closable) 1735 1736 @runtime_checkable 1737 class Named(Protocol): 1738 name: str 1739 1740 import threading 1741 assert isinstance(threading.Thread(name='Bob'), Named) 1742 1743 .. note:: 1744 1745 :func:`!runtime_checkable` will check only the presence of the required 1746 methods or attributes, not their type signatures or types. 1747 For example, :class:`ssl.SSLObject` 1748 is a class, therefore it passes an :func:`issubclass` 1749 check against :data:`Callable`. However, the 1750 ``ssl.SSLObject.__init__`` method exists only to raise a 1751 :exc:`TypeError` with a more informative message, therefore making 1752 it impossible to call (instantiate) :class:`ssl.SSLObject`. 1753 1754 .. note:: 1755 1756 An :func:`isinstance` check against a runtime-checkable protocol can be 1757 surprisingly slow compared to an ``isinstance()`` check against 1758 a non-protocol class. Consider using alternative idioms such as 1759 :func:`hasattr` calls for structural checks in performance-sensitive 1760 code. 1761 1762 .. versionadded:: 3.8 1763 1764 1765.. class:: TypedDict(dict) 1766 1767 Special construct to add type hints to a dictionary. 1768 At runtime it is a plain :class:`dict`. 1769 1770 ``TypedDict`` declares a dictionary type that expects all of its 1771 instances to have a certain set of keys, where each key is 1772 associated with a value of a consistent type. This expectation 1773 is not checked at runtime but is only enforced by type checkers. 1774 Usage:: 1775 1776 class Point2D(TypedDict): 1777 x: int 1778 y: int 1779 label: str 1780 1781 a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK 1782 b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check 1783 1784 assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first') 1785 1786 To allow using this feature with older versions of Python that do not 1787 support :pep:`526`, ``TypedDict`` supports two additional equivalent 1788 syntactic forms: 1789 1790 * Using a literal :class:`dict` as the second argument:: 1791 1792 Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) 1793 1794 * Using keyword arguments:: 1795 1796 Point2D = TypedDict('Point2D', x=int, y=int, label=str) 1797 1798 .. deprecated-removed:: 3.11 3.13 1799 The keyword-argument syntax is deprecated in 3.11 and will be removed 1800 in 3.13. It may also be unsupported by static type checkers. 1801 1802 The functional syntax should also be used when any of the keys are not valid 1803 :ref:`identifiers <identifiers>`, for example because they are keywords or contain hyphens. 1804 Example:: 1805 1806 # raises SyntaxError 1807 class Point2D(TypedDict): 1808 in: int # 'in' is a keyword 1809 x-y: int # name with hyphens 1810 1811 # OK, functional syntax 1812 Point2D = TypedDict('Point2D', {'in': int, 'x-y': int}) 1813 1814 By default, all keys must be present in a ``TypedDict``. It is possible to 1815 mark individual keys as non-required using :data:`NotRequired`:: 1816 1817 class Point2D(TypedDict): 1818 x: int 1819 y: int 1820 label: NotRequired[str] 1821 1822 # Alternative syntax 1823 Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': NotRequired[str]}) 1824 1825 This means that a ``Point2D`` ``TypedDict`` can have the ``label`` 1826 key omitted. 1827 1828 It is also possible to mark all keys as non-required by default 1829 by specifying a totality of ``False``:: 1830 1831 class Point2D(TypedDict, total=False): 1832 x: int 1833 y: int 1834 1835 # Alternative syntax 1836 Point2D = TypedDict('Point2D', {'x': int, 'y': int}, total=False) 1837 1838 This means that a ``Point2D`` ``TypedDict`` can have any of the keys 1839 omitted. A type checker is only expected to support a literal ``False`` or 1840 ``True`` as the value of the ``total`` argument. ``True`` is the default, 1841 and makes all items defined in the class body required. 1842 1843 Individual keys of a ``total=False`` ``TypedDict`` can be marked as 1844 required using :data:`Required`:: 1845 1846 class Point2D(TypedDict, total=False): 1847 x: Required[int] 1848 y: Required[int] 1849 label: str 1850 1851 # Alternative syntax 1852 Point2D = TypedDict('Point2D', { 1853 'x': Required[int], 1854 'y': Required[int], 1855 'label': str 1856 }, total=False) 1857 1858 It is possible for a ``TypedDict`` type to inherit from one or more other ``TypedDict`` types 1859 using the class-based syntax. 1860 Usage:: 1861 1862 class Point3D(Point2D): 1863 z: int 1864 1865 ``Point3D`` has three items: ``x``, ``y`` and ``z``. It is equivalent to this 1866 definition:: 1867 1868 class Point3D(TypedDict): 1869 x: int 1870 y: int 1871 z: int 1872 1873 A ``TypedDict`` cannot inherit from a non-\ ``TypedDict`` class, 1874 except for :class:`Generic`. For example:: 1875 1876 class X(TypedDict): 1877 x: int 1878 1879 class Y(TypedDict): 1880 y: int 1881 1882 class Z(object): pass # A non-TypedDict class 1883 1884 class XY(X, Y): pass # OK 1885 1886 class XZ(X, Z): pass # raises TypeError 1887 1888 T = TypeVar('T') 1889 class XT(X, Generic[T]): pass # raises TypeError 1890 1891 A ``TypedDict`` can be generic:: 1892 1893 class Group(TypedDict, Generic[T]): 1894 key: T 1895 group: list[T] 1896 1897 A ``TypedDict`` can be introspected via annotations dicts 1898 (see :ref:`annotations-howto` for more information on annotations best practices), 1899 :attr:`__total__`, :attr:`__required_keys__`, and :attr:`__optional_keys__`. 1900 1901 .. attribute:: __total__ 1902 1903 ``Point2D.__total__`` gives the value of the ``total`` argument. 1904 Example:: 1905 1906 >>> from typing import TypedDict 1907 >>> class Point2D(TypedDict): pass 1908 >>> Point2D.__total__ 1909 True 1910 >>> class Point2D(TypedDict, total=False): pass 1911 >>> Point2D.__total__ 1912 False 1913 >>> class Point3D(Point2D): pass 1914 >>> Point3D.__total__ 1915 True 1916 1917 .. attribute:: __required_keys__ 1918 1919 .. versionadded:: 3.9 1920 1921 .. attribute:: __optional_keys__ 1922 1923 ``Point2D.__required_keys__`` and ``Point2D.__optional_keys__`` return 1924 :class:`frozenset` objects containing required and non-required keys, respectively. 1925 1926 Keys marked with :data:`Required` will always appear in ``__required_keys__`` 1927 and keys marked with :data:`NotRequired` will always appear in ``__optional_keys__``. 1928 1929 For backwards compatibility with Python 3.10 and below, 1930 it is also possible to use inheritance to declare both required and 1931 non-required keys in the same ``TypedDict`` . This is done by declaring a 1932 ``TypedDict`` with one value for the ``total`` argument and then 1933 inheriting from it in another ``TypedDict`` with a different value for 1934 ``total``:: 1935 1936 >>> class Point2D(TypedDict, total=False): 1937 ... x: int 1938 ... y: int 1939 ... 1940 >>> class Point3D(Point2D): 1941 ... z: int 1942 ... 1943 >>> Point3D.__required_keys__ == frozenset({'z'}) 1944 True 1945 >>> Point3D.__optional_keys__ == frozenset({'x', 'y'}) 1946 True 1947 1948 .. versionadded:: 3.9 1949 1950 See :pep:`589` for more examples and detailed rules of using ``TypedDict``. 1951 1952 .. versionadded:: 3.8 1953 1954 .. versionchanged:: 3.11 1955 Added support for marking individual keys as :data:`Required` or :data:`NotRequired`. 1956 See :pep:`655`. 1957 1958 .. versionchanged:: 3.11 1959 Added support for generic ``TypedDict``\ s. 1960 1961Generic concrete collections 1962---------------------------- 1963 1964Corresponding to built-in types 1965""""""""""""""""""""""""""""""" 1966 1967.. class:: Dict(dict, MutableMapping[KT, VT]) 1968 1969 A generic version of :class:`dict`. 1970 Useful for annotating return types. To annotate arguments it is preferred 1971 to use an abstract collection type such as :class:`Mapping`. 1972 1973 This type can be used as follows:: 1974 1975 def count_words(text: str) -> Dict[str, int]: 1976 ... 1977 1978 .. deprecated:: 3.9 1979 :class:`builtins.dict <dict>` now supports subscripting (``[]``). 1980 See :pep:`585` and :ref:`types-genericalias`. 1981 1982.. class:: List(list, MutableSequence[T]) 1983 1984 Generic version of :class:`list`. 1985 Useful for annotating return types. To annotate arguments it is preferred 1986 to use an abstract collection type such as :class:`Sequence` or 1987 :class:`Iterable`. 1988 1989 This type may be used as follows:: 1990 1991 T = TypeVar('T', int, float) 1992 1993 def vec2(x: T, y: T) -> List[T]: 1994 return [x, y] 1995 1996 def keep_positives(vector: Sequence[T]) -> List[T]: 1997 return [item for item in vector if item > 0] 1998 1999 .. deprecated:: 3.9 2000 :class:`builtins.list <list>` now supports subscripting (``[]``). 2001 See :pep:`585` and :ref:`types-genericalias`. 2002 2003.. class:: Set(set, MutableSet[T]) 2004 2005 A generic version of :class:`builtins.set <set>`. 2006 Useful for annotating return types. To annotate arguments it is preferred 2007 to use an abstract collection type such as :class:`AbstractSet`. 2008 2009 .. deprecated:: 3.9 2010 :class:`builtins.set <set>` now supports subscripting (``[]``). 2011 See :pep:`585` and :ref:`types-genericalias`. 2012 2013.. class:: FrozenSet(frozenset, AbstractSet[T_co]) 2014 2015 A generic version of :class:`builtins.frozenset <frozenset>`. 2016 2017 .. deprecated:: 3.9 2018 :class:`builtins.frozenset <frozenset>` 2019 now supports subscripting (``[]``). 2020 See :pep:`585` and :ref:`types-genericalias`. 2021 2022.. note:: :data:`Tuple` is a special form. 2023 2024Corresponding to types in :mod:`collections` 2025"""""""""""""""""""""""""""""""""""""""""""" 2026 2027.. class:: DefaultDict(collections.defaultdict, MutableMapping[KT, VT]) 2028 2029 A generic version of :class:`collections.defaultdict`. 2030 2031 .. versionadded:: 3.5.2 2032 2033 .. deprecated:: 3.9 2034 :class:`collections.defaultdict` now supports subscripting (``[]``). 2035 See :pep:`585` and :ref:`types-genericalias`. 2036 2037.. class:: OrderedDict(collections.OrderedDict, MutableMapping[KT, VT]) 2038 2039 A generic version of :class:`collections.OrderedDict`. 2040 2041 .. versionadded:: 3.7.2 2042 2043 .. deprecated:: 3.9 2044 :class:`collections.OrderedDict` now supports subscripting (``[]``). 2045 See :pep:`585` and :ref:`types-genericalias`. 2046 2047.. class:: ChainMap(collections.ChainMap, MutableMapping[KT, VT]) 2048 2049 A generic version of :class:`collections.ChainMap`. 2050 2051 .. versionadded:: 3.5.4 2052 .. versionadded:: 3.6.1 2053 2054 .. deprecated:: 3.9 2055 :class:`collections.ChainMap` now supports subscripting (``[]``). 2056 See :pep:`585` and :ref:`types-genericalias`. 2057 2058.. class:: Counter(collections.Counter, Dict[T, int]) 2059 2060 A generic version of :class:`collections.Counter`. 2061 2062 .. versionadded:: 3.5.4 2063 .. versionadded:: 3.6.1 2064 2065 .. deprecated:: 3.9 2066 :class:`collections.Counter` now supports subscripting (``[]``). 2067 See :pep:`585` and :ref:`types-genericalias`. 2068 2069.. class:: Deque(deque, MutableSequence[T]) 2070 2071 A generic version of :class:`collections.deque`. 2072 2073 .. versionadded:: 3.5.4 2074 .. versionadded:: 3.6.1 2075 2076 .. deprecated:: 3.9 2077 :class:`collections.deque` now supports subscripting (``[]``). 2078 See :pep:`585` and :ref:`types-genericalias`. 2079 2080Other concrete types 2081"""""""""""""""""""" 2082 2083.. class:: IO 2084 TextIO 2085 BinaryIO 2086 2087 Generic type ``IO[AnyStr]`` and its subclasses ``TextIO(IO[str])`` 2088 and ``BinaryIO(IO[bytes])`` 2089 represent the types of I/O streams such as returned by 2090 :func:`open`. 2091 2092 .. deprecated-removed:: 3.8 3.13 2093 The ``typing.io`` namespace is deprecated and will be removed. 2094 These types should be directly imported from ``typing`` instead. 2095 2096.. class:: Pattern 2097 Match 2098 2099 These type aliases 2100 correspond to the return types from :func:`re.compile` and 2101 :func:`re.match`. These types (and the corresponding functions) 2102 are generic in ``AnyStr`` and can be made specific by writing 2103 ``Pattern[str]``, ``Pattern[bytes]``, ``Match[str]``, or 2104 ``Match[bytes]``. 2105 2106 .. deprecated-removed:: 3.8 3.13 2107 The ``typing.re`` namespace is deprecated and will be removed. 2108 These types should be directly imported from ``typing`` instead. 2109 2110 .. deprecated:: 3.9 2111 Classes ``Pattern`` and ``Match`` from :mod:`re` now support ``[]``. 2112 See :pep:`585` and :ref:`types-genericalias`. 2113 2114.. class:: Text 2115 2116 ``Text`` is an alias for ``str``. It is provided to supply a forward 2117 compatible path for Python 2 code: in Python 2, ``Text`` is an alias for 2118 ``unicode``. 2119 2120 Use ``Text`` to indicate that a value must contain a unicode string in 2121 a manner that is compatible with both Python 2 and Python 3:: 2122 2123 def add_unicode_checkmark(text: Text) -> Text: 2124 return text + u' \u2713' 2125 2126 .. versionadded:: 3.5.2 2127 2128 .. deprecated:: 3.11 2129 Python 2 is no longer supported, and most type checkers also no longer 2130 support type checking Python 2 code. Removal of the alias is not 2131 currently planned, but users are encouraged to use 2132 :class:`str` instead of ``Text``. 2133 2134Abstract Base Classes 2135--------------------- 2136 2137Corresponding to collections in :mod:`collections.abc` 2138"""""""""""""""""""""""""""""""""""""""""""""""""""""" 2139 2140.. class:: AbstractSet(Collection[T_co]) 2141 2142 A generic version of :class:`collections.abc.Set`. 2143 2144 .. deprecated:: 3.9 2145 :class:`collections.abc.Set` now supports subscripting (``[]``). 2146 See :pep:`585` and :ref:`types-genericalias`. 2147 2148.. class:: ByteString(Sequence[int]) 2149 2150 This type represents the types :class:`bytes`, :class:`bytearray`, 2151 and :class:`memoryview` of byte sequences. 2152 2153 .. deprecated-removed:: 3.9 3.14 2154 Prefer ``typing_extensions.Buffer``, or a union like ``bytes | bytearray | memoryview``. 2155 2156.. class:: Collection(Sized, Iterable[T_co], Container[T_co]) 2157 2158 A generic version of :class:`collections.abc.Collection` 2159 2160 .. versionadded:: 3.6.0 2161 2162 .. deprecated:: 3.9 2163 :class:`collections.abc.Collection` now supports subscripting (``[]``). 2164 See :pep:`585` and :ref:`types-genericalias`. 2165 2166.. class:: Container(Generic[T_co]) 2167 2168 A generic version of :class:`collections.abc.Container`. 2169 2170 .. deprecated:: 3.9 2171 :class:`collections.abc.Container` now supports subscripting (``[]``). 2172 See :pep:`585` and :ref:`types-genericalias`. 2173 2174.. class:: ItemsView(MappingView, AbstractSet[tuple[KT_co, VT_co]]) 2175 2176 A generic version of :class:`collections.abc.ItemsView`. 2177 2178 .. deprecated:: 3.9 2179 :class:`collections.abc.ItemsView` now supports subscripting (``[]``). 2180 See :pep:`585` and :ref:`types-genericalias`. 2181 2182.. class:: KeysView(MappingView, AbstractSet[KT_co]) 2183 2184 A generic version of :class:`collections.abc.KeysView`. 2185 2186 .. deprecated:: 3.9 2187 :class:`collections.abc.KeysView` now supports subscripting (``[]``). 2188 See :pep:`585` and :ref:`types-genericalias`. 2189 2190.. class:: Mapping(Collection[KT], Generic[KT, VT_co]) 2191 2192 A generic version of :class:`collections.abc.Mapping`. 2193 This type can be used as follows:: 2194 2195 def get_position_in_index(word_list: Mapping[str, int], word: str) -> int: 2196 return word_list[word] 2197 2198 .. deprecated:: 3.9 2199 :class:`collections.abc.Mapping` now supports subscripting (``[]``). 2200 See :pep:`585` and :ref:`types-genericalias`. 2201 2202.. class:: MappingView(Sized) 2203 2204 A generic version of :class:`collections.abc.MappingView`. 2205 2206 .. deprecated:: 3.9 2207 :class:`collections.abc.MappingView` now supports subscripting (``[]``). 2208 See :pep:`585` and :ref:`types-genericalias`. 2209 2210.. class:: MutableMapping(Mapping[KT, VT]) 2211 2212 A generic version of :class:`collections.abc.MutableMapping`. 2213 2214 .. deprecated:: 3.9 2215 :class:`collections.abc.MutableMapping` 2216 now supports subscripting (``[]``). 2217 See :pep:`585` and :ref:`types-genericalias`. 2218 2219.. class:: MutableSequence(Sequence[T]) 2220 2221 A generic version of :class:`collections.abc.MutableSequence`. 2222 2223 .. deprecated:: 3.9 2224 :class:`collections.abc.MutableSequence` 2225 now supports subscripting (``[]``). 2226 See :pep:`585` and :ref:`types-genericalias`. 2227 2228.. class:: MutableSet(AbstractSet[T]) 2229 2230 A generic version of :class:`collections.abc.MutableSet`. 2231 2232 .. deprecated:: 3.9 2233 :class:`collections.abc.MutableSet` now supports subscripting (``[]``). 2234 See :pep:`585` and :ref:`types-genericalias`. 2235 2236.. class:: Sequence(Reversible[T_co], Collection[T_co]) 2237 2238 A generic version of :class:`collections.abc.Sequence`. 2239 2240 .. deprecated:: 3.9 2241 :class:`collections.abc.Sequence` now supports subscripting (``[]``). 2242 See :pep:`585` and :ref:`types-genericalias`. 2243 2244.. class:: ValuesView(MappingView, Collection[_VT_co]) 2245 2246 A generic version of :class:`collections.abc.ValuesView`. 2247 2248 .. deprecated:: 3.9 2249 :class:`collections.abc.ValuesView` now supports subscripting (``[]``). 2250 See :pep:`585` and :ref:`types-genericalias`. 2251 2252Corresponding to other types in :mod:`collections.abc` 2253"""""""""""""""""""""""""""""""""""""""""""""""""""""" 2254 2255.. class:: Iterable(Generic[T_co]) 2256 2257 A generic version of :class:`collections.abc.Iterable`. 2258 2259 .. deprecated:: 3.9 2260 :class:`collections.abc.Iterable` now supports subscripting (``[]``). 2261 See :pep:`585` and :ref:`types-genericalias`. 2262 2263.. class:: Iterator(Iterable[T_co]) 2264 2265 A generic version of :class:`collections.abc.Iterator`. 2266 2267 .. deprecated:: 3.9 2268 :class:`collections.abc.Iterator` now supports subscripting (``[]``). 2269 See :pep:`585` and :ref:`types-genericalias`. 2270 2271.. class:: Generator(Iterator[T_co], Generic[T_co, T_contra, V_co]) 2272 2273 A generator can be annotated by the generic type 2274 ``Generator[YieldType, SendType, ReturnType]``. For example:: 2275 2276 def echo_round() -> Generator[int, float, str]: 2277 sent = yield 0 2278 while sent >= 0: 2279 sent = yield round(sent) 2280 return 'Done' 2281 2282 Note that unlike many other generics in the typing module, the ``SendType`` 2283 of :class:`Generator` behaves contravariantly, not covariantly or 2284 invariantly. 2285 2286 If your generator will only yield values, set the ``SendType`` and 2287 ``ReturnType`` to ``None``:: 2288 2289 def infinite_stream(start: int) -> Generator[int, None, None]: 2290 while True: 2291 yield start 2292 start += 1 2293 2294 Alternatively, annotate your generator as having a return type of 2295 either ``Iterable[YieldType]`` or ``Iterator[YieldType]``:: 2296 2297 def infinite_stream(start: int) -> Iterator[int]: 2298 while True: 2299 yield start 2300 start += 1 2301 2302 .. deprecated:: 3.9 2303 :class:`collections.abc.Generator` now supports subscripting (``[]``). 2304 See :pep:`585` and :ref:`types-genericalias`. 2305 2306.. class:: Hashable 2307 2308 An alias to :class:`collections.abc.Hashable`. 2309 2310.. class:: Reversible(Iterable[T_co]) 2311 2312 A generic version of :class:`collections.abc.Reversible`. 2313 2314 .. deprecated:: 3.9 2315 :class:`collections.abc.Reversible` now supports subscripting (``[]``). 2316 See :pep:`585` and :ref:`types-genericalias`. 2317 2318.. class:: Sized 2319 2320 An alias to :class:`collections.abc.Sized`. 2321 2322Asynchronous programming 2323"""""""""""""""""""""""" 2324 2325.. class:: Coroutine(Awaitable[V_co], Generic[T_co, T_contra, V_co]) 2326 2327 A generic version of :class:`collections.abc.Coroutine`. 2328 The variance and order of type variables 2329 correspond to those of :class:`Generator`, for example:: 2330 2331 from collections.abc import Coroutine 2332 c: Coroutine[list[str], str, int] # Some coroutine defined elsewhere 2333 x = c.send('hi') # Inferred type of 'x' is list[str] 2334 async def bar() -> None: 2335 y = await c # Inferred type of 'y' is int 2336 2337 .. versionadded:: 3.5.3 2338 2339 .. deprecated:: 3.9 2340 :class:`collections.abc.Coroutine` now supports subscripting (``[]``). 2341 See :pep:`585` and :ref:`types-genericalias`. 2342 2343.. class:: AsyncGenerator(AsyncIterator[T_co], Generic[T_co, T_contra]) 2344 2345 An async generator can be annotated by the generic type 2346 ``AsyncGenerator[YieldType, SendType]``. For example:: 2347 2348 async def echo_round() -> AsyncGenerator[int, float]: 2349 sent = yield 0 2350 while sent >= 0.0: 2351 rounded = await round(sent) 2352 sent = yield rounded 2353 2354 Unlike normal generators, async generators cannot return a value, so there 2355 is no ``ReturnType`` type parameter. As with :class:`Generator`, the 2356 ``SendType`` behaves contravariantly. 2357 2358 If your generator will only yield values, set the ``SendType`` to 2359 ``None``:: 2360 2361 async def infinite_stream(start: int) -> AsyncGenerator[int, None]: 2362 while True: 2363 yield start 2364 start = await increment(start) 2365 2366 Alternatively, annotate your generator as having a return type of 2367 either ``AsyncIterable[YieldType]`` or ``AsyncIterator[YieldType]``:: 2368 2369 async def infinite_stream(start: int) -> AsyncIterator[int]: 2370 while True: 2371 yield start 2372 start = await increment(start) 2373 2374 .. versionadded:: 3.6.1 2375 2376 .. deprecated:: 3.9 2377 :class:`collections.abc.AsyncGenerator` 2378 now supports subscripting (``[]``). 2379 See :pep:`585` and :ref:`types-genericalias`. 2380 2381.. class:: AsyncIterable(Generic[T_co]) 2382 2383 A generic version of :class:`collections.abc.AsyncIterable`. 2384 2385 .. versionadded:: 3.5.2 2386 2387 .. deprecated:: 3.9 2388 :class:`collections.abc.AsyncIterable` now supports subscripting (``[]``). 2389 See :pep:`585` and :ref:`types-genericalias`. 2390 2391.. class:: AsyncIterator(AsyncIterable[T_co]) 2392 2393 A generic version of :class:`collections.abc.AsyncIterator`. 2394 2395 .. versionadded:: 3.5.2 2396 2397 .. deprecated:: 3.9 2398 :class:`collections.abc.AsyncIterator` now supports subscripting (``[]``). 2399 See :pep:`585` and :ref:`types-genericalias`. 2400 2401.. class:: Awaitable(Generic[T_co]) 2402 2403 A generic version of :class:`collections.abc.Awaitable`. 2404 2405 .. versionadded:: 3.5.2 2406 2407 .. deprecated:: 3.9 2408 :class:`collections.abc.Awaitable` now supports subscripting (``[]``). 2409 See :pep:`585` and :ref:`types-genericalias`. 2410 2411 2412Context manager types 2413""""""""""""""""""""" 2414 2415.. class:: ContextManager(Generic[T_co]) 2416 2417 A generic version of :class:`contextlib.AbstractContextManager`. 2418 2419 .. versionadded:: 3.5.4 2420 .. versionadded:: 3.6.0 2421 2422 .. deprecated:: 3.9 2423 :class:`contextlib.AbstractContextManager` 2424 now supports subscripting (``[]``). 2425 See :pep:`585` and :ref:`types-genericalias`. 2426 2427.. class:: AsyncContextManager(Generic[T_co]) 2428 2429 A generic version of :class:`contextlib.AbstractAsyncContextManager`. 2430 2431 .. versionadded:: 3.5.4 2432 .. versionadded:: 3.6.2 2433 2434 .. deprecated:: 3.9 2435 :class:`contextlib.AbstractAsyncContextManager` 2436 now supports subscripting (``[]``). 2437 See :pep:`585` and :ref:`types-genericalias`. 2438 2439Protocols 2440--------- 2441 2442These protocols are decorated with :func:`runtime_checkable`. 2443 2444.. class:: SupportsAbs 2445 2446 An ABC with one abstract method ``__abs__`` that is covariant 2447 in its return type. 2448 2449.. class:: SupportsBytes 2450 2451 An ABC with one abstract method ``__bytes__``. 2452 2453.. class:: SupportsComplex 2454 2455 An ABC with one abstract method ``__complex__``. 2456 2457.. class:: SupportsFloat 2458 2459 An ABC with one abstract method ``__float__``. 2460 2461.. class:: SupportsIndex 2462 2463 An ABC with one abstract method ``__index__``. 2464 2465 .. versionadded:: 3.8 2466 2467.. class:: SupportsInt 2468 2469 An ABC with one abstract method ``__int__``. 2470 2471.. class:: SupportsRound 2472 2473 An ABC with one abstract method ``__round__`` 2474 that is covariant in its return type. 2475 2476Functions and decorators 2477------------------------ 2478 2479.. function:: cast(typ, val) 2480 2481 Cast a value to a type. 2482 2483 This returns the value unchanged. To the type checker this 2484 signals that the return value has the designated type, but at 2485 runtime we intentionally don't check anything (we want this 2486 to be as fast as possible). 2487 2488.. function:: assert_type(val, typ, /) 2489 2490 Ask a static type checker to confirm that *val* has an inferred type of *typ*. 2491 2492 At runtime this does nothing: it returns the first argument unchanged with no 2493 checks or side effects, no matter the actual type of the argument. 2494 2495 When a static type checker encounters a call to ``assert_type()``, it 2496 emits an error if the value is not of the specified type:: 2497 2498 def greet(name: str) -> None: 2499 assert_type(name, str) # OK, inferred type of `name` is `str` 2500 assert_type(name, int) # type checker error 2501 2502 This function is useful for ensuring the type checker's understanding of a 2503 script is in line with the developer's intentions:: 2504 2505 def complex_function(arg: object): 2506 # Do some complex type-narrowing logic, 2507 # after which we hope the inferred type will be `int` 2508 ... 2509 # Test whether the type checker correctly understands our function 2510 assert_type(arg, int) 2511 2512 .. versionadded:: 3.11 2513 2514.. function:: assert_never(arg, /) 2515 2516 Ask a static type checker to confirm that a line of code is unreachable. 2517 2518 Example:: 2519 2520 def int_or_str(arg: int | str) -> None: 2521 match arg: 2522 case int(): 2523 print("It's an int") 2524 case str(): 2525 print("It's a str") 2526 case _ as unreachable: 2527 assert_never(unreachable) 2528 2529 Here, the annotations allow the type checker to infer that the 2530 last case can never execute, because ``arg`` is either 2531 an :class:`int` or a :class:`str`, and both options are covered by 2532 earlier cases. 2533 If a type checker finds that a call to ``assert_never()`` is 2534 reachable, it will emit an error. For example, if the type annotation 2535 for ``arg`` was instead ``int | str | float``, the type checker would 2536 emit an error pointing out that ``unreachable`` is of type :class:`float`. 2537 For a call to ``assert_never`` to pass type checking, the inferred type of 2538 the argument passed in must be the bottom type, :data:`Never`, and nothing 2539 else. 2540 2541 At runtime, this throws an exception when called. 2542 2543 .. seealso:: 2544 `Unreachable Code and Exhaustiveness Checking 2545 <https://typing.readthedocs.io/en/latest/source/unreachable.html>`__ has more 2546 information about exhaustiveness checking with static typing. 2547 2548 .. versionadded:: 3.11 2549 2550.. function:: reveal_type(obj, /) 2551 2552 Reveal the inferred static type of an expression. 2553 2554 When a static type checker encounters a call to this function, 2555 it emits a diagnostic with the type of the argument. For example:: 2556 2557 x: int = 1 2558 reveal_type(x) # Revealed type is "builtins.int" 2559 2560 This can be useful when you want to debug how your type checker 2561 handles a particular piece of code. 2562 2563 The function returns its argument unchanged, which allows using 2564 it within an expression:: 2565 2566 x = reveal_type(1) # Revealed type is "builtins.int" 2567 2568 Most type checkers support ``reveal_type()`` anywhere, even if the 2569 name is not imported from ``typing``. Importing the name from 2570 ``typing`` allows your code to run without runtime errors and 2571 communicates intent more clearly. 2572 2573 At runtime, this function prints the runtime type of its argument to stderr 2574 and returns it unchanged:: 2575 2576 x = reveal_type(1) # prints "Runtime type is int" 2577 print(x) # prints "1" 2578 2579 .. versionadded:: 3.11 2580 2581.. decorator:: dataclass_transform 2582 2583 :data:`~typing.dataclass_transform` may be used to 2584 decorate a class, metaclass, or a function that is itself a decorator. 2585 The presence of ``@dataclass_transform()`` tells a static type checker that the 2586 decorated object performs runtime "magic" that 2587 transforms a class, giving it :func:`dataclasses.dataclass`-like behaviors. 2588 2589 Example usage with a decorator function:: 2590 2591 T = TypeVar("T") 2592 2593 @dataclass_transform() 2594 def create_model(cls: type[T]) -> type[T]: 2595 ... 2596 return cls 2597 2598 @create_model 2599 class CustomerModel: 2600 id: int 2601 name: str 2602 2603 On a base class:: 2604 2605 @dataclass_transform() 2606 class ModelBase: ... 2607 2608 class CustomerModel(ModelBase): 2609 id: int 2610 name: str 2611 2612 On a metaclass:: 2613 2614 @dataclass_transform() 2615 class ModelMeta(type): ... 2616 2617 class ModelBase(metaclass=ModelMeta): ... 2618 2619 class CustomerModel(ModelBase): 2620 id: int 2621 name: str 2622 2623 The ``CustomerModel`` classes defined above will 2624 be treated by type checkers similarly to classes created with 2625 :func:`@dataclasses.dataclass <dataclasses.dataclass>`. 2626 For example, type checkers will assume these classes have 2627 ``__init__`` methods that accept ``id`` and ``name``. 2628 2629 The decorated class, metaclass, or function may accept the following bool 2630 arguments which type checkers will assume have the same effect as they 2631 would have on the 2632 :func:`@dataclasses.dataclass<dataclasses.dataclass>` decorator: ``init``, 2633 ``eq``, ``order``, ``unsafe_hash``, ``frozen``, ``match_args``, 2634 ``kw_only``, and ``slots``. It must be possible for the value of these 2635 arguments (``True`` or ``False``) to be statically evaluated. 2636 2637 The arguments to the ``dataclass_transform`` decorator can be used to 2638 customize the default behaviors of the decorated class, metaclass, or 2639 function: 2640 2641 * ``eq_default`` indicates whether the ``eq`` parameter is assumed to be 2642 ``True`` or ``False`` if it is omitted by the caller. 2643 * ``order_default`` indicates whether the ``order`` parameter is 2644 assumed to be True or False if it is omitted by the caller. 2645 * ``kw_only_default`` indicates whether the ``kw_only`` parameter is 2646 assumed to be True or False if it is omitted by the caller. 2647 * ``field_specifiers`` specifies a static list of supported classes 2648 or functions that describe fields, similar to ``dataclasses.field()``. 2649 * Arbitrary other keyword arguments are accepted in order to allow for 2650 possible future extensions. 2651 2652 Type checkers recognize the following optional arguments on field 2653 specifiers: 2654 2655 * ``init`` indicates whether the field should be included in the 2656 synthesized ``__init__`` method. If unspecified, ``init`` defaults to 2657 ``True``. 2658 * ``default`` provides the default value for the field. 2659 * ``default_factory`` provides a runtime callback that returns the 2660 default value for the field. If neither ``default`` nor 2661 ``default_factory`` are specified, the field is assumed to have no 2662 default value and must be provided a value when the class is 2663 instantiated. 2664 * ``factory`` is an alias for ``default_factory``. 2665 * ``kw_only`` indicates whether the field should be marked as 2666 keyword-only. If ``True``, the field will be keyword-only. If 2667 ``False``, it will not be keyword-only. If unspecified, the value of 2668 the ``kw_only`` parameter on the object decorated with 2669 ``dataclass_transform`` will be used, or if that is unspecified, the 2670 value of ``kw_only_default`` on ``dataclass_transform`` will be used. 2671 * ``alias`` provides an alternative name for the field. This alternative 2672 name is used in the synthesized ``__init__`` method. 2673 2674 At runtime, this decorator records its arguments in the 2675 ``__dataclass_transform__`` attribute on the decorated object. 2676 It has no other runtime effect. 2677 2678 See :pep:`681` for more details. 2679 2680 .. versionadded:: 3.11 2681 2682.. decorator:: overload 2683 2684 The ``@overload`` decorator allows describing functions and methods 2685 that support multiple different combinations of argument types. A series 2686 of ``@overload``-decorated definitions must be followed by exactly one 2687 non-``@overload``-decorated definition (for the same function/method). 2688 The ``@overload``-decorated definitions are for the benefit of the 2689 type checker only, since they will be overwritten by the 2690 non-``@overload``-decorated definition, while the latter is used at 2691 runtime but should be ignored by a type checker. At runtime, calling 2692 a ``@overload``-decorated function directly will raise 2693 :exc:`NotImplementedError`. An example of overload that gives a more 2694 precise type than can be expressed using a union or a type variable:: 2695 2696 @overload 2697 def process(response: None) -> None: 2698 ... 2699 @overload 2700 def process(response: int) -> tuple[int, str]: 2701 ... 2702 @overload 2703 def process(response: bytes) -> str: 2704 ... 2705 def process(response): 2706 <actual implementation> 2707 2708 See :pep:`484` for more details and comparison with other typing semantics. 2709 2710 .. versionchanged:: 3.11 2711 Overloaded functions can now be introspected at runtime using 2712 :func:`get_overloads`. 2713 2714 2715.. function:: get_overloads(func) 2716 2717 Return a sequence of :func:`@overload <overload>`-decorated definitions for 2718 *func*. *func* is the function object for the implementation of the 2719 overloaded function. For example, given the definition of ``process`` in 2720 the documentation for :func:`@overload <overload>`, 2721 ``get_overloads(process)`` will return a sequence of three function objects 2722 for the three defined overloads. If called on a function with no overloads, 2723 ``get_overloads()`` returns an empty sequence. 2724 2725 ``get_overloads()`` can be used for introspecting an overloaded function at 2726 runtime. 2727 2728 .. versionadded:: 3.11 2729 2730 2731.. function:: clear_overloads() 2732 2733 Clear all registered overloads in the internal registry. This can be used 2734 to reclaim the memory used by the registry. 2735 2736 .. versionadded:: 3.11 2737 2738 2739.. decorator:: final 2740 2741 A decorator to indicate to type checkers that the decorated method 2742 cannot be overridden, and the decorated class cannot be subclassed. 2743 For example:: 2744 2745 class Base: 2746 @final 2747 def done(self) -> None: 2748 ... 2749 class Sub(Base): 2750 def done(self) -> None: # Error reported by type checker 2751 ... 2752 2753 @final 2754 class Leaf: 2755 ... 2756 class Other(Leaf): # Error reported by type checker 2757 ... 2758 2759 There is no runtime checking of these properties. See :pep:`591` for 2760 more details. 2761 2762 .. versionadded:: 3.8 2763 2764 .. versionchanged:: 3.11 2765 The decorator will now set the ``__final__`` attribute to ``True`` 2766 on the decorated object. Thus, a check like 2767 ``if getattr(obj, "__final__", False)`` can be used at runtime 2768 to determine whether an object ``obj`` has been marked as final. 2769 If the decorated object does not support setting attributes, 2770 the decorator returns the object unchanged without raising an exception. 2771 2772 2773.. decorator:: no_type_check 2774 2775 Decorator to indicate that annotations are not type hints. 2776 2777 This works as class or function :term:`decorator`. With a class, it 2778 applies recursively to all methods and classes defined in that class 2779 (but not to methods defined in its superclasses or subclasses). 2780 2781 This mutates the function(s) in place. 2782 2783.. decorator:: no_type_check_decorator 2784 2785 Decorator to give another decorator the :func:`no_type_check` effect. 2786 2787 This wraps the decorator with something that wraps the decorated 2788 function in :func:`no_type_check`. 2789 2790.. decorator:: type_check_only 2791 2792 Decorator to mark a class or function to be unavailable at runtime. 2793 2794 This decorator is itself not available at runtime. It is mainly 2795 intended to mark classes that are defined in type stub files if 2796 an implementation returns an instance of a private class:: 2797 2798 @type_check_only 2799 class Response: # private or not available at runtime 2800 code: int 2801 def get_header(self, name: str) -> str: ... 2802 2803 def fetch_response() -> Response: ... 2804 2805 Note that returning instances of private classes is not recommended. 2806 It is usually preferable to make such classes public. 2807 2808Introspection helpers 2809--------------------- 2810 2811.. function:: get_type_hints(obj, globalns=None, localns=None, include_extras=False) 2812 2813 Return a dictionary containing type hints for a function, method, module 2814 or class object. 2815 2816 This is often the same as ``obj.__annotations__``. In addition, 2817 forward references encoded as string literals are handled by evaluating 2818 them in ``globals`` and ``locals`` namespaces. For a class ``C``, return 2819 a dictionary constructed by merging all the ``__annotations__`` along 2820 ``C.__mro__`` in reverse order. 2821 2822 The function recursively replaces all ``Annotated[T, ...]`` with ``T``, 2823 unless ``include_extras`` is set to ``True`` (see :class:`Annotated` for 2824 more information). For example:: 2825 2826 class Student(NamedTuple): 2827 name: Annotated[str, 'some marker'] 2828 2829 get_type_hints(Student) == {'name': str} 2830 get_type_hints(Student, include_extras=False) == {'name': str} 2831 get_type_hints(Student, include_extras=True) == { 2832 'name': Annotated[str, 'some marker'] 2833 } 2834 2835 .. note:: 2836 2837 :func:`get_type_hints` does not work with imported 2838 :ref:`type aliases <type-aliases>` that include forward references. 2839 Enabling postponed evaluation of annotations (:pep:`563`) may remove 2840 the need for most forward references. 2841 2842 .. versionchanged:: 3.9 2843 Added ``include_extras`` parameter as part of :pep:`593`. 2844 2845 .. versionchanged:: 3.11 2846 Previously, ``Optional[t]`` was added for function and method annotations 2847 if a default value equal to ``None`` was set. 2848 Now the annotation is returned unchanged. 2849 2850.. function:: get_origin(tp) 2851 2852 Get the unsubscripted version of a type: for a typing object of the form 2853 ``X[Y, Z, ...]`` return ``X``. If ``X`` is a generic alias for a builtin or 2854 :mod:`collections` class, it gets normalized to the original class. 2855 If ``X`` is an instance of :class:`ParamSpecArgs` or :class:`ParamSpecKwargs`, 2856 return the underlying :class:`ParamSpec`. 2857 Return ``None`` for unsupported objects. 2858 Examples:: 2859 2860 assert get_origin(str) is None 2861 assert get_origin(Dict[str, int]) is dict 2862 assert get_origin(Union[int, str]) is Union 2863 P = ParamSpec('P') 2864 assert get_origin(P.args) is P 2865 assert get_origin(P.kwargs) is P 2866 2867 .. versionadded:: 3.8 2868 2869.. function:: get_args(tp) 2870 2871 Get type arguments with all substitutions performed: for a typing object 2872 of the form ``X[Y, Z, ...]`` return ``(Y, Z, ...)``. 2873 If ``X`` is a union or :class:`Literal` contained in another 2874 generic type, the order of ``(Y, Z, ...)`` may be different from the order 2875 of the original arguments ``[Y, Z, ...]`` due to type caching. 2876 Return ``()`` for unsupported objects. 2877 Examples:: 2878 2879 assert get_args(int) == () 2880 assert get_args(Dict[int, str]) == (int, str) 2881 assert get_args(Union[int, str]) == (int, str) 2882 2883 .. versionadded:: 3.8 2884 2885.. function:: is_typeddict(tp) 2886 2887 Check if a type is a :class:`TypedDict`. 2888 2889 For example:: 2890 2891 class Film(TypedDict): 2892 title: str 2893 year: int 2894 2895 is_typeddict(Film) # => True 2896 is_typeddict(list | str) # => False 2897 2898 .. versionadded:: 3.10 2899 2900.. class:: ForwardRef 2901 2902 A class used for internal typing representation of string forward references. 2903 For example, ``List["SomeClass"]`` is implicitly transformed into 2904 ``List[ForwardRef("SomeClass")]``. This class should not be instantiated by 2905 a user, but may be used by introspection tools. 2906 2907 .. note:: 2908 :pep:`585` generic types such as ``list["SomeClass"]`` will not be 2909 implicitly transformed into ``list[ForwardRef("SomeClass")]`` and thus 2910 will not automatically resolve to ``list[SomeClass]``. 2911 2912 .. versionadded:: 3.7.4 2913 2914Constant 2915-------- 2916 2917.. data:: TYPE_CHECKING 2918 2919 A special constant that is assumed to be ``True`` by 3rd party static 2920 type checkers. It is ``False`` at runtime. Usage:: 2921 2922 if TYPE_CHECKING: 2923 import expensive_mod 2924 2925 def fun(arg: 'expensive_mod.SomeType') -> None: 2926 local_var: expensive_mod.AnotherType = other_fun() 2927 2928 The first type annotation must be enclosed in quotes, making it a 2929 "forward reference", to hide the ``expensive_mod`` reference from the 2930 interpreter runtime. Type annotations for local variables are not 2931 evaluated, so the second annotation does not need to be enclosed in quotes. 2932 2933 .. note:: 2934 2935 If ``from __future__ import annotations`` is used, 2936 annotations are not evaluated at function definition time. 2937 Instead, they are stored as strings in ``__annotations__``. 2938 This makes it unnecessary to use quotes around the annotation 2939 (see :pep:`563`). 2940 2941 .. versionadded:: 3.5.2 2942 2943Deprecation Timeline of Major Features 2944====================================== 2945 2946Certain features in ``typing`` are deprecated and may be removed in a future 2947version of Python. The following table summarizes major deprecations for your 2948convenience. This is subject to change, and not all deprecations are listed. 2949 2950+----------------------------------+---------------+-------------------+----------------+ 2951| Feature | Deprecated in | Projected removal | PEP/issue | 2952+==================================+===============+===================+================+ 2953| ``typing.io`` and ``typing.re`` | 3.8 | 3.13 | :issue:`38291` | 2954| submodules | | | | 2955+----------------------------------+---------------+-------------------+----------------+ 2956| ``typing`` versions of standard | 3.9 | Undecided | :pep:`585` | 2957| collections | | | | 2958+----------------------------------+---------------+-------------------+----------------+ 2959| ``typing.ByteString`` | 3.9 | 3.14 | :gh:`91896` | 2960+----------------------------------+---------------+-------------------+----------------+ 2961| ``typing.Text`` | 3.11 | Undecided | :gh:`92332` | 2962+----------------------------------+---------------+-------------------+----------------+ 2963