diff options
| author | Craig Jennings <c@cjennings.net> | 2024-04-07 13:41:34 -0500 |
|---|---|---|
| committer | Craig Jennings <c@cjennings.net> | 2024-04-07 13:41:34 -0500 |
| commit | 754bbf7a25a8dda49b5d08ef0d0443bbf5af0e36 (patch) | |
| tree | f1190704f78f04a2b0b4c977d20fe96a828377f1 /devdocs/python~3.12/library%2Ftyping.html | |
new repository
Diffstat (limited to 'devdocs/python~3.12/library%2Ftyping.html')
| -rw-r--r-- | devdocs/python~3.12/library%2Ftyping.html | 1504 |
1 files changed, 1504 insertions, 0 deletions
diff --git a/devdocs/python~3.12/library%2Ftyping.html b/devdocs/python~3.12/library%2Ftyping.html new file mode 100644 index 00000000..4e46541e --- /dev/null +++ b/devdocs/python~3.12/library%2Ftyping.html @@ -0,0 +1,1504 @@ + <h1>typing — Support for type hints</h1> <span class="target" id="module-typing"></span><div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.</span></p> </div> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/typing.py">Lib/typing.py</a></p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as <a class="reference internal" href="../glossary#term-static-type-checker"><span class="xref std std-term">type checkers</span></a>, IDEs, linters, etc.</p> </div> <p>This module provides runtime support for type hints. For the original specification of the typing system, see <span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-0484/"><strong>PEP 484</strong></a>. For a simplified introduction to type hints, see <span class="target" id="index-1"></span><a class="pep reference external" href="https://peps.python.org/pep-0483/"><strong>PEP 483</strong></a>.</p> <p>The function below takes and returns a string and is annotated as follows:</p> <pre data-language="python">def greeting(name: str) -> str: + return 'Hello ' + name +</pre> <p>In the function <code>greeting</code>, the argument <code>name</code> is expected to be of type <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a> and the return type <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a>. Subtypes are accepted as arguments.</p> <p>New features are frequently added to the <code>typing</code> module. The <a class="reference external" href="https://pypi.org/project/typing-extensions/">typing_extensions</a> package provides backports of these new features to older versions of Python.</p> <p>For a summary of deprecated features and a deprecation timeline, please see <a class="reference internal" href="#deprecation-timeline-of-major-features">Deprecation Timeline of Major Features</a>.</p> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt><a class="reference external" href="https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html">“Typing cheat sheet”</a></dt> +<dd> +<p>A quick overview of type hints (hosted at the mypy docs)</p> </dd> <dt>“Type System Reference” section of <a class="reference external" href="https://mypy.readthedocs.io/en/stable/index.html">the mypy docs</a> +</dt> +<dd> +<p>The Python typing system is standardised via PEPs, so this reference should broadly apply to most Python type checkers. (Some parts may still be specific to mypy.)</p> </dd> <dt><a class="reference external" href="https://typing.readthedocs.io/en/latest/">“Static Typing with Python”</a></dt> +<dd> +<p>Type-checker-agnostic documentation written by the community detailing type system features, useful typing related tools and typing best practices.</p> </dd> </dl> </div> <section id="relevant-peps"> <span id="id1"></span><h2>Relevant PEPs</h2> <p>Since the initial introduction of type hints in <span class="target" id="index-2"></span><a class="pep reference external" href="https://peps.python.org/pep-0484/"><strong>PEP 484</strong></a> and <span class="target" id="index-3"></span><a class="pep reference external" href="https://peps.python.org/pep-0483/"><strong>PEP 483</strong></a>, a number of PEPs have modified and enhanced Python’s framework for type annotations:</p> <details> <summary><a style="cursor:pointer;">The full list of PEPs</a></summary><ul class="simple"> <li> +<dl class="simple"> <dt> +<span class="target" id="index-4"></span><a class="pep reference external" href="https://peps.python.org/pep-0526/"><strong>PEP 526</strong></a>: Syntax for Variable Annotations</dt> +<dd> +<p><em>Introducing</em> syntax for annotating variables outside of function definitions, and <a class="reference internal" href="#typing.ClassVar" title="typing.ClassVar"><code>ClassVar</code></a></p> </dd> </dl> </li> <li> +<dl class="simple"> <dt> +<span class="target" id="index-5"></span><a class="pep reference external" href="https://peps.python.org/pep-0544/"><strong>PEP 544</strong></a>: Protocols: Structural subtyping (static duck typing)</dt> +<dd> +<p><em>Introducing</em> <a class="reference internal" href="#typing.Protocol" title="typing.Protocol"><code>Protocol</code></a> and the <a class="reference internal" href="#typing.runtime_checkable" title="typing.runtime_checkable"><code>@runtime_checkable</code></a> decorator</p> </dd> </dl> </li> <li> +<dl class="simple"> <dt> +<span class="target" id="index-6"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a>: Type Hinting Generics In Standard Collections</dt> +<dd> +<p><em>Introducing</em> <a class="reference internal" href="types#types.GenericAlias" title="types.GenericAlias"><code>types.GenericAlias</code></a> and the ability to use standard library classes as <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">generic types</span></a></p> </dd> </dl> </li> <li> +<dl class="simple"> <dt> +<span class="target" id="index-7"></span><a class="pep reference external" href="https://peps.python.org/pep-0586/"><strong>PEP 586</strong></a>: Literal Types</dt> +<dd> +<p><em>Introducing</em> <a class="reference internal" href="#typing.Literal" title="typing.Literal"><code>Literal</code></a></p> </dd> </dl> </li> <li> +<dl class="simple"> <dt> +<span class="target" id="index-8"></span><a class="pep reference external" href="https://peps.python.org/pep-0589/"><strong>PEP 589</strong></a>: TypedDict: Type Hints for Dictionaries with a Fixed Set of Keys</dt> +<dd> +<p><em>Introducing</em> <a class="reference internal" href="#typing.TypedDict" title="typing.TypedDict"><code>TypedDict</code></a></p> </dd> </dl> </li> <li> +<dl class="simple"> <dt> +<span class="target" id="index-9"></span><a class="pep reference external" href="https://peps.python.org/pep-0591/"><strong>PEP 591</strong></a>: Adding a final qualifier to typing</dt> +<dd> +<p><em>Introducing</em> <a class="reference internal" href="#typing.Final" title="typing.Final"><code>Final</code></a> and the <a class="reference internal" href="#typing.final" title="typing.final"><code>@final</code></a> decorator</p> </dd> </dl> </li> <li> +<dl class="simple"> <dt> +<span class="target" id="index-10"></span><a class="pep reference external" href="https://peps.python.org/pep-0593/"><strong>PEP 593</strong></a>: Flexible function and variable annotations</dt> +<dd> +<p><em>Introducing</em> <a class="reference internal" href="#typing.Annotated" title="typing.Annotated"><code>Annotated</code></a></p> </dd> </dl> </li> <li> +<dl class="simple"> <dt> +<code>PEP 604: Allow writing union types as X | Y</code> </dt> +<dd> +<p><em>Introducing</em> <a class="reference internal" href="types#types.UnionType" title="types.UnionType"><code>types.UnionType</code></a> and the ability to use the binary-or operator <code>|</code> to signify a <a class="reference internal" href="stdtypes#types-union"><span class="std std-ref">union of types</span></a></p> </dd> </dl> </li> <li> +<dl class="simple"> <dt> +<span class="target" id="index-12"></span><a class="pep reference external" href="https://peps.python.org/pep-0612/"><strong>PEP 612</strong></a>: Parameter Specification Variables</dt> +<dd> +<p><em>Introducing</em> <a class="reference internal" href="#typing.ParamSpec" title="typing.ParamSpec"><code>ParamSpec</code></a> and <a class="reference internal" href="#typing.Concatenate" title="typing.Concatenate"><code>Concatenate</code></a></p> </dd> </dl> </li> <li> +<dl class="simple"> <dt> +<span class="target" id="index-13"></span><a class="pep reference external" href="https://peps.python.org/pep-0613/"><strong>PEP 613</strong></a>: Explicit Type Aliases</dt> +<dd> +<p><em>Introducing</em> <a class="reference internal" href="#typing.TypeAlias" title="typing.TypeAlias"><code>TypeAlias</code></a></p> </dd> </dl> </li> <li> +<dl class="simple"> <dt> +<span class="target" id="index-14"></span><a class="pep reference external" href="https://peps.python.org/pep-0646/"><strong>PEP 646</strong></a>: Variadic Generics</dt> +<dd> +<p><em>Introducing</em> <a class="reference internal" href="#typing.TypeVarTuple" title="typing.TypeVarTuple"><code>TypeVarTuple</code></a></p> </dd> </dl> </li> <li> +<dl class="simple"> <dt> +<span class="target" id="index-15"></span><a class="pep reference external" href="https://peps.python.org/pep-0647/"><strong>PEP 647</strong></a>: User-Defined Type Guards</dt> +<dd> +<p><em>Introducing</em> <a class="reference internal" href="#typing.TypeGuard" title="typing.TypeGuard"><code>TypeGuard</code></a></p> </dd> </dl> </li> <li> +<dl class="simple"> <dt> +<span class="target" id="index-16"></span><a class="pep reference external" href="https://peps.python.org/pep-0655/"><strong>PEP 655</strong></a>: Marking individual TypedDict items as required or potentially missing</dt> +<dd> +<p><em>Introducing</em> <a class="reference internal" href="#typing.Required" title="typing.Required"><code>Required</code></a> and <a class="reference internal" href="#typing.NotRequired" title="typing.NotRequired"><code>NotRequired</code></a></p> </dd> </dl> </li> <li> +<dl class="simple"> <dt> +<span class="target" id="index-17"></span><a class="pep reference external" href="https://peps.python.org/pep-0673/"><strong>PEP 673</strong></a>: Self type</dt> +<dd> +<p><em>Introducing</em> <a class="reference internal" href="#typing.Self" title="typing.Self"><code>Self</code></a></p> </dd> </dl> </li> <li> +<dl class="simple"> <dt> +<span class="target" id="index-18"></span><a class="pep reference external" href="https://peps.python.org/pep-0675/"><strong>PEP 675</strong></a>: Arbitrary Literal String Type</dt> +<dd> +<p><em>Introducing</em> <a class="reference internal" href="#typing.LiteralString" title="typing.LiteralString"><code>LiteralString</code></a></p> </dd> </dl> </li> <li> +<dl class="simple"> <dt> +<span class="target" id="index-19"></span><a class="pep reference external" href="https://peps.python.org/pep-0681/"><strong>PEP 681</strong></a>: Data Class Transforms</dt> +<dd> +<p><em>Introducing</em> the <a class="reference internal" href="#typing.dataclass_transform" title="typing.dataclass_transform"><code>@dataclass_transform</code></a> decorator</p> </dd> </dl> </li> <li> +<dl class="simple"> <dt> +<code>PEP 692: Using TypedDict for more precise **kwargs typing</code> </dt> +<dd> +<p><em>Introducing</em> a new way of typing <code>**kwargs</code> with <a class="reference internal" href="#typing.Unpack" title="typing.Unpack"><code>Unpack</code></a> and <a class="reference internal" href="#typing.TypedDict" title="typing.TypedDict"><code>TypedDict</code></a></p> </dd> </dl> </li> <li> +<dl class="simple"> <dt> +<span class="target" id="index-21"></span><a class="pep reference external" href="https://peps.python.org/pep-0695/"><strong>PEP 695</strong></a>: Type Parameter Syntax</dt> +<dd> +<p><em>Introducing</em> builtin syntax for creating generic functions, classes, and type aliases.</p> </dd> </dl> </li> <li> +<dl class="simple"> <dt> +<span class="target" id="index-22"></span><a class="pep reference external" href="https://peps.python.org/pep-0698/"><strong>PEP 698</strong></a>: Adding an override decorator to typing</dt> +<dd> +<p><em>Introducing</em> the <a class="reference internal" href="#typing.override" title="typing.override"><code>@override</code></a> decorator</p> </dd> </dl> </li> </ul> </details> <br></section> <section id="type-aliases"> <span id="id2"></span><h2>Type aliases</h2> <p>A type alias is defined using the <a class="reference internal" href="../reference/simple_stmts#type"><code>type</code></a> statement, which creates an instance of <a class="reference internal" href="#typing.TypeAliasType" title="typing.TypeAliasType"><code>TypeAliasType</code></a>. In this example, <code>Vector</code> and <code>list[float]</code> will be treated equivalently by static type checkers:</p> <pre data-language="python">type Vector = list[float] + +def scale(scalar: float, vector: Vector) -> Vector: + return [scalar * num for num in vector] + +# passes type checking; a list of floats qualifies as a Vector. +new_vector = scale(2.0, [1.0, -4.2, 5.4]) +</pre> <p>Type aliases are useful for simplifying complex type signatures. For example:</p> <pre data-language="python">from collections.abc import Sequence + +type ConnectionOptions = dict[str, str] +type Address = tuple[str, int] +type Server = tuple[Address, ConnectionOptions] + +def broadcast_message(message: str, servers: Sequence[Server]) -> None: + ... + +# The static type checker will treat the previous type signature as +# being exactly equivalent to this one. +def broadcast_message( + message: str, + servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: + ... +</pre> <p>The <a class="reference internal" href="../reference/simple_stmts#type"><code>type</code></a> statement is new in Python 3.12. For backwards compatibility, type aliases can also be created through simple assignment:</p> <pre data-language="python">Vector = list[float] +</pre> <p>Or marked with <a class="reference internal" href="#typing.TypeAlias" title="typing.TypeAlias"><code>TypeAlias</code></a> to make it explicit that this is a type alias, not a normal variable assignment:</p> <pre data-language="python">from typing import TypeAlias + +Vector: TypeAlias = list[float] +</pre> </section> <section id="newtype"> <span id="distinct"></span><h2>NewType</h2> <p>Use the <a class="reference internal" href="#typing.NewType" title="typing.NewType"><code>NewType</code></a> helper to create distinct types:</p> <pre data-language="python">from typing import NewType + +UserId = NewType('UserId', int) +some_id = UserId(524313) +</pre> <p>The static type checker will treat the new type as if it were a subclass of the original type. This is useful in helping catch logical errors:</p> <pre data-language="python">def get_user_name(user_id: UserId) -> str: + ... + +# passes type checking +user_a = get_user_name(UserId(42351)) + +# fails type checking; an int is not a UserId +user_b = get_user_name(-1) +</pre> <p>You may still perform all <code>int</code> operations on a variable of type <code>UserId</code>, but the result will always be of type <code>int</code>. This lets you pass in a <code>UserId</code> wherever an <code>int</code> might be expected, but will prevent you from accidentally creating a <code>UserId</code> in an invalid way:</p> <pre data-language="python"># 'output' is of type 'int', not 'UserId' +output = UserId(23413) + UserId(54341) +</pre> <p>Note that these checks are enforced only by the static type checker. At runtime, the statement <code>Derived = NewType('Derived', Base)</code> will make <code>Derived</code> a callable that immediately returns whatever parameter you pass it. That means the expression <code>Derived(some_value)</code> does not create a new class or introduce much overhead beyond that of a regular function call.</p> <p>More precisely, the expression <code>some_value is Derived(some_value)</code> is always true at runtime.</p> <p>It is invalid to create a subtype of <code>Derived</code>:</p> <pre data-language="python">from typing import NewType + +UserId = NewType('UserId', int) + +# Fails at runtime and does not pass type checking +class AdminUserId(UserId): pass +</pre> <p>However, it is possible to create a <a class="reference internal" href="#typing.NewType" title="typing.NewType"><code>NewType</code></a> based on a ‘derived’ <code>NewType</code>:</p> <pre data-language="python">from typing import NewType + +UserId = NewType('UserId', int) + +ProUserId = NewType('ProUserId', UserId) +</pre> <p>and typechecking for <code>ProUserId</code> will work as expected.</p> <p>See <span class="target" id="index-23"></span><a class="pep reference external" href="https://peps.python.org/pep-0484/"><strong>PEP 484</strong></a> for more details.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Recall that the use of a type alias declares two types to be <em>equivalent</em> to one another. Doing <code>type Alias = Original</code> will make the static type checker treat <code>Alias</code> as being <em>exactly equivalent</em> to <code>Original</code> in all cases. This is useful when you want to simplify complex type signatures.</p> <p>In contrast, <code>NewType</code> declares one type to be a <em>subtype</em> of another. Doing <code>Derived = NewType('Derived', Original)</code> will make the static type checker treat <code>Derived</code> as a <em>subclass</em> of <code>Original</code>, which means a value of type <code>Original</code> cannot be used in places where a value of type <code>Derived</code> is expected. This is useful when you want to prevent logic errors with minimal runtime cost.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.2.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span><code>NewType</code> is now a class rather than a function. As a result, there is some additional runtime cost when calling <code>NewType</code> over a regular function.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>The performance of calling <code>NewType</code> has been restored to its level in Python 3.9.</p> </div> </section> <section id="annotating-callable-objects"> <span id="annotating-callables"></span><h2>Annotating callable objects</h2> <p>Functions – or other <a class="reference internal" href="../glossary#term-callable"><span class="xref std std-term">callable</span></a> objects – can be annotated using <a class="reference internal" href="collections.abc#collections.abc.Callable" title="collections.abc.Callable"><code>collections.abc.Callable</code></a> or <a class="reference internal" href="#typing.Callable" title="typing.Callable"><code>typing.Callable</code></a>. <code>Callable[[int], str]</code> signifies a function that takes a single parameter of type <a class="reference internal" href="functions#int" title="int"><code>int</code></a> and returns a <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a>.</p> <p>For example:</p> <pre data-language="python">from collections.abc import Callable, Awaitable + +def feeder(get_next_item: Callable[[], str]) -> None: + ... # Body + +def async_query(on_success: Callable[[int], None], + on_error: Callable[[int, Exception], None]) -> None: + ... # Body + +async def on_update(value: str) -> None: + ... # Body + +callback: Callable[[str], Awaitable[None]] = on_update +</pre> <p>The subscription syntax must always be used with exactly two values: the argument list and the return type. The argument list must be a list of types, a <a class="reference internal" href="#typing.ParamSpec" title="typing.ParamSpec"><code>ParamSpec</code></a>, <a class="reference internal" href="#typing.Concatenate" title="typing.Concatenate"><code>Concatenate</code></a>, or an ellipsis. The return type must be a single type.</p> <p>If a literal ellipsis <code>...</code> is given as the argument list, it indicates that a callable with any arbitrary parameter list would be acceptable:</p> <pre data-language="python">def concat(x: str, y: str) -> str: + return x + y + +x: Callable[..., str] +x = str # OK +x = concat # Also OK +</pre> <p><code>Callable</code> cannot express complex signatures such as functions that take a variadic number of arguments, <a class="reference internal" href="#overload"><span class="std std-ref">overloaded functions</span></a>, or functions that have keyword-only parameters. However, these signatures can be expressed by defining a <a class="reference internal" href="#typing.Protocol" title="typing.Protocol"><code>Protocol</code></a> class with a <a class="reference internal" href="../reference/datamodel#object.__call__" title="object.__call__"><code>__call__()</code></a> method:</p> <pre data-language="python">from collections.abc import Iterable +from typing import Protocol + +class Combiner(Protocol): + def __call__(self, *vals: bytes, maxlen: int | None = None) -> list[bytes]: ... + +def batch_proc(data: Iterable[bytes], cb_results: Combiner) -> bytes: + for item in data: + ... + +def good_cb(*vals: bytes, maxlen: int | None = None) -> list[bytes]: + ... +def bad_cb(*vals: bytes, maxitems: int | None) -> list[bytes]: + ... + +batch_proc([], good_cb) # OK +batch_proc([], bad_cb) # Error! Argument 2 has incompatible type because of + # different name and kind in the callback +</pre> <p>Callables which take other callables as arguments may indicate that their parameter types are dependent on each other using <a class="reference internal" href="#typing.ParamSpec" title="typing.ParamSpec"><code>ParamSpec</code></a>. Additionally, if that callable adds or removes arguments from other callables, the <a class="reference internal" href="#typing.Concatenate" title="typing.Concatenate"><code>Concatenate</code></a> operator may be used. They take the form <code>Callable[ParamSpecVariable, ReturnType]</code> and <code>Callable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], ReturnType]</code> respectively.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span><code>Callable</code> now supports <a class="reference internal" href="#typing.ParamSpec" title="typing.ParamSpec"><code>ParamSpec</code></a> and <a class="reference internal" href="#typing.Concatenate" title="typing.Concatenate"><code>Concatenate</code></a>. See <span class="target" id="index-24"></span><a class="pep reference external" href="https://peps.python.org/pep-0612/"><strong>PEP 612</strong></a> for more details.</p> </div> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p>The documentation for <a class="reference internal" href="#typing.ParamSpec" title="typing.ParamSpec"><code>ParamSpec</code></a> and <a class="reference internal" href="#typing.Concatenate" title="typing.Concatenate"><code>Concatenate</code></a> provides examples of usage in <code>Callable</code>.</p> </div> </section> <section id="generics"> <span id="id3"></span><h2>Generics</h2> <p>Since type information about objects kept in containers cannot be statically inferred in a generic way, many container classes in the standard library support subscription to denote the expected types of container elements.</p> <pre data-language="python">from collections.abc import Mapping, Sequence + +class Employee: ... + +# Sequence[Employee] indicates that all elements in the sequence +# must be instances of "Employee". +# Mapping[str, str] indicates that all keys and all values in the mapping +# must be strings. +def notify_by_email(employees: Sequence[Employee], + overrides: Mapping[str, str]) -> None: ... +</pre> <p>Generic functions and classes can be parameterized by using <a class="reference internal" href="../reference/compound_stmts#type-params"><span class="std std-ref">type parameter syntax</span></a>:</p> <pre data-language="python">from collections.abc import Sequence + +def first[T](l: Sequence[T]) -> T: # Function is generic over the TypeVar "T" + return l[0] +</pre> <p>Or by using the <a class="reference internal" href="#typing.TypeVar" title="typing.TypeVar"><code>TypeVar</code></a> factory directly:</p> <pre data-language="python">from collections.abc import Sequence +from typing import TypeVar + +U = TypeVar('U') # Declare type variable "U" + +def second(l: Sequence[U]) -> U: # Function is generic over the TypeVar "U" + return l[1] +</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Syntactic support for generics is new in Python 3.12.</p> </div> </section> <section id="annotating-tuples"> <span id="id4"></span><h2>Annotating tuples</h2> <p>For most containers in Python, the typing system assumes that all elements in the container will be of the same type. For example:</p> <pre data-language="python">from collections.abc import Mapping + +# Type checker will infer that all elements in ``x`` are meant to be ints +x: list[int] = [] + +# Type checker error: ``list`` only accepts a single type argument: +y: list[int, str] = [1, 'foo'] + +# Type checker will infer that all keys in ``z`` are meant to be strings, +# and that all values in ``z`` are meant to be either strings or ints +z: Mapping[str, str | int] = {} +</pre> <p><a class="reference internal" href="stdtypes#list" title="list"><code>list</code></a> only accepts one type argument, so a type checker would emit an error on the <code>y</code> assignment above. Similarly, <a class="reference internal" href="collections.abc#collections.abc.Mapping" title="collections.abc.Mapping"><code>Mapping</code></a> only accepts two type arguments: the first indicates the type of the keys, and the second indicates the type of the values.</p> <p>Unlike most other Python containers, however, it is common in idiomatic Python code for tuples to have elements which are not all of the same type. For this reason, tuples are special-cased in Python’s typing system. <a class="reference internal" href="stdtypes#tuple" title="tuple"><code>tuple</code></a> accepts <em>any number</em> of type arguments:</p> <pre data-language="python"># OK: ``x`` is assigned to a tuple of length 1 where the sole element is an int +x: tuple[int] = (5,) + +# OK: ``y`` is assigned to a tuple of length 2; +# element 1 is an int, element 2 is a str +y: tuple[int, str] = (5, "foo") + +# Error: the type annotation indicates a tuple of length 1, +# but ``z`` has been assigned to a tuple of length 3 +z: tuple[int] = (1, 2, 3) +</pre> <p>To denote a tuple which could be of <em>any</em> length, and in which all elements are of the same type <code>T</code>, use <code>tuple[T, ...]</code>. To denote an empty tuple, use <code>tuple[()]</code>. Using plain <code>tuple</code> as an annotation is equivalent to using <code>tuple[Any, ...]</code>:</p> <pre data-language="python">x: tuple[int, ...] = (1, 2) +# These reassignments are OK: ``tuple[int, ...]`` indicates x can be of any length +x = (1, 2, 3) +x = () +# This reassignment is an error: all elements in ``x`` must be ints +x = ("foo", "bar") + +# ``y`` can only ever be assigned to an empty tuple +y: tuple[()] = () + +z: tuple = ("foo", "bar") +# These reassignments are OK: plain ``tuple`` is equivalent to ``tuple[Any, ...]`` +z = (1, 2, 3) +z = () +</pre> </section> <section id="the-type-of-class-objects"> <span id="type-of-class-objects"></span><h2>The type of class objects</h2> <p>A variable annotated with <code>C</code> may accept a value of type <code>C</code>. In contrast, a variable annotated with <code>type[C]</code> (or <a class="reference internal" href="#typing.Type" title="typing.Type"><code>typing.Type[C]</code></a>) may accept values that are classes themselves – specifically, it will accept the <em>class object</em> of <code>C</code>. For example:</p> <pre data-language="python">a = 3 # Has type ``int`` +b = int # Has type ``type[int]`` +c = type(a) # Also has type ``type[int]`` +</pre> <p>Note that <code>type[C]</code> is covariant:</p> <pre data-language="python">class User: ... +class ProUser(User): ... +class TeamUser(User): ... + +def make_new_user(user_class: type[User]) -> User: + # ... + return user_class() + +make_new_user(User) # OK +make_new_user(ProUser) # Also OK: ``type[ProUser]`` is a subtype of ``type[User]`` +make_new_user(TeamUser) # Still fine +make_new_user(User()) # Error: expected ``type[User]`` but got ``User`` +make_new_user(int) # Error: ``type[int]`` is not a subtype of ``type[User]`` +</pre> <p>The only legal parameters for <a class="reference internal" href="functions#type" title="type"><code>type</code></a> are classes, <a class="reference internal" href="#typing.Any" title="typing.Any"><code>Any</code></a>, <a class="reference internal" href="#generics"><span class="std std-ref">type variables</span></a>, and unions of any of these types. For example:</p> <pre data-language="python">def new_non_team_user(user_class: type[BasicUser | ProUser]): ... + +new_non_team_user(BasicUser) # OK +new_non_team_user(ProUser) # OK +new_non_team_user(TeamUser) # Error: ``type[TeamUser]`` is not a subtype + # of ``type[BasicUser | ProUser]`` +new_non_team_user(User) # Also an error +</pre> <p><code>type[Any]</code> is equivalent to <a class="reference internal" href="functions#type" title="type"><code>type</code></a>, which is the root of Python’s <a class="reference internal" href="../reference/datamodel#metaclasses"><span class="std std-ref">metaclass hierarchy</span></a>.</p> </section> <section id="user-defined-generic-types"> <span id="user-defined-generics"></span><h2>User-defined generic types</h2> <p>A user-defined class can be defined as a generic class.</p> <pre data-language="python">from logging import Logger + +class LoggedVar[T]: + def __init__(self, value: T, name: str, logger: Logger) -> None: + self.name = name + self.logger = logger + self.value = value + + def set(self, new: T) -> None: + self.log('Set ' + repr(self.value)) + self.value = new + + def get(self) -> T: + self.log('Get ' + repr(self.value)) + return self.value + + def log(self, message: str) -> None: + self.logger.info('%s: %s', self.name, message) +</pre> <p>This syntax indicates that the class <code>LoggedVar</code> is parameterised around a single <a class="reference internal" href="#typevar"><span class="std std-ref">type variable</span></a> <code>T</code> . This also makes <code>T</code> valid as a type within the class body.</p> <p>Generic classes implicitly inherit from <a class="reference internal" href="#typing.Generic" title="typing.Generic"><code>Generic</code></a>. For compatibility with Python 3.11 and lower, it is also possible to inherit explicitly from <a class="reference internal" href="#typing.Generic" title="typing.Generic"><code>Generic</code></a> to indicate a generic class:</p> <pre data-language="python">from typing import TypeVar, Generic + +T = TypeVar('T') + +class LoggedVar(Generic[T]): + ... +</pre> <p>Generic classes have <a class="reference internal" href="../reference/datamodel#object.__class_getitem__" title="object.__class_getitem__"><code>__class_getitem__()</code></a> methods, meaning they can be parameterised at runtime (e.g. <code>LoggedVar[int]</code> below):</p> <pre data-language="python">from collections.abc import Iterable + +def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None: + for var in vars: + var.set(0) +</pre> <p>A generic type can have any number of type variables. All varieties of <a class="reference internal" href="#typing.TypeVar" title="typing.TypeVar"><code>TypeVar</code></a> are permissible as parameters for a generic type:</p> <pre data-language="python">from typing import TypeVar, Generic, Sequence + +class WeirdTrio[T, B: Sequence[bytes], S: (int, str)]: + ... + +OldT = TypeVar('OldT', contravariant=True) +OldB = TypeVar('OldB', bound=Sequence[bytes], covariant=True) +OldS = TypeVar('OldS', int, str) + +class OldWeirdTrio(Generic[OldT, OldB, OldS]): + ... +</pre> <p>Each type variable argument to <a class="reference internal" href="#typing.Generic" title="typing.Generic"><code>Generic</code></a> must be distinct. This is thus invalid:</p> <pre data-language="python">from typing import TypeVar, Generic +... + +class Pair[M, M]: # SyntaxError + ... + +T = TypeVar('T') + +class Pair(Generic[T, T]): # INVALID + ... +</pre> <p>Generic classes can also inherit from other classes:</p> <pre data-language="python">from collections.abc import Sized + +class LinkedList[T](Sized): + ... +</pre> <p>When inheriting from generic classes, some type parameters could be fixed:</p> <pre data-language="python">from collections.abc import Mapping + +class MyDict[T](Mapping[str, T]): + ... +</pre> <p>In this case <code>MyDict</code> has a single parameter, <code>T</code>.</p> <p>Using a generic class without specifying type parameters assumes <a class="reference internal" href="#typing.Any" title="typing.Any"><code>Any</code></a> for each position. In the following example, <code>MyIterable</code> is not generic but implicitly inherits from <code>Iterable[Any]</code>:</p> <pre data-language="python">from collections.abc import Iterable + +class MyIterable(Iterable): # Same as Iterable[Any] + ... +</pre> <p>User-defined generic type aliases are also supported. Examples:</p> <pre data-language="python">from collections.abc import Iterable + +type Response[S] = Iterable[S] | int + +# Return type here is same as Iterable[str] | int +def response(query: str) -> Response[str]: + ... + +type Vec[T] = Iterable[tuple[T, T]] + +def inproduct[T: (int, float, complex)](v: Vec[T]) -> T: # Same as Iterable[tuple[T, T]] + return sum(x*y for x, y in v) +</pre> <p>For backward compatibility, generic type aliases can also be created through a simple assignment:</p> <pre data-language="python">from collections.abc import Iterable +from typing import TypeVar + +S = TypeVar("S") +Response = Iterable[S] | int +</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span><a class="reference internal" href="#typing.Generic" title="typing.Generic"><code>Generic</code></a> no longer has a custom metaclass.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Syntactic support for generics and type aliases is new in version 3.12. Previously, generic classes had to explicitly inherit from <a class="reference internal" href="#typing.Generic" title="typing.Generic"><code>Generic</code></a> or contain a type variable in one of their bases.</p> </div> <p>User-defined generics for parameter expressions are also supported via parameter specification variables in the form <code>[**P]</code>. The behavior is consistent with type variables’ described above as parameter specification variables are treated by the typing module as a specialized type variable. The one exception to this is that a list of types can be used to substitute a <a class="reference internal" href="#typing.ParamSpec" title="typing.ParamSpec"><code>ParamSpec</code></a>:</p> <pre data-language="python">>>> class Z[T, **P]: ... # T is a TypeVar; P is a ParamSpec +... +>>> Z[int, [dict, float]] +__main__.Z[int, [dict, float]] +</pre> <p>Classes generic over a <a class="reference internal" href="#typing.ParamSpec" title="typing.ParamSpec"><code>ParamSpec</code></a> can also be created using explicit inheritance from <a class="reference internal" href="#typing.Generic" title="typing.Generic"><code>Generic</code></a>. In this case, <code>**</code> is not used:</p> <pre data-language="python">from typing import ParamSpec, Generic + +P = ParamSpec('P') + +class Z(Generic[P]): + ... +</pre> <p>Another difference between <a class="reference internal" href="#typing.TypeVar" title="typing.TypeVar"><code>TypeVar</code></a> and <a class="reference internal" href="#typing.ParamSpec" title="typing.ParamSpec"><code>ParamSpec</code></a> is that a generic with only one parameter specification variable will accept parameter lists in the forms <code>X[[Type1, Type2, ...]]</code> and also <code>X[Type1, Type2, ...]</code> for aesthetic reasons. Internally, the latter is converted to the former, so the following are equivalent:</p> <pre data-language="python">>>> class X[**P]: ... +... +>>> X[int, str] +__main__.X[[int, str]] +>>> X[[int, str]] +__main__.X[[int, str]] +</pre> <p>Note that generics with <a class="reference internal" href="#typing.ParamSpec" title="typing.ParamSpec"><code>ParamSpec</code></a> may not have correct <code>__parameters__</code> after substitution in some cases because they are intended primarily for static type checking.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span><a class="reference internal" href="#typing.Generic" title="typing.Generic"><code>Generic</code></a> can now be parameterized over parameter expressions. See <a class="reference internal" href="#typing.ParamSpec" title="typing.ParamSpec"><code>ParamSpec</code></a> and <span class="target" id="index-25"></span><a class="pep reference external" href="https://peps.python.org/pep-0612/"><strong>PEP 612</strong></a> for more details.</p> </div> <p>A user-defined generic class can have ABCs as base classes without a metaclass conflict. Generic metaclasses are not supported. The outcome of parameterizing generics is cached, and most types in the typing module are <a class="reference internal" href="../glossary#term-hashable"><span class="xref std std-term">hashable</span></a> and comparable for equality.</p> </section> <section id="the-any-type"> <h2>The Any type</h2> <p>A special kind of type is <a class="reference internal" href="#typing.Any" title="typing.Any"><code>Any</code></a>. A static type checker will treat every type as being compatible with <a class="reference internal" href="#typing.Any" title="typing.Any"><code>Any</code></a> and <a class="reference internal" href="#typing.Any" title="typing.Any"><code>Any</code></a> as being compatible with every type.</p> <p>This means that it is possible to perform any operation or method call on a value of type <a class="reference internal" href="#typing.Any" title="typing.Any"><code>Any</code></a> and assign it to any variable:</p> <pre data-language="python">from typing import Any + +a: Any = None +a = [] # OK +a = 2 # OK + +s: str = '' +s = a # OK + +def foo(item: Any) -> int: + # Passes type checking; 'item' could be any type, + # and that type might have a 'bar' method + item.bar() + ... +</pre> <p>Notice that no type checking is performed when assigning a value of type <a class="reference internal" href="#typing.Any" title="typing.Any"><code>Any</code></a> to a more precise type. For example, the static type checker did not report an error when assigning <code>a</code> to <code>s</code> even though <code>s</code> was declared to be of type <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a> and receives an <a class="reference internal" href="functions#int" title="int"><code>int</code></a> value at runtime!</p> <p>Furthermore, all functions without a return type or parameter types will implicitly default to using <a class="reference internal" href="#typing.Any" title="typing.Any"><code>Any</code></a>:</p> <pre data-language="python">def legacy_parser(text): + ... + return data + +# A static type checker will treat the above +# as having the same signature as: +def legacy_parser(text: Any) -> Any: + ... + return data +</pre> <p>This behavior allows <a class="reference internal" href="#typing.Any" title="typing.Any"><code>Any</code></a> to be used as an <em>escape hatch</em> when you need to mix dynamically and statically typed code.</p> <p>Contrast the behavior of <a class="reference internal" href="#typing.Any" title="typing.Any"><code>Any</code></a> with the behavior of <a class="reference internal" href="functions#object" title="object"><code>object</code></a>. Similar to <a class="reference internal" href="#typing.Any" title="typing.Any"><code>Any</code></a>, every type is a subtype of <a class="reference internal" href="functions#object" title="object"><code>object</code></a>. However, unlike <a class="reference internal" href="#typing.Any" title="typing.Any"><code>Any</code></a>, the reverse is not true: <a class="reference internal" href="functions#object" title="object"><code>object</code></a> is <em>not</em> a subtype of every other type.</p> <p>That means when the type of a value is <a class="reference internal" href="functions#object" title="object"><code>object</code></a>, a type checker will reject almost all operations on it, and assigning it to a variable (or using it as a return value) of a more specialized type is a type error. For example:</p> <pre data-language="python">def hash_a(item: object) -> int: + # Fails type checking; an object does not have a 'magic' method. + item.magic() + ... + +def hash_b(item: Any) -> int: + # Passes type checking + item.magic() + ... + +# Passes type checking, since ints and strs are subclasses of object +hash_a(42) +hash_a("foo") + +# Passes type checking, since Any is compatible with all types +hash_b(42) +hash_b("foo") +</pre> <p>Use <a class="reference internal" href="functions#object" title="object"><code>object</code></a> to indicate that a value could be any type in a typesafe manner. Use <a class="reference internal" href="#typing.Any" title="typing.Any"><code>Any</code></a> to indicate that a value is dynamically typed.</p> </section> <section id="nominal-vs-structural-subtyping"> <h2>Nominal vs structural subtyping</h2> <p>Initially <span class="target" id="index-26"></span><a class="pep reference external" href="https://peps.python.org/pep-0484/"><strong>PEP 484</strong></a> defined the Python static type system as using <em>nominal subtyping</em>. This means that a class <code>A</code> is allowed where a class <code>B</code> is expected if and only if <code>A</code> is a subclass of <code>B</code>.</p> <p>This requirement previously also applied to abstract base classes, such as <a class="reference internal" href="collections.abc#collections.abc.Iterable" title="collections.abc.Iterable"><code>Iterable</code></a>. The problem with this approach is that a class had to be explicitly marked to support them, which is unpythonic and unlike what one would normally do in idiomatic dynamically typed Python code. For example, this conforms to <span class="target" id="index-27"></span><a class="pep reference external" href="https://peps.python.org/pep-0484/"><strong>PEP 484</strong></a>:</p> <pre data-language="python">from collections.abc import Sized, Iterable, Iterator + +class Bucket(Sized, Iterable[int]): + ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[int]: ... +</pre> <p><span class="target" id="index-28"></span><a class="pep reference external" href="https://peps.python.org/pep-0544/"><strong>PEP 544</strong></a> allows to solve this problem by allowing users to write the above code without explicit base classes in the class definition, allowing <code>Bucket</code> to be implicitly considered a subtype of both <code>Sized</code> and <code>Iterable[int]</code> by static type checkers. This is known as <em>structural subtyping</em> (or static duck-typing):</p> <pre data-language="python">from collections.abc import Iterator, Iterable + +class Bucket: # Note: no base classes + ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[int]: ... + +def collect(items: Iterable[int]) -> int: ... +result = collect(Bucket()) # Passes type check +</pre> <p>Moreover, by subclassing a special class <a class="reference internal" href="#typing.Protocol" title="typing.Protocol"><code>Protocol</code></a>, a user can define new custom protocols to fully enjoy structural subtyping (see examples below).</p> </section> <section id="module-contents"> <h2>Module contents</h2> <p>The <code>typing</code> module defines the following classes, functions and decorators.</p> <section id="special-typing-primitives"> <h3>Special typing primitives</h3> <section id="special-types"> <h4>Special types</h4> <p>These can be used as types in annotations. They do not support subscription using <code>[]</code>.</p> <dl class="py data"> <dt class="sig sig-object py" id="typing.Any"> +<code>typing.Any</code> </dt> <dd> +<p>Special type indicating an unconstrained type.</p> <ul class="simple"> <li>Every type is compatible with <a class="reference internal" href="#typing.Any" title="typing.Any"><code>Any</code></a>.</li> <li> +<a class="reference internal" href="#typing.Any" title="typing.Any"><code>Any</code></a> is compatible with every type.</li> </ul> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span><a class="reference internal" href="#typing.Any" title="typing.Any"><code>Any</code></a> can now be used as a base class. This can be useful for avoiding type checker errors with classes that can duck type anywhere or are highly dynamic.</p> </div> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="typing.AnyStr"> +<code>typing.AnyStr</code> </dt> <dd> +<p>A <a class="reference internal" href="#typing-constrained-typevar"><span class="std std-ref">constrained type variable</span></a>.</p> <p>Definition:</p> <pre data-language="python">AnyStr = TypeVar('AnyStr', str, bytes) +</pre> <p><code>AnyStr</code> is meant to be used for functions that may accept <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a> or <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a> arguments but cannot allow the two to mix.</p> <p>For example:</p> <pre data-language="python">def concat(a: AnyStr, b: AnyStr) -> AnyStr: + return a + b + +concat("foo", "bar") # OK, output has type 'str' +concat(b"foo", b"bar") # OK, output has type 'bytes' +concat("foo", b"bar") # Error, cannot mix str and bytes +</pre> <p>Note that, despite its name, <code>AnyStr</code> has nothing to do with the <a class="reference internal" href="#typing.Any" title="typing.Any"><code>Any</code></a> type, nor does it mean “any string”. In particular, <code>AnyStr</code> and <code>str | bytes</code> are different from each other and have different use cases:</p> <pre data-language="python"># Invalid use of AnyStr: +# The type variable is used only once in the function signature, +# so cannot be "solved" by the type checker +def greet_bad(cond: bool) -> AnyStr: + return "hi there!" if cond else b"greetings!" + +# The better way of annotating this function: +def greet_proper(cond: bool) -> str | bytes: + return "hi there!" if cond else b"greetings!" +</pre> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="typing.LiteralString"> +<code>typing.LiteralString</code> </dt> <dd> +<p>Special type that includes only literal strings.</p> <p>Any string literal is compatible with <code>LiteralString</code>, as is another <code>LiteralString</code>. However, an object typed as just <code>str</code> is not. A string created by composing <code>LiteralString</code>-typed objects is also acceptable as a <code>LiteralString</code>.</p> <p>Example:</p> <pre data-language="python">def run_query(sql: LiteralString) -> None: + ... + +def caller(arbitrary_string: str, literal_string: LiteralString) -> None: + run_query("SELECT * FROM students") # OK + run_query(literal_string) # OK + run_query("SELECT * FROM " + literal_string) # OK + run_query(arbitrary_string) # type checker error + run_query( # type checker error + f"SELECT * FROM students WHERE name = {arbitrary_string}" + ) +</pre> <p><code>LiteralString</code> is useful for sensitive APIs where arbitrary user-generated strings could generate problems. For example, the two cases above that generate type checker errors could be vulnerable to an SQL injection attack.</p> <p>See <span class="target" id="index-29"></span><a class="pep reference external" href="https://peps.python.org/pep-0675/"><strong>PEP 675</strong></a> for more details.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="typing.Never"> +<code>typing.Never</code> </dt> <dd> +<p>The <a class="reference external" href="https://en.wikipedia.org/wiki/Bottom_type">bottom type</a>, a type that has no members.</p> <p>This can be used to define a function that should never be called, or a function that never returns:</p> <pre data-language="python">from typing import Never + +def never_call_me(arg: Never) -> None: + pass + +def int_or_str(arg: int | str) -> None: + never_call_me(arg) # type checker error + match arg: + case int(): + print("It's an int") + case str(): + print("It's a str") + case _: + never_call_me(arg) # OK, arg is of type Never +</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11: </span>On older Python versions, <a class="reference internal" href="#typing.NoReturn" title="typing.NoReturn"><code>NoReturn</code></a> may be used to express the same concept. <code>Never</code> was added to make the intended meaning more explicit.</p> </div> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="typing.NoReturn"> +<code>typing.NoReturn</code> </dt> <dd> +<p>Special type indicating that a function never returns.</p> <p>For example:</p> <pre data-language="python">from typing import NoReturn + +def stop() -> NoReturn: + raise RuntimeError('no way') +</pre> <p><code>NoReturn</code> can also be used as a <a class="reference external" href="https://en.wikipedia.org/wiki/Bottom_type">bottom type</a>, a type that has no values. Starting in Python 3.11, the <a class="reference internal" href="#typing.Never" title="typing.Never"><code>Never</code></a> type should be used for this concept instead. Type checkers should treat the two equivalently.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.4.</span></p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.2.</span></p> </div> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="typing.Self"> +<code>typing.Self</code> </dt> <dd> +<p>Special type to represent the current enclosed class.</p> <p>For example:</p> <pre data-language="python">from typing import Self, reveal_type + +class Foo: + def return_self(self) -> Self: + ... + return self + +class SubclassOfFoo(Foo): pass + +reveal_type(Foo().return_self()) # Revealed type is "Foo" +reveal_type(SubclassOfFoo().return_self()) # Revealed type is "SubclassOfFoo" +</pre> <p>This annotation is semantically equivalent to the following, albeit in a more succinct fashion:</p> <pre data-language="python">from typing import TypeVar + +Self = TypeVar("Self", bound="Foo") + +class Foo: + def return_self(self: Self) -> Self: + ... + return self +</pre> <p>In general, if something returns <code>self</code>, as in the above examples, you should use <code>Self</code> as the return annotation. If <code>Foo.return_self</code> was annotated as returning <code>"Foo"</code>, then the type checker would infer the object returned from <code>SubclassOfFoo.return_self</code> as being of type <code>Foo</code> rather than <code>SubclassOfFoo</code>.</p> <p>Other common use cases include:</p> <ul class="simple"> <li> +<a class="reference internal" href="functions#classmethod" title="classmethod"><code>classmethod</code></a>s that are used as alternative constructors and return instances of the <code>cls</code> parameter.</li> <li>Annotating an <a class="reference internal" href="../reference/datamodel#object.__enter__" title="object.__enter__"><code>__enter__()</code></a> method which returns self.</li> </ul> <p>You should not use <code>Self</code> as the return annotation if the method is not guaranteed to return an instance of a subclass when the class is subclassed:</p> <pre data-language="python">class Eggs: + # Self would be an incorrect return annotation here, + # as the object returned is always an instance of Eggs, + # even in subclasses + def returns_eggs(self) -> "Eggs": + return Eggs() +</pre> <p>See <span class="target" id="index-30"></span><a class="pep reference external" href="https://peps.python.org/pep-0673/"><strong>PEP 673</strong></a> for more details.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="typing.TypeAlias"> +<code>typing.TypeAlias</code> </dt> <dd> +<p>Special annotation for explicitly declaring a <a class="reference internal" href="#type-aliases"><span class="std std-ref">type alias</span></a>.</p> <p>For example:</p> <pre data-language="python">from typing import TypeAlias + +Factors: TypeAlias = list[int] +</pre> <p><code>TypeAlias</code> is particularly useful on older Python versions for annotating aliases that make use of forward references, as it can be hard for type checkers to distinguish these from normal variable assignments:</p> <pre data-language="python">from typing import Generic, TypeAlias, TypeVar + +T = TypeVar("T") + +# "Box" does not exist yet, +# so we have to use quotes for the forward reference on Python <3.12. +# Using ``TypeAlias`` tells the type checker that this is a type alias declaration, +# not a variable assignment to a string. +BoxOfStrings: TypeAlias = "Box[str]" + +class Box(Generic[T]): + @classmethod + def make_box_of_strings(cls) -> BoxOfStrings: ... +</pre> <p>See <span class="target" id="index-31"></span><a class="pep reference external" href="https://peps.python.org/pep-0613/"><strong>PEP 613</strong></a> for more details.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.12: </span><a class="reference internal" href="#typing.TypeAlias" title="typing.TypeAlias"><code>TypeAlias</code></a> is deprecated in favor of the <a class="reference internal" href="../reference/simple_stmts#type"><code>type</code></a> statement, which creates instances of <a class="reference internal" href="#typing.TypeAliasType" title="typing.TypeAliasType"><code>TypeAliasType</code></a> and which natively supports forward references. Note that while <a class="reference internal" href="#typing.TypeAlias" title="typing.TypeAlias"><code>TypeAlias</code></a> and <a class="reference internal" href="#typing.TypeAliasType" title="typing.TypeAliasType"><code>TypeAliasType</code></a> serve similar purposes and have similar names, they are distinct and the latter is not the type of the former. Removal of <a class="reference internal" href="#typing.TypeAlias" title="typing.TypeAlias"><code>TypeAlias</code></a> is not currently planned, but users are encouraged to migrate to <a class="reference internal" href="../reference/simple_stmts#type"><code>type</code></a> statements.</p> </div> </dd> +</dl> </section> <section id="special-forms"> <h4>Special forms</h4> <p>These can be used as types in annotations. They all support subscription using <code>[]</code>, but each has a unique syntax.</p> <dl class="py data"> <dt class="sig sig-object py" id="typing.Union"> +<code>typing.Union</code> </dt> <dd> +<p>Union type; <code>Union[X, Y]</code> is equivalent to <code>X | Y</code> and means either X or Y.</p> <p>To define a union, use e.g. <code>Union[int, str]</code> or the shorthand <code>int | str</code>. Using that shorthand is recommended. Details:</p> <ul> <li>The arguments must be types and there must be at least one.</li> <li> +<p>Unions of unions are flattened, e.g.:</p> <pre data-language="python">Union[Union[int, str], float] == Union[int, str, float] +</pre> </li> <li> +<p>Unions of a single argument vanish, e.g.:</p> <pre data-language="python">Union[int] == int # The constructor actually returns int +</pre> </li> <li> +<p>Redundant arguments are skipped, e.g.:</p> <pre data-language="python">Union[int, str, int] == Union[int, str] == int | str +</pre> </li> <li> +<p>When comparing unions, the argument order is ignored, e.g.:</p> <pre data-language="python">Union[int, str] == Union[str, int] +</pre> </li> <li>You cannot subclass or instantiate a <code>Union</code>.</li> <li>You cannot write <code>Union[X][Y]</code>.</li> </ul> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Don’t remove explicit subclasses from unions at runtime.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>Unions can now be written as <code>X | Y</code>. See <a class="reference internal" href="stdtypes#types-union"><span class="std std-ref">union type expressions</span></a>.</p> </div> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="typing.Optional"> +<code>typing.Optional</code> </dt> <dd> +<p><code>Optional[X]</code> is equivalent to <code>X | None</code> (or <code>Union[X, None]</code>).</p> <p>Note that this is not the same concept as an optional argument, which is one that has a default. An optional argument with a default does not require the <code>Optional</code> qualifier on its type annotation just because it is optional. For example:</p> <pre data-language="python">def foo(arg: int = 0) -> None: + ... +</pre> <p>On the other hand, if an explicit value of <code>None</code> is allowed, the use of <code>Optional</code> is appropriate, whether the argument is optional or not. For example:</p> <pre data-language="python">def foo(arg: Optional[int] = None) -> None: + ... +</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>Optional can now be written as <code>X | None</code>. See <a class="reference internal" href="stdtypes#types-union"><span class="std std-ref">union type expressions</span></a>.</p> </div> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="typing.Concatenate"> +<code>typing.Concatenate</code> </dt> <dd> +<p>Special form for annotating higher-order functions.</p> <p><code>Concatenate</code> can be used in conjunction with <a class="reference internal" href="#annotating-callables"><span class="std std-ref">Callable</span></a> and <a class="reference internal" href="#typing.ParamSpec" title="typing.ParamSpec"><code>ParamSpec</code></a> to annotate a higher-order callable which adds, removes, or transforms parameters of another callable. Usage is in the form <code>Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable]</code>. <code>Concatenate</code> is currently only valid when used as the first argument to a <a class="reference internal" href="#annotating-callables"><span class="std std-ref">Callable</span></a>. The last parameter to <code>Concatenate</code> must be a <a class="reference internal" href="#typing.ParamSpec" title="typing.ParamSpec"><code>ParamSpec</code></a> or ellipsis (<code>...</code>).</p> <p>For example, to annotate a decorator <code>with_lock</code> which provides a <a class="reference internal" href="threading#threading.Lock" title="threading.Lock"><code>threading.Lock</code></a> to the decorated function, <code>Concatenate</code> can be used to indicate that <code>with_lock</code> expects a callable which takes in a <code>Lock</code> as the first argument, and returns a callable with a different type signature. In this case, the <a class="reference internal" href="#typing.ParamSpec" title="typing.ParamSpec"><code>ParamSpec</code></a> indicates that the returned callable’s parameter types are dependent on the parameter types of the callable being passed in:</p> <pre data-language="python">from collections.abc import Callable +from threading import Lock +from typing import Concatenate + +# Use this lock to ensure that only one thread is executing a function +# at any time. +my_lock = Lock() + +def with_lock[**P, R](f: Callable[Concatenate[Lock, P], R]) -> Callable[P, R]: + '''A type-safe decorator which provides a lock.''' + def inner(*args: P.args, **kwargs: P.kwargs) -> R: + # Provide the lock as the first argument. + return f(my_lock, *args, **kwargs) + return inner + +@with_lock +def sum_threadsafe(lock: Lock, numbers: list[float]) -> float: + '''Add a list of numbers together in a thread-safe manner.''' + with lock: + return sum(numbers) + +# We don't need to pass in the lock ourselves thanks to the decorator. +sum_threadsafe([1.1, 2.2, 3.3]) +</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> <div class="admonition seealso"> <p class="admonition-title">See also</p> <ul class="simple"> <li> +<span class="target" id="index-32"></span><a class="pep reference external" href="https://peps.python.org/pep-0612/"><strong>PEP 612</strong></a> – Parameter Specification Variables (the PEP which introduced <code>ParamSpec</code> and <code>Concatenate</code>)</li> <li><a class="reference internal" href="#typing.ParamSpec" title="typing.ParamSpec"><code>ParamSpec</code></a></li> <li><a class="reference internal" href="#annotating-callables"><span class="std std-ref">Annotating callable objects</span></a></li> </ul> </div> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="typing.Literal"> +<code>typing.Literal</code> </dt> <dd> +<p>Special typing form to define “literal types”.</p> <p><code>Literal</code> can be used to indicate to type checkers that the annotated object has a value equivalent to one of the provided literals.</p> <p>For example:</p> <pre data-language="python">def validate_simple(data: Any) -> Literal[True]: # always returns True + ... + +type Mode = Literal['r', 'rb', 'w', 'wb'] +def open_helper(file: str, mode: Mode) -> str: + ... + +open_helper('/some/path', 'r') # Passes type check +open_helper('/other/path', 'typo') # Error in type checker +</pre> <p><code>Literal[...]</code> cannot be subclassed. At runtime, an arbitrary value is allowed as type argument to <code>Literal[...]</code>, but type checkers may impose restrictions. See <span class="target" id="index-33"></span><a class="pep reference external" href="https://peps.python.org/pep-0586/"><strong>PEP 586</strong></a> for more details about literal types.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9.1: </span><code>Literal</code> now de-duplicates parameters. Equality comparisons of <code>Literal</code> objects are no longer order dependent. <code>Literal</code> objects will now raise a <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> exception during equality comparisons if one of their parameters are not <a class="reference internal" href="../glossary#term-hashable"><span class="xref std std-term">hashable</span></a>.</p> </div> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="typing.ClassVar"> +<code>typing.ClassVar</code> </dt> <dd> +<p>Special type construct to mark class variables.</p> <p>As introduced in <span class="target" id="index-34"></span><a class="pep reference external" href="https://peps.python.org/pep-0526/"><strong>PEP 526</strong></a>, a variable annotation wrapped in ClassVar indicates that a given attribute is intended to be used as a class variable and should not be set on instances of that class. Usage:</p> <pre data-language="python">class Starship: + stats: ClassVar[dict[str, int]] = {} # class variable + damage: int = 10 # instance variable +</pre> <p><a class="reference internal" href="#typing.ClassVar" title="typing.ClassVar"><code>ClassVar</code></a> accepts only types and cannot be further subscribed.</p> <p><a class="reference internal" href="#typing.ClassVar" title="typing.ClassVar"><code>ClassVar</code></a> is not a class itself, and should not be used with <a class="reference internal" href="functions#isinstance" title="isinstance"><code>isinstance()</code></a> or <a class="reference internal" href="functions#issubclass" title="issubclass"><code>issubclass()</code></a>. <a class="reference internal" href="#typing.ClassVar" title="typing.ClassVar"><code>ClassVar</code></a> does not change Python runtime behavior, but it can be used by third-party type checkers. For example, a type checker might flag the following code as an error:</p> <pre data-language="python">enterprise_d = Starship(3000) +enterprise_d.stats = {} # Error, setting class variable on instance +Starship.stats = {} # This is OK +</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.3.</span></p> </div> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="typing.Final"> +<code>typing.Final</code> </dt> <dd> +<p>Special typing construct to indicate final names to type checkers.</p> <p>Final names cannot be reassigned in any scope. Final names declared in class scopes cannot be overridden in subclasses.</p> <p>For example:</p> <pre data-language="python">MAX_SIZE: Final = 9000 +MAX_SIZE += 1 # Error reported by type checker + +class Connection: + TIMEOUT: Final[int] = 10 + +class FastConnector(Connection): + TIMEOUT = 1 # Error reported by type checker +</pre> <p>There is no runtime checking of these properties. See <span class="target" id="index-35"></span><a class="pep reference external" href="https://peps.python.org/pep-0591/"><strong>PEP 591</strong></a> for more details.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="typing.Required"> +<code>typing.Required</code> </dt> <dd> +<p>Special typing construct to mark a <a class="reference internal" href="#typing.TypedDict" title="typing.TypedDict"><code>TypedDict</code></a> key as required.</p> <p>This is mainly useful for <code>total=False</code> TypedDicts. See <a class="reference internal" href="#typing.TypedDict" title="typing.TypedDict"><code>TypedDict</code></a> and <span class="target" id="index-36"></span><a class="pep reference external" href="https://peps.python.org/pep-0655/"><strong>PEP 655</strong></a> for more details.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="typing.NotRequired"> +<code>typing.NotRequired</code> </dt> <dd> +<p>Special typing construct to mark a <a class="reference internal" href="#typing.TypedDict" title="typing.TypedDict"><code>TypedDict</code></a> key as potentially missing.</p> <p>See <a class="reference internal" href="#typing.TypedDict" title="typing.TypedDict"><code>TypedDict</code></a> and <span class="target" id="index-37"></span><a class="pep reference external" href="https://peps.python.org/pep-0655/"><strong>PEP 655</strong></a> for more details.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="typing.Annotated"> +<code>typing.Annotated</code> </dt> <dd> +<p>Special typing form to add context-specific metadata to an annotation.</p> <p>Add metadata <code>x</code> to a given type <code>T</code> by using the annotation <code>Annotated[T, x]</code>. Metadata added using <code>Annotated</code> can be used by static analysis tools or at runtime. At runtime, the metadata is stored in a <code>__metadata__</code> attribute.</p> <p>If a library or tool encounters an annotation <code>Annotated[T, x]</code> and has no special logic for the metadata, it should ignore the metadata and simply treat the annotation as <code>T</code>. As such, <code>Annotated</code> can be useful for code that wants to use annotations for purposes outside Python’s static typing system.</p> <p>Using <code>Annotated[T, x]</code> as an annotation still allows for static typechecking of <code>T</code>, as type checkers will simply ignore the metadata <code>x</code>. In this way, <code>Annotated</code> differs from the <a class="reference internal" href="#typing.no_type_check" title="typing.no_type_check"><code>@no_type_check</code></a> decorator, which can also be used for adding annotations outside the scope of the typing system, but completely disables typechecking for a function or class.</p> <p>The responsibility of how to interpret the metadata lies with the tool or library encountering an <code>Annotated</code> annotation. A tool or library encountering an <code>Annotated</code> type can scan through the metadata elements to determine if they are of interest (e.g., using <a class="reference internal" href="functions#isinstance" title="isinstance"><code>isinstance()</code></a>).</p> <dl class="describe"> <dt class="sig sig-object"> <span class="sig-name descname">Annotated[<type>, <metadata>]</span> +</dt> <dd></dd> +</dl> <p>Here is an example of how you might use <code>Annotated</code> to add metadata to type annotations if you were doing range analysis:</p> <pre data-language="python">@dataclass +class ValueRange: + lo: int + hi: int + +T1 = Annotated[int, ValueRange(-10, 5)] +T2 = Annotated[T1, ValueRange(-20, 3)] +</pre> <p>Details of the syntax:</p> <ul> <li>The first argument to <code>Annotated</code> must be a valid type</li> <li> +<p>Multiple metadata elements can be supplied (<code>Annotated</code> supports variadic arguments):</p> <pre data-language="python">@dataclass +class ctype: + kind: str + +Annotated[int, ValueRange(3, 10), ctype("char")] +</pre> <p>It is up to the tool consuming the annotations to decide whether the client is allowed to add multiple metadata elements to one annotation and how to merge those annotations.</p> </li> <li> +<code>Annotated</code> must be subscripted with at least two arguments ( <code>Annotated[int]</code> is not valid)</li> <li> +<p>The order of the metadata elements is preserved and matters for equality checks:</p> <pre data-language="python">assert Annotated[int, ValueRange(3, 10), ctype("char")] != Annotated[ + int, ctype("char"), ValueRange(3, 10) +] +</pre> </li> <li> +<p>Nested <code>Annotated</code> types are flattened. The order of the metadata elements starts with the innermost annotation:</p> <pre data-language="python">assert Annotated[Annotated[int, ValueRange(3, 10)], ctype("char")] == Annotated[ + int, ValueRange(3, 10), ctype("char") +] +</pre> </li> <li> +<p>Duplicated metadata elements are not removed:</p> <pre data-language="python">assert Annotated[int, ValueRange(3, 10)] != Annotated[ + int, ValueRange(3, 10), ValueRange(3, 10) +] +</pre> </li> <li> +<p><code>Annotated</code> can be used with nested and generic aliases:</p> <pre data-language="python">@dataclass +class MaxLen: + value: int + +type Vec[T] = Annotated[list[tuple[T, T]], MaxLen(10)] + +# When used in a type annotation, a type checker will treat "V" the same as +# ``Annotated[list[tuple[int, int]], MaxLen(10)]``: +type V = Vec[int] +</pre> </li> <li> +<p><code>Annotated</code> cannot be used with an unpacked <a class="reference internal" href="#typing.TypeVarTuple" title="typing.TypeVarTuple"><code>TypeVarTuple</code></a>:</p> <pre data-language="python">type Variadic[*Ts] = Annotated[*Ts, Ann1] # NOT valid +</pre> <p>This would be equivalent to:</p> <pre data-language="python">Annotated[T1, T2, T3, ..., Ann1] +</pre> <p>where <code>T1</code>, <code>T2</code>, etc. are <a class="reference internal" href="#typing.TypeVar" title="typing.TypeVar"><code>TypeVars</code></a>. This would be invalid: only one type should be passed to Annotated.</p> </li> <li> +<p>By default, <a class="reference internal" href="#typing.get_type_hints" title="typing.get_type_hints"><code>get_type_hints()</code></a> strips the metadata from annotations. Pass <code>include_extras=True</code> to have the metadata preserved:</p> <pre data-language="pycon3">>>> from typing import Annotated, get_type_hints +>>> def func(x: Annotated[int, "metadata"]) -> None: pass +... +>>> get_type_hints(func) +{'x': <class 'int'>, 'return': <class 'NoneType'>} +>>> get_type_hints(func, include_extras=True) +{'x': typing.Annotated[int, 'metadata'], 'return': <class 'NoneType'>} +</pre> </li> <li> +<p>At runtime, the metadata associated with an <code>Annotated</code> type can be retrieved via the <code>__metadata__</code> attribute:</p> <pre data-language="pycon3">>>> from typing import Annotated +>>> X = Annotated[int, "very", "important", "metadata"] +>>> X +typing.Annotated[int, 'very', 'important', 'metadata'] +>>> X.__metadata__ +('very', 'important', 'metadata') +</pre> </li> </ul> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt> +<span class="target" id="index-38"></span><a class="pep reference external" href="https://peps.python.org/pep-0593/"><strong>PEP 593</strong></a> - Flexible function and variable annotations</dt> +<dd> +<p>The PEP introducing <code>Annotated</code> to the standard library.</p> </dd> </dl> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.9.</span></p> </div> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="typing.TypeGuard"> +<code>typing.TypeGuard</code> </dt> <dd> +<p>Special typing construct for marking user-defined type guard functions.</p> <p><code>TypeGuard</code> can be used to annotate the return type of a user-defined type guard function. <code>TypeGuard</code> only accepts a single type argument. At runtime, functions marked this way should return a boolean.</p> <p><code>TypeGuard</code> aims to benefit <em>type narrowing</em> – a technique used by static type checkers to determine a more precise type of an expression within a program’s code flow. Usually type narrowing is done by analyzing conditional code flow and applying the narrowing to a block of code. The conditional expression here is sometimes referred to as a “type guard”:</p> <pre data-language="python">def is_str(val: str | float): + # "isinstance" type guard + if isinstance(val, str): + # Type of ``val`` is narrowed to ``str`` + ... + else: + # Else, type of ``val`` is narrowed to ``float``. + ... +</pre> <p>Sometimes it would be convenient to use a user-defined boolean function as a type guard. Such a function should use <code>TypeGuard[...]</code> as its return type to alert static type checkers to this intention.</p> <p>Using <code>-> TypeGuard</code> tells the static type checker that for a given function:</p> <ol class="arabic simple"> <li>The return value is a boolean.</li> <li>If the return value is <code>True</code>, the type of its argument is the type inside <code>TypeGuard</code>.</li> </ol> <p>For example:</p> <pre data-language="python">def is_str_list(val: list[object]) -> TypeGuard[list[str]]: + '''Determines whether all objects in the list are strings''' + return all(isinstance(x, str) for x in val) + +def func1(val: list[object]): + if is_str_list(val): + # Type of ``val`` is narrowed to ``list[str]``. + print(" ".join(val)) + else: + # Type of ``val`` remains as ``list[object]``. + print("Not a list of strings!") +</pre> <p>If <code>is_str_list</code> is a class or instance method, then the type in <code>TypeGuard</code> maps to the type of the second parameter after <code>cls</code> or <code>self</code>.</p> <p>In short, the form <code>def foo(arg: TypeA) -> TypeGuard[TypeB]: ...</code>, means that if <code>foo(arg)</code> returns <code>True</code>, then <code>arg</code> narrows from <code>TypeA</code> to <code>TypeB</code>.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p><code>TypeB</code> need not be a narrower form of <code>TypeA</code> – it can even be a wider form. The main reason is to allow for things like narrowing <code>list[object]</code> to <code>list[str]</code> even though the latter is not a subtype of the former, since <code>list</code> is invariant. The responsibility of writing type-safe type guards is left to the user.</p> </div> <p><code>TypeGuard</code> also works with type variables. See <span class="target" id="index-39"></span><a class="pep reference external" href="https://peps.python.org/pep-0647/"><strong>PEP 647</strong></a> for more details.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="typing.Unpack"> +<code>typing.Unpack</code> </dt> <dd> +<p>Typing operator to conceptually mark an object as having been unpacked.</p> <p>For example, using the unpack operator <code>*</code> on a <a class="reference internal" href="#typevartuple"><span class="std std-ref">type variable tuple</span></a> is equivalent to using <code>Unpack</code> to mark the type variable tuple as having been unpacked:</p> <pre data-language="python">Ts = TypeVarTuple('Ts') +tup: tuple[*Ts] +# Effectively does: +tup: tuple[Unpack[Ts]] +</pre> <p>In fact, <code>Unpack</code> can be used interchangeably with <code>*</code> in the context of <a class="reference internal" href="#typing.TypeVarTuple" title="typing.TypeVarTuple"><code>typing.TypeVarTuple</code></a> and <a class="reference internal" href="stdtypes#tuple" title="tuple"><code>builtins.tuple</code></a> types. You might see <code>Unpack</code> being used explicitly in older versions of Python, where <code>*</code> couldn’t be used in certain places:</p> <pre data-language="python"># In older versions of Python, TypeVarTuple and Unpack +# are located in the `typing_extensions` backports package. +from typing_extensions import TypeVarTuple, Unpack + +Ts = TypeVarTuple('Ts') +tup: tuple[*Ts] # Syntax error on Python <= 3.10! +tup: tuple[Unpack[Ts]] # Semantically equivalent, and backwards-compatible +</pre> <p><code>Unpack</code> can also be used along with <a class="reference internal" href="#typing.TypedDict" title="typing.TypedDict"><code>typing.TypedDict</code></a> for typing <code>**kwargs</code> in a function signature:</p> <pre data-language="python">from typing import TypedDict, Unpack + +class Movie(TypedDict): + name: str + year: int + +# This function expects two keyword arguments - `name` of type `str` +# and `year` of type `int`. +def foo(**kwargs: Unpack[Movie]): ... +</pre> <p>See <span class="target" id="index-40"></span><a class="pep reference external" href="https://peps.python.org/pep-0692/"><strong>PEP 692</strong></a> for more details on using <code>Unpack</code> for <code>**kwargs</code> typing.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd> +</dl> </section> <section id="building-generic-types-and-type-aliases"> <h4>Building generic types and type aliases</h4> <p>The following classes should not be used directly as annotations. Their intended purpose is to be building blocks for creating generic types and type aliases.</p> <p>These objects can be created through special syntax (<a class="reference internal" href="../reference/compound_stmts#type-params"><span class="std std-ref">type parameter lists</span></a> and the <a class="reference internal" href="../reference/simple_stmts#type"><code>type</code></a> statement). For compatibility with Python 3.11 and earlier, they can also be created without the dedicated syntax, as documented below.</p> <dl class="py class"> <dt class="sig sig-object py" id="typing.Generic"> +<code>class typing.Generic</code> </dt> <dd> +<p>Abstract base class for generic types.</p> <p>A generic type is typically declared by adding a list of type parameters after the class name:</p> <pre data-language="python">class Mapping[KT, VT]: + def __getitem__(self, key: KT) -> VT: + ... + # Etc. +</pre> <p>Such a class implicitly inherits from <code>Generic</code>. The runtime semantics of this syntax are discussed in the <a class="reference internal" href="../reference/compound_stmts#generic-classes"><span class="std std-ref">Language Reference</span></a>.</p> <p>This class can then be used as follows:</p> <pre data-language="python">def lookup_name[X, Y](mapping: Mapping[X, Y], key: X, default: Y) -> Y: + try: + return mapping[key] + except KeyError: + return default +</pre> <p>Here the brackets after the function name indicate a <a class="reference internal" href="../reference/compound_stmts#generic-functions"><span class="std std-ref">generic function</span></a>.</p> <p>For backwards compatibility, generic classes can also be declared by explicitly inheriting from <code>Generic</code>. In this case, the type parameters must be declared separately:</p> <pre data-language="python">KT = TypeVar('KT') +VT = TypeVar('VT') + +class Mapping(Generic[KT, VT]): + def __getitem__(self, key: KT) -> VT: + ... + # Etc. +</pre> </dd> +</dl> <span class="target" id="typevar"></span><dl class="py class"> <dt class="sig sig-object py" id="typing.TypeVar"> +<code>class typing.TypeVar(name, *constraints, bound=None, covariant=False, contravariant=False, infer_variance=False)</code> </dt> <dd> +<p>Type variable.</p> <p>The preferred way to construct a type variable is via the dedicated syntax for <a class="reference internal" href="../reference/compound_stmts#generic-functions"><span class="std std-ref">generic functions</span></a>, <a class="reference internal" href="../reference/compound_stmts#generic-classes"><span class="std std-ref">generic classes</span></a>, and <a class="reference internal" href="../reference/compound_stmts#generic-type-aliases"><span class="std std-ref">generic type aliases</span></a>:</p> <pre data-language="python">class Sequence[T]: # T is a TypeVar + ... +</pre> <p>This syntax can also be used to create bound and constrained type variables:</p> <pre data-language="python">class StrSequence[S: str]: # S is a TypeVar bound to str + ... + + +class StrOrBytesSequence[A: (str, bytes)]: # A is a TypeVar constrained to str or bytes + ... +</pre> <p>However, if desired, reusable type variables can also be constructed manually, like so:</p> <pre data-language="python">T = TypeVar('T') # Can be anything +S = TypeVar('S', bound=str) # Can be any subtype of str +A = TypeVar('A', str, bytes) # Must be exactly str or bytes +</pre> <p>Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function and type alias definitions. See <a class="reference internal" href="#typing.Generic" title="typing.Generic"><code>Generic</code></a> for more information on generic types. Generic functions work as follows:</p> <pre data-language="python">def repeat[T](x: T, n: int) -> Sequence[T]: + """Return a list containing n references to x.""" + return [x]*n + + +def print_capitalized[S: str](x: S) -> S: + """Print x capitalized, and return x.""" + print(x.capitalize()) + return x + + +def concatenate[A: (str, bytes)](x: A, y: A) -> A: + """Add two strings or bytes objects together.""" + return x + y +</pre> <p>Note that type variables can be <em>bound</em>, <em>constrained</em>, or neither, but cannot be both bound <em>and</em> constrained.</p> <p>The variance of type variables is inferred by type checkers when they are created through the <a class="reference internal" href="../reference/compound_stmts#type-params"><span class="std std-ref">type parameter syntax</span></a> or when <code>infer_variance=True</code> is passed. Manually created type variables may be explicitly marked covariant or contravariant by passing <code>covariant=True</code> or <code>contravariant=True</code>. By default, manually created type variables are invariant. See <span class="target" id="index-41"></span><a class="pep reference external" href="https://peps.python.org/pep-0484/"><strong>PEP 484</strong></a> and <span class="target" id="index-42"></span><a class="pep reference external" href="https://peps.python.org/pep-0695/"><strong>PEP 695</strong></a> for more details.</p> <p>Bound type variables and constrained type variables have different semantics in several important ways. Using a <em>bound</em> type variable means that the <code>TypeVar</code> will be solved using the most specific type possible:</p> <pre data-language="python">x = print_capitalized('a string') +reveal_type(x) # revealed type is str + +class StringSubclass(str): + pass + +y = print_capitalized(StringSubclass('another string')) +reveal_type(y) # revealed type is StringSubclass + +z = print_capitalized(45) # error: int is not a subtype of str +</pre> <p>Type variables can be bound to concrete types, abstract types (ABCs or protocols), and even unions of types:</p> <pre data-language="python"># Can be anything with an __abs__ method +def print_abs[T: SupportsAbs](arg: T) -> None: + print("Absolute value:", abs(arg)) + +U = TypeVar('U', bound=str|bytes) # Can be any subtype of the union str|bytes +V = TypeVar('V', bound=SupportsAbs) # Can be anything with an __abs__ method +</pre> <p id="typing-constrained-typevar">Using a <em>constrained</em> type variable, however, means that the <code>TypeVar</code> can only ever be solved as being exactly one of the constraints given:</p> <pre data-language="python">a = concatenate('one', 'two') +reveal_type(a) # revealed type is str + +b = concatenate(StringSubclass('one'), StringSubclass('two')) +reveal_type(b) # revealed type is str, despite StringSubclass being passed in + +c = concatenate('one', b'two') # error: type variable 'A' can be either str or bytes in a function call, but not both +</pre> <p>At runtime, <code>isinstance(x, T)</code> will raise <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a>.</p> <dl class="py attribute"> <dt class="sig sig-object py" id="typing.TypeVar.__name__"> +<code>__name__</code> </dt> <dd> +<p>The name of the type variable.</p> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="typing.TypeVar.__covariant__"> +<code>__covariant__</code> </dt> <dd> +<p>Whether the type var has been explicitly marked as covariant.</p> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="typing.TypeVar.__contravariant__"> +<code>__contravariant__</code> </dt> <dd> +<p>Whether the type var has been explicitly marked as contravariant.</p> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="typing.TypeVar.__infer_variance__"> +<code>__infer_variance__</code> </dt> <dd> +<p>Whether the type variable’s variance should be inferred by type checkers.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="typing.TypeVar.__bound__"> +<code>__bound__</code> </dt> <dd> +<p>The bound of the type variable, if any.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>For type variables created through <a class="reference internal" href="../reference/compound_stmts#type-params"><span class="std std-ref">type parameter syntax</span></a>, the bound is evaluated only when the attribute is accessed, not when the type variable is created (see <a class="reference internal" href="../reference/executionmodel#lazy-evaluation"><span class="std std-ref">Lazy evaluation</span></a>).</p> </div> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="typing.TypeVar.__constraints__"> +<code>__constraints__</code> </dt> <dd> +<p>A tuple containing the constraints of the type variable, if any.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>For type variables created through <a class="reference internal" href="../reference/compound_stmts#type-params"><span class="std std-ref">type parameter syntax</span></a>, the constraints are evaluated only when the attribute is accessed, not when the type variable is created (see <a class="reference internal" href="../reference/executionmodel#lazy-evaluation"><span class="std std-ref">Lazy evaluation</span></a>).</p> </div> </dd> +</dl> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Type variables can now be declared using the <a class="reference internal" href="../reference/compound_stmts#type-params"><span class="std std-ref">type parameter</span></a> syntax introduced by <span class="target" id="index-43"></span><a class="pep reference external" href="https://peps.python.org/pep-0695/"><strong>PEP 695</strong></a>. The <code>infer_variance</code> parameter was added.</p> </div> </dd> +</dl> <span class="target" id="typevartuple"></span><dl class="py class"> <dt class="sig sig-object py" id="typing.TypeVarTuple"> +<code>class typing.TypeVarTuple(name)</code> </dt> <dd> +<p>Type variable tuple. A specialized form of <a class="reference internal" href="#typevar"><span class="std std-ref">type variable</span></a> that enables <em>variadic</em> generics.</p> <p>Type variable tuples can be declared in <a class="reference internal" href="../reference/compound_stmts#type-params"><span class="std std-ref">type parameter lists</span></a> using a single asterisk (<code>*</code>) before the name:</p> <pre data-language="python">def move_first_element_to_last[T, *Ts](tup: tuple[T, *Ts]) -> tuple[*Ts, T]: + return (*tup[1:], tup[0]) +</pre> <p>Or by explicitly invoking the <code>TypeVarTuple</code> constructor:</p> <pre data-language="python">T = TypeVar("T") +Ts = TypeVarTuple("Ts") + +def move_first_element_to_last(tup: tuple[T, *Ts]) -> tuple[*Ts, T]: + return (*tup[1:], tup[0]) +</pre> <p>A normal type variable enables parameterization with a single type. A type variable tuple, in contrast, allows parameterization with an <em>arbitrary</em> number of types by acting like an <em>arbitrary</em> number of type variables wrapped in a tuple. For example:</p> <pre data-language="python"># T is bound to int, Ts is bound to () +# Return value is (1,), which has type tuple[int] +move_first_element_to_last(tup=(1,)) + +# T is bound to int, Ts is bound to (str,) +# Return value is ('spam', 1), which has type tuple[str, int] +move_first_element_to_last(tup=(1, 'spam')) + +# T is bound to int, Ts is bound to (str, float) +# Return value is ('spam', 3.0, 1), which has type tuple[str, float, int] +move_first_element_to_last(tup=(1, 'spam', 3.0)) + +# This fails to type check (and fails at runtime) +# because tuple[()] is not compatible with tuple[T, *Ts] +# (at least one element is required) +move_first_element_to_last(tup=()) +</pre> <p>Note the use of the unpacking operator <code>*</code> in <code>tuple[T, *Ts]</code>. Conceptually, you can think of <code>Ts</code> as a tuple of type variables <code>(T1, T2, ...)</code>. <code>tuple[T, *Ts]</code> would then become <code>tuple[T, *(T1, T2, ...)]</code>, which is equivalent to <code>tuple[T, T1, T2, ...]</code>. (Note that in older versions of Python, you might see this written using <a class="reference internal" href="#typing.Unpack" title="typing.Unpack"><code>Unpack</code></a> instead, as <code>Unpack[Ts]</code>.)</p> <p>Type variable tuples must <em>always</em> be unpacked. This helps distinguish type variable tuples from normal type variables:</p> <pre data-language="python">x: Ts # Not valid +x: tuple[Ts] # Not valid +x: tuple[*Ts] # The correct way to do it +</pre> <p>Type variable tuples can be used in the same contexts as normal type variables. For example, in class definitions, arguments, and return types:</p> <pre data-language="python">class Array[*Shape]: + def __getitem__(self, key: tuple[*Shape]) -> float: ... + def __abs__(self) -> "Array[*Shape]": ... + def get_shape(self) -> tuple[*Shape]: ... +</pre> <p>Type variable tuples can be happily combined with normal type variables:</p> <pre data-language="python">class Array[DType, *Shape]: # This is fine + pass + +class Array2[*Shape, DType]: # This would also be fine + pass + +class Height: ... +class Width: ... + +float_array_1d: Array[float, Height] = Array() # Totally fine +int_array_2d: Array[int, Height, Width] = Array() # Yup, fine too +</pre> <p>However, note that at most one type variable tuple may appear in a single list of type arguments or type parameters:</p> <pre data-language="python">x: tuple[*Ts, *Ts] # Not valid +class Array[*Shape, *Shape]: # Not valid + pass +</pre> <p>Finally, an unpacked type variable tuple can be used as the type annotation of <code>*args</code>:</p> <pre data-language="python">def call_soon[*Ts]( + callback: Callable[[*Ts], None], + *args: *Ts +) -> None: + ... + callback(*args) +</pre> <p>In contrast to non-unpacked annotations of <code>*args</code> - e.g. <code>*args: int</code>, which would specify that <em>all</em> arguments are <code>int</code> - <code>*args: *Ts</code> enables reference to the types of the <em>individual</em> arguments in <code>*args</code>. Here, this allows us to ensure the types of the <code>*args</code> passed to <code>call_soon</code> match the types of the (positional) arguments of <code>callback</code>.</p> <p>See <span class="target" id="index-44"></span><a class="pep reference external" href="https://peps.python.org/pep-0646/"><strong>PEP 646</strong></a> for more details on type variable tuples.</p> <dl class="py attribute"> <dt class="sig sig-object py" id="typing.TypeVarTuple.__name__"> +<code>__name__</code> </dt> <dd> +<p>The name of the type variable tuple.</p> </dd> +</dl> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Type variable tuples can now be declared using the <a class="reference internal" href="../reference/compound_stmts#type-params"><span class="std std-ref">type parameter</span></a> syntax introduced by <span class="target" id="index-45"></span><a class="pep reference external" href="https://peps.python.org/pep-0695/"><strong>PEP 695</strong></a>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.ParamSpec"> +<code>class typing.ParamSpec(name, *, bound=None, covariant=False, contravariant=False)</code> </dt> <dd> +<p>Parameter specification variable. A specialized version of <a class="reference internal" href="#typevar"><span class="std std-ref">type variables</span></a>.</p> <p>In <a class="reference internal" href="../reference/compound_stmts#type-params"><span class="std std-ref">type parameter lists</span></a>, parameter specifications can be declared with two asterisks (<code>**</code>):</p> <pre data-language="python">type IntFunc[**P] = Callable[P, int] +</pre> <p>For compatibility with Python 3.11 and earlier, <code>ParamSpec</code> objects can also be created as follows:</p> <pre data-language="python">P = ParamSpec('P') +</pre> <p>Parameter specification variables exist primarily for the benefit of static type checkers. They are used to forward the parameter types of one callable to another callable – a pattern commonly found in higher order functions and decorators. They are only valid when used in <code>Concatenate</code>, or as the first argument to <code>Callable</code>, or as parameters for user-defined Generics. See <a class="reference internal" href="#typing.Generic" title="typing.Generic"><code>Generic</code></a> for more information on generic types.</p> <p>For example, to add basic logging to a function, one can create a decorator <code>add_logging</code> to log function calls. The parameter specification variable tells the type checker that the callable passed into the decorator and the new callable returned by it have inter-dependent type parameters:</p> <pre data-language="python">from collections.abc import Callable +import logging + +def add_logging[T, **P](f: Callable[P, T]) -> Callable[P, T]: + '''A type-safe decorator to add logging to a function.''' + def inner(*args: P.args, **kwargs: P.kwargs) -> T: + logging.info(f'{f.__name__} was called') + return f(*args, **kwargs) + return inner + +@add_logging +def add_two(x: float, y: float) -> float: + '''Add two numbers together.''' + return x + y +</pre> <p>Without <code>ParamSpec</code>, the simplest way to annotate this previously was to use a <a class="reference internal" href="#typing.TypeVar" title="typing.TypeVar"><code>TypeVar</code></a> with bound <code>Callable[..., Any]</code>. However this causes two problems:</p> <ol class="arabic simple"> <li>The type checker can’t type check the <code>inner</code> function because <code>*args</code> and <code>**kwargs</code> have to be typed <a class="reference internal" href="#typing.Any" title="typing.Any"><code>Any</code></a>.</li> <li> +<a class="reference internal" href="#typing.cast" title="typing.cast"><code>cast()</code></a> may be required in the body of the <code>add_logging</code> decorator when returning the <code>inner</code> function, or the static type checker must be told to ignore the <code>return inner</code>.</li> </ol> <dl class="py attribute"> <dt class="sig sig-object py" id="typing.ParamSpec.args"> +<code>args</code> </dt> <dd></dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="typing.ParamSpec.kwargs"> +<code>kwargs</code> </dt> <dd> +<p>Since <code>ParamSpec</code> captures both positional and keyword parameters, <code>P.args</code> and <code>P.kwargs</code> can be used to split a <code>ParamSpec</code> into its components. <code>P.args</code> represents the tuple of positional parameters in a given call and should only be used to annotate <code>*args</code>. <code>P.kwargs</code> represents the mapping of keyword parameters to their values in a given call, and should be only be used to annotate <code>**kwargs</code>. Both attributes require the annotated parameter to be in scope. At runtime, <code>P.args</code> and <code>P.kwargs</code> are instances respectively of <a class="reference internal" href="#typing.ParamSpecArgs" title="typing.ParamSpecArgs"><code>ParamSpecArgs</code></a> and <a class="reference internal" href="#typing.ParamSpecKwargs" title="typing.ParamSpecKwargs"><code>ParamSpecKwargs</code></a>.</p> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="typing.ParamSpec.__name__"> +<code>__name__</code> </dt> <dd> +<p>The name of the parameter specification.</p> </dd> +</dl> <p>Parameter specification variables created with <code>covariant=True</code> or <code>contravariant=True</code> can be used to declare covariant or contravariant generic types. The <code>bound</code> argument is also accepted, similar to <a class="reference internal" href="#typing.TypeVar" title="typing.TypeVar"><code>TypeVar</code></a>. However the actual semantics of these keywords are yet to be decided.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Parameter specifications can now be declared using the <a class="reference internal" href="../reference/compound_stmts#type-params"><span class="std std-ref">type parameter</span></a> syntax introduced by <span class="target" id="index-46"></span><a class="pep reference external" href="https://peps.python.org/pep-0695/"><strong>PEP 695</strong></a>.</p> </div> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Only parameter specification variables defined in global scope can be pickled.</p> </div> <div class="admonition seealso"> <p class="admonition-title">See also</p> <ul class="simple"> <li> +<span class="target" id="index-47"></span><a class="pep reference external" href="https://peps.python.org/pep-0612/"><strong>PEP 612</strong></a> – Parameter Specification Variables (the PEP which introduced <code>ParamSpec</code> and <code>Concatenate</code>)</li> <li><a class="reference internal" href="#typing.Concatenate" title="typing.Concatenate"><code>Concatenate</code></a></li> <li><a class="reference internal" href="#annotating-callables"><span class="std std-ref">Annotating callable objects</span></a></li> </ul> </div> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="typing.ParamSpecArgs"> +<code>typing.ParamSpecArgs</code> </dt> <dd></dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="typing.ParamSpecKwargs"> +<code>typing.ParamSpecKwargs</code> </dt> <dd> +<p>Arguments and keyword arguments attributes of a <a class="reference internal" href="#typing.ParamSpec" title="typing.ParamSpec"><code>ParamSpec</code></a>. The <code>P.args</code> attribute of a <code>ParamSpec</code> is an instance of <code>ParamSpecArgs</code>, and <code>P.kwargs</code> is an instance of <code>ParamSpecKwargs</code>. They are intended for runtime introspection and have no special meaning to static type checkers.</p> <p>Calling <a class="reference internal" href="#typing.get_origin" title="typing.get_origin"><code>get_origin()</code></a> on either of these objects will return the original <code>ParamSpec</code>:</p> <pre data-language="pycon3">>>> from typing import ParamSpec, get_origin +>>> P = ParamSpec("P") +>>> get_origin(P.args) is P +True +>>> get_origin(P.kwargs) is P +True +</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.TypeAliasType"> +<code>class typing.TypeAliasType(name, value, *, type_params=())</code> </dt> <dd> +<p>The type of type aliases created through the <a class="reference internal" href="../reference/simple_stmts#type"><code>type</code></a> statement.</p> <p>Example:</p> <pre data-language="pycon3">>>> type Alias = int +>>> type(Alias) +<class 'typing.TypeAliasType'> +</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> <dl class="py attribute"> <dt class="sig sig-object py" id="typing.TypeAliasType.__name__"> +<code>__name__</code> </dt> <dd> +<p>The name of the type alias:</p> <pre data-language="pycon3">>>> type Alias = int +>>> Alias.__name__ +'Alias' +</pre> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="typing.TypeAliasType.__module__"> +<code>__module__</code> </dt> <dd> +<p>The module in which the type alias was defined:</p> <pre data-language="python">>>> type Alias = int +>>> Alias.__module__ +'__main__' +</pre> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="typing.TypeAliasType.__type_params__"> +<code>__type_params__</code> </dt> <dd> +<p>The type parameters of the type alias, or an empty tuple if the alias is not generic:</p> <pre data-language="pycon3">>>> type ListOrSet[T] = list[T] | set[T] +>>> ListOrSet.__type_params__ +(T,) +>>> type NotGeneric = int +>>> NotGeneric.__type_params__ +() +</pre> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="typing.TypeAliasType.__value__"> +<code>__value__</code> </dt> <dd> +<p>The type alias’s value. This is <a class="reference internal" href="../reference/executionmodel#lazy-evaluation"><span class="std std-ref">lazily evaluated</span></a>, so names used in the definition of the alias are not resolved until the <code>__value__</code> attribute is accessed:</p> <pre data-language="pycon3">>>> type Mutually = Recursive +>>> type Recursive = Mutually +>>> Mutually +Mutually +>>> Recursive +Recursive +>>> Mutually.__value__ +Recursive +>>> Recursive.__value__ +Mutually +</pre> </dd> +</dl> </dd> +</dl> </section> <section id="other-special-directives"> <h4>Other special directives</h4> <p>These functions and classes should not be used directly as annotations. Their intended purpose is to be building blocks for creating and declaring types.</p> <dl class="py class"> <dt class="sig sig-object py" id="typing.NamedTuple"> +<code>class typing.NamedTuple</code> </dt> <dd> +<p>Typed version of <a class="reference internal" href="collections#collections.namedtuple" title="collections.namedtuple"><code>collections.namedtuple()</code></a>.</p> <p>Usage:</p> <pre data-language="python">class Employee(NamedTuple): + name: str + id: int +</pre> <p>This is equivalent to:</p> <pre data-language="python">Employee = collections.namedtuple('Employee', ['name', 'id']) +</pre> <p>To give a field a default value, you can assign to it in the class body:</p> <pre data-language="python">class Employee(NamedTuple): + name: str + id: int = 3 + +employee = Employee('Guido') +assert employee.id == 3 +</pre> <p>Fields with a default value must come after any fields without a default.</p> <p>The resulting class has an extra attribute <code>__annotations__</code> giving a dict that maps the field names to the field types. (The field names are in the <code>_fields</code> attribute and the default values are in the <code>_field_defaults</code> attribute, both of which are part of the <a class="reference internal" href="collections#collections.namedtuple" title="collections.namedtuple"><code>namedtuple()</code></a> API.)</p> <p><code>NamedTuple</code> subclasses can also have docstrings and methods:</p> <pre data-language="python">class Employee(NamedTuple): + """Represents an employee.""" + name: str + id: int = 3 + + def __repr__(self) -> str: + return f'<Employee {self.name}, id={self.id}>' +</pre> <p><code>NamedTuple</code> subclasses can be generic:</p> <pre data-language="python">class Group[T](NamedTuple): + key: T + group: list[T] +</pre> <p>Backward-compatible usage:</p> <pre data-language="python"># For creating a generic NamedTuple on Python 3.11 or lower +class Group(NamedTuple, Generic[T]): + key: T + group: list[T] + +# A functional syntax is also supported +Employee = NamedTuple('Employee', [('name', str), ('id', int)]) +</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>Added support for <span class="target" id="index-48"></span><a class="pep reference external" href="https://peps.python.org/pep-0526/"><strong>PEP 526</strong></a> variable annotation syntax.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6.1: </span>Added support for default values, methods, and docstrings.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>The <code>_field_types</code> and <code>__annotations__</code> attributes are now regular dictionaries instead of instances of <code>OrderedDict</code>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9: </span>Removed the <code>_field_types</code> attribute in favor of the more standard <code>__annotations__</code> attribute which has the same information.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Added support for generic namedtuples.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.NewType"> +<code>class typing.NewType(name, tp)</code> </dt> <dd> +<p>Helper class to create low-overhead <a class="reference internal" href="#distinct"><span class="std std-ref">distinct types</span></a>.</p> <p>A <code>NewType</code> is considered a distinct type by a typechecker. At runtime, however, calling a <code>NewType</code> returns its argument unchanged.</p> <p>Usage:</p> <pre data-language="python">UserId = NewType('UserId', int) # Declare the NewType "UserId" +first_user = UserId(1) # "UserId" returns the argument unchanged at runtime +</pre> <dl class="py attribute"> <dt class="sig sig-object py" id="typing.NewType.__module__"> +<code>__module__</code> </dt> <dd> +<p>The module in which the new type is defined.</p> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="typing.NewType.__name__"> +<code>__name__</code> </dt> <dd> +<p>The name of the new type.</p> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="typing.NewType.__supertype__"> +<code>__supertype__</code> </dt> <dd> +<p>The type that the new type is based on.</p> </dd> +</dl> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.2.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span><code>NewType</code> is now a class rather than a function.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.Protocol"> +<code>class typing.Protocol(Generic)</code> </dt> <dd> +<p>Base class for protocol classes.</p> <p>Protocol classes are defined like this:</p> <pre data-language="python">class Proto(Protocol): + def meth(self) -> int: + ... +</pre> <p>Such classes are primarily used with static type checkers that recognize structural subtyping (static duck-typing), for example:</p> <pre data-language="python">class C: + def meth(self) -> int: + return 0 + +def func(x: Proto) -> int: + return x.meth() + +func(C()) # Passes static type check +</pre> <p>See <span class="target" id="index-49"></span><a class="pep reference external" href="https://peps.python.org/pep-0544/"><strong>PEP 544</strong></a> for more details. Protocol classes decorated with <a class="reference internal" href="#typing.runtime_checkable" title="typing.runtime_checkable"><code>runtime_checkable()</code></a> (described later) act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures.</p> <p>Protocol classes can be generic, for example:</p> <pre data-language="python">class GenProto[T](Protocol): + def meth(self) -> T: + ... +</pre> <p>In code that needs to be compatible with Python 3.11 or older, generic Protocols can be written as follows:</p> <pre data-language="python">T = TypeVar("T") + +class GenProto(Protocol[T]): + def meth(self) -> T: + ... +</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd> +</dl> <dl class="py function"> <dt class="sig sig-object py" id="typing.runtime_checkable"> +<code>@typing.runtime_checkable</code> </dt> <dd> +<p>Mark a protocol class as a runtime protocol.</p> <p>Such a protocol can be used with <a class="reference internal" href="functions#isinstance" title="isinstance"><code>isinstance()</code></a> and <a class="reference internal" href="functions#issubclass" title="issubclass"><code>issubclass()</code></a>. This raises <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> when applied to a non-protocol class. This allows a simple-minded structural check, very similar to “one trick ponies” in <a class="reference internal" href="collections.abc#module-collections.abc" title="collections.abc: Abstract base classes for containers"><code>collections.abc</code></a> such as <a class="reference internal" href="collections.abc#collections.abc.Iterable" title="collections.abc.Iterable"><code>Iterable</code></a>. For example:</p> <pre data-language="python">@runtime_checkable +class Closable(Protocol): + def close(self): ... + +assert isinstance(open('/some/file'), Closable) + +@runtime_checkable +class Named(Protocol): + name: str + +import threading +assert isinstance(threading.Thread(name='Bob'), Named) +</pre> <div class="admonition note"> <p class="admonition-title">Note</p> <p><code>runtime_checkable()</code> will check only the presence of the required methods or attributes, not their type signatures or types. For example, <a class="reference internal" href="ssl#ssl.SSLObject" title="ssl.SSLObject"><code>ssl.SSLObject</code></a> is a class, therefore it passes an <a class="reference internal" href="functions#issubclass" title="issubclass"><code>issubclass()</code></a> check against <a class="reference internal" href="#annotating-callables"><span class="std std-ref">Callable</span></a>. However, the <code>ssl.SSLObject.__init__</code> method exists only to raise a <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> with a more informative message, therefore making it impossible to call (instantiate) <a class="reference internal" href="ssl#ssl.SSLObject" title="ssl.SSLObject"><code>ssl.SSLObject</code></a>.</p> </div> <div class="admonition note"> <p class="admonition-title">Note</p> <p>An <a class="reference internal" href="functions#isinstance" title="isinstance"><code>isinstance()</code></a> check against a runtime-checkable protocol can be surprisingly slow compared to an <code>isinstance()</code> check against a non-protocol class. Consider using alternative idioms such as <a class="reference internal" href="functions#hasattr" title="hasattr"><code>hasattr()</code></a> calls for structural checks in performance-sensitive code.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>The internal implementation of <a class="reference internal" href="functions#isinstance" title="isinstance"><code>isinstance()</code></a> checks against runtime-checkable protocols now uses <a class="reference internal" href="inspect#inspect.getattr_static" title="inspect.getattr_static"><code>inspect.getattr_static()</code></a> to look up attributes (previously, <a class="reference internal" href="functions#hasattr" title="hasattr"><code>hasattr()</code></a> was used). As a result, some objects which used to be considered instances of a runtime-checkable protocol may no longer be considered instances of that protocol on Python 3.12+, and vice versa. Most users are unlikely to be affected by this change.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>The members of a runtime-checkable protocol are now considered “frozen” at runtime as soon as the class has been created. Monkey-patching attributes onto a runtime-checkable protocol will still work, but will have no impact on <a class="reference internal" href="functions#isinstance" title="isinstance"><code>isinstance()</code></a> checks comparing objects to the protocol. See <a class="reference internal" href="https://docs.python.org/3.12/whatsnew/3.12.html#whatsnew-typing-py312"><span class="std std-ref">“What’s new in Python 3.12”</span></a> for more details.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.TypedDict"> +<code>class typing.TypedDict(dict)</code> </dt> <dd> +<p>Special construct to add type hints to a dictionary. At runtime it is a plain <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a>.</p> <p><code>TypedDict</code> declares a dictionary type that expects all of its instances to have a certain set of keys, where each key is associated with a value of a consistent type. This expectation is not checked at runtime but is only enforced by type checkers. Usage:</p> <pre data-language="python">class Point2D(TypedDict): + x: int + y: int + label: str + +a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK +b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check + +assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first') +</pre> <p>To allow using this feature with older versions of Python that do not support <span class="target" id="index-50"></span><a class="pep reference external" href="https://peps.python.org/pep-0526/"><strong>PEP 526</strong></a>, <code>TypedDict</code> supports two additional equivalent syntactic forms:</p> <ul> <li> +<p>Using a literal <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> as the second argument:</p> <pre data-language="python">Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) +</pre> </li> <li> +<p>Using keyword arguments:</p> <pre data-language="python">Point2D = TypedDict('Point2D', x=int, y=int, label=str) +</pre> </li> </ul> <div class="deprecated-removed"> <p><span class="versionmodified">Deprecated since version 3.11, will be removed in version 3.13: </span>The keyword-argument syntax is deprecated in 3.11 and will be removed in 3.13. It may also be unsupported by static type checkers.</p> </div> <p>The functional syntax should also be used when any of the keys are not valid <a class="reference internal" href="../reference/lexical_analysis#identifiers"><span class="std std-ref">identifiers</span></a>, for example because they are keywords or contain hyphens. Example:</p> <pre data-language="python"># raises SyntaxError +class Point2D(TypedDict): + in: int # 'in' is a keyword + x-y: int # name with hyphens + +# OK, functional syntax +Point2D = TypedDict('Point2D', {'in': int, 'x-y': int}) +</pre> <p>By default, all keys must be present in a <code>TypedDict</code>. It is possible to mark individual keys as non-required using <a class="reference internal" href="#typing.NotRequired" title="typing.NotRequired"><code>NotRequired</code></a>:</p> <pre data-language="python">class Point2D(TypedDict): + x: int + y: int + label: NotRequired[str] + +# Alternative syntax +Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': NotRequired[str]}) +</pre> <p>This means that a <code>Point2D</code> <code>TypedDict</code> can have the <code>label</code> key omitted.</p> <p>It is also possible to mark all keys as non-required by default by specifying a totality of <code>False</code>:</p> <pre data-language="python">class Point2D(TypedDict, total=False): + x: int + y: int + +# Alternative syntax +Point2D = TypedDict('Point2D', {'x': int, 'y': int}, total=False) +</pre> <p>This means that a <code>Point2D</code> <code>TypedDict</code> can have any of the keys omitted. A type checker is only expected to support a literal <code>False</code> or <code>True</code> as the value of the <code>total</code> argument. <code>True</code> is the default, and makes all items defined in the class body required.</p> <p>Individual keys of a <code>total=False</code> <code>TypedDict</code> can be marked as required using <a class="reference internal" href="#typing.Required" title="typing.Required"><code>Required</code></a>:</p> <pre data-language="python">class Point2D(TypedDict, total=False): + x: Required[int] + y: Required[int] + label: str + +# Alternative syntax +Point2D = TypedDict('Point2D', { + 'x': Required[int], + 'y': Required[int], + 'label': str +}, total=False) +</pre> <p>It is possible for a <code>TypedDict</code> type to inherit from one or more other <code>TypedDict</code> types using the class-based syntax. Usage:</p> <pre data-language="python">class Point3D(Point2D): + z: int +</pre> <p><code>Point3D</code> has three items: <code>x</code>, <code>y</code> and <code>z</code>. It is equivalent to this definition:</p> <pre data-language="python">class Point3D(TypedDict): + x: int + y: int + z: int +</pre> <p>A <code>TypedDict</code> cannot inherit from a non-<code>TypedDict</code> class, except for <a class="reference internal" href="#typing.Generic" title="typing.Generic"><code>Generic</code></a>. For example:</p> <pre data-language="python">class X(TypedDict): + x: int + +class Y(TypedDict): + y: int + +class Z(object): pass # A non-TypedDict class + +class XY(X, Y): pass # OK + +class XZ(X, Z): pass # raises TypeError +</pre> <p>A <code>TypedDict</code> can be generic:</p> <pre data-language="python">class Group[T](TypedDict): + key: T + group: list[T] +</pre> <p>To create a generic <code>TypedDict</code> that is compatible with Python 3.11 or lower, inherit from <a class="reference internal" href="#typing.Generic" title="typing.Generic"><code>Generic</code></a> explicitly:</p> <pre data-language="python">T = TypeVar("T") + +class Group(TypedDict, Generic[T]): + key: T + group: list[T] +</pre> <p>A <code>TypedDict</code> can be introspected via annotations dicts (see <a class="reference internal" href="../howto/annotations#annotations-howto"><span class="std std-ref">Annotations Best Practices</span></a> for more information on annotations best practices), <a class="reference internal" href="#typing.TypedDict.__total__" title="typing.TypedDict.__total__"><code>__total__</code></a>, <a class="reference internal" href="#typing.TypedDict.__required_keys__" title="typing.TypedDict.__required_keys__"><code>__required_keys__</code></a>, and <a class="reference internal" href="#typing.TypedDict.__optional_keys__" title="typing.TypedDict.__optional_keys__"><code>__optional_keys__</code></a>.</p> <dl class="py attribute"> <dt class="sig sig-object py" id="typing.TypedDict.__total__"> +<code>__total__</code> </dt> <dd> +<p><code>Point2D.__total__</code> gives the value of the <code>total</code> argument. Example:</p> <pre data-language="pycon3">>>> from typing import TypedDict +>>> class Point2D(TypedDict): pass +>>> Point2D.__total__ +True +>>> class Point2D(TypedDict, total=False): pass +>>> Point2D.__total__ +False +>>> class Point3D(Point2D): pass +>>> Point3D.__total__ +True +</pre> <p>This attribute reflects <em>only</em> the value of the <code>total</code> argument to the current <code>TypedDict</code> class, not whether the class is semantically total. For example, a <code>TypedDict</code> with <code>__total__</code> set to True may have keys marked with <a class="reference internal" href="#typing.NotRequired" title="typing.NotRequired"><code>NotRequired</code></a>, or it may inherit from another <code>TypedDict</code> with <code>total=False</code>. Therefore, it is generally better to use <a class="reference internal" href="#typing.TypedDict.__required_keys__" title="typing.TypedDict.__required_keys__"><code>__required_keys__</code></a> and <a class="reference internal" href="#typing.TypedDict.__optional_keys__" title="typing.TypedDict.__optional_keys__"><code>__optional_keys__</code></a> for introspection.</p> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="typing.TypedDict.__required_keys__"> +<code>__required_keys__</code> </dt> <dd> +<div class="versionadded"> <p><span class="versionmodified added">New in version 3.9.</span></p> </div> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="typing.TypedDict.__optional_keys__"> +<code>__optional_keys__</code> </dt> <dd> +<p><code>Point2D.__required_keys__</code> and <code>Point2D.__optional_keys__</code> return <a class="reference internal" href="stdtypes#frozenset" title="frozenset"><code>frozenset</code></a> objects containing required and non-required keys, respectively.</p> <p>Keys marked with <a class="reference internal" href="#typing.Required" title="typing.Required"><code>Required</code></a> will always appear in <code>__required_keys__</code> and keys marked with <a class="reference internal" href="#typing.NotRequired" title="typing.NotRequired"><code>NotRequired</code></a> will always appear in <code>__optional_keys__</code>.</p> <p>For backwards compatibility with Python 3.10 and below, it is also possible to use inheritance to declare both required and non-required keys in the same <code>TypedDict</code> . This is done by declaring a <code>TypedDict</code> with one value for the <code>total</code> argument and then inheriting from it in another <code>TypedDict</code> with a different value for <code>total</code>:</p> <pre data-language="pycon3">>>> class Point2D(TypedDict, total=False): +... x: int +... y: int +... +>>> class Point3D(Point2D): +... z: int +... +>>> Point3D.__required_keys__ == frozenset({'z'}) +True +>>> Point3D.__optional_keys__ == frozenset({'x', 'y'}) +True +</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.9.</span></p> </div> <div class="admonition note"> <p class="admonition-title">Note</p> <p>If <code>from __future__ import annotations</code> is used or if annotations are given as strings, annotations are not evaluated when the <code>TypedDict</code> is defined. Therefore, the runtime introspection that <code>__required_keys__</code> and <code>__optional_keys__</code> rely on may not work properly, and the values of the attributes may be incorrect.</p> </div> </dd> +</dl> <p>See <span class="target" id="index-51"></span><a class="pep reference external" href="https://peps.python.org/pep-0589/"><strong>PEP 589</strong></a> for more examples and detailed rules of using <code>TypedDict</code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Added support for marking individual keys as <a class="reference internal" href="#typing.Required" title="typing.Required"><code>Required</code></a> or <a class="reference internal" href="#typing.NotRequired" title="typing.NotRequired"><code>NotRequired</code></a>. See <span class="target" id="index-52"></span><a class="pep reference external" href="https://peps.python.org/pep-0655/"><strong>PEP 655</strong></a>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Added support for generic <code>TypedDict</code>s.</p> </div> </dd> +</dl> </section> </section> <section id="protocols"> <h3>Protocols</h3> <p>The following protocols are provided by the typing module. All are decorated with <a class="reference internal" href="#typing.runtime_checkable" title="typing.runtime_checkable"><code>@runtime_checkable</code></a>.</p> <dl class="py class"> <dt class="sig sig-object py" id="typing.SupportsAbs"> +<code>class typing.SupportsAbs</code> </dt> <dd> +<p>An ABC with one abstract method <code>__abs__</code> that is covariant in its return type.</p> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.SupportsBytes"> +<code>class typing.SupportsBytes</code> </dt> <dd> +<p>An ABC with one abstract method <code>__bytes__</code>.</p> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.SupportsComplex"> +<code>class typing.SupportsComplex</code> </dt> <dd> +<p>An ABC with one abstract method <code>__complex__</code>.</p> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.SupportsFloat"> +<code>class typing.SupportsFloat</code> </dt> <dd> +<p>An ABC with one abstract method <code>__float__</code>.</p> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.SupportsIndex"> +<code>class typing.SupportsIndex</code> </dt> <dd> +<p>An ABC with one abstract method <code>__index__</code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.SupportsInt"> +<code>class typing.SupportsInt</code> </dt> <dd> +<p>An ABC with one abstract method <code>__int__</code>.</p> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.SupportsRound"> +<code>class typing.SupportsRound</code> </dt> <dd> +<p>An ABC with one abstract method <code>__round__</code> that is covariant in its return type.</p> </dd> +</dl> </section> <section id="abcs-for-working-with-io"> <h3>ABCs for working with IO</h3> <dl class="py class"> <dt class="sig sig-object py" id="typing.IO"> +<code>class typing.IO</code> </dt> <dt class="sig sig-object py" id="typing.TextIO"> +<code>class typing.TextIO</code> </dt> <dt class="sig sig-object py" id="typing.BinaryIO"> +<code>class typing.BinaryIO</code> </dt> <dd> +<p>Generic type <code>IO[AnyStr]</code> and its subclasses <code>TextIO(IO[str])</code> and <code>BinaryIO(IO[bytes])</code> represent the types of I/O streams such as returned by <a class="reference internal" href="functions#open" title="open"><code>open()</code></a>.</p> </dd> +</dl> </section> <section id="functions-and-decorators"> <h3>Functions and decorators</h3> <dl class="py function"> <dt class="sig sig-object py" id="typing.cast"> +<code>typing.cast(typ, val)</code> </dt> <dd> +<p>Cast a value to a type.</p> <p>This returns the value unchanged. To the type checker this signals that the return value has the designated type, but at runtime we intentionally don’t check anything (we want this to be as fast as possible).</p> </dd> +</dl> <dl class="py function"> <dt class="sig sig-object py" id="typing.assert_type"> +<code>typing.assert_type(val, typ, /)</code> </dt> <dd> +<p>Ask a static type checker to confirm that <em>val</em> has an inferred type of <em>typ</em>.</p> <p>At runtime this does nothing: it returns the first argument unchanged with no checks or side effects, no matter the actual type of the argument.</p> <p>When a static type checker encounters a call to <code>assert_type()</code>, it emits an error if the value is not of the specified type:</p> <pre data-language="python">def greet(name: str) -> None: + assert_type(name, str) # OK, inferred type of `name` is `str` + assert_type(name, int) # type checker error +</pre> <p>This function is useful for ensuring the type checker’s understanding of a script is in line with the developer’s intentions:</p> <pre data-language="python">def complex_function(arg: object): + # Do some complex type-narrowing logic, + # after which we hope the inferred type will be `int` + ... + # Test whether the type checker correctly understands our function + assert_type(arg, int) +</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd> +</dl> <dl class="py function"> <dt class="sig sig-object py" id="typing.assert_never"> +<code>typing.assert_never(arg, /)</code> </dt> <dd> +<p>Ask a static type checker to confirm that a line of code is unreachable.</p> <p>Example:</p> <pre data-language="python">def int_or_str(arg: int | str) -> None: + match arg: + case int(): + print("It's an int") + case str(): + print("It's a str") + case _ as unreachable: + assert_never(unreachable) +</pre> <p>Here, the annotations allow the type checker to infer that the last case can never execute, because <code>arg</code> is either an <a class="reference internal" href="functions#int" title="int"><code>int</code></a> or a <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a>, and both options are covered by earlier cases.</p> <p>If a type checker finds that a call to <code>assert_never()</code> is reachable, it will emit an error. For example, if the type annotation for <code>arg</code> was instead <code>int | str | float</code>, the type checker would emit an error pointing out that <code>unreachable</code> is of type <a class="reference internal" href="functions#float" title="float"><code>float</code></a>. For a call to <code>assert_never</code> to pass type checking, the inferred type of the argument passed in must be the bottom type, <a class="reference internal" href="#typing.Never" title="typing.Never"><code>Never</code></a>, and nothing else.</p> <p>At runtime, this throws an exception when called.</p> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p><a class="reference external" href="https://typing.readthedocs.io/en/latest/source/unreachable.html">Unreachable Code and Exhaustiveness Checking</a> has more information about exhaustiveness checking with static typing.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd> +</dl> <dl class="py function"> <dt class="sig sig-object py" id="typing.reveal_type"> +<code>typing.reveal_type(obj, /)</code> </dt> <dd> +<p>Ask a static type checker to reveal the inferred type of an expression.</p> <p>When a static type checker encounters a call to this function, it emits a diagnostic with the inferred type of the argument. For example:</p> <pre data-language="python">x: int = 1 +reveal_type(x) # Revealed type is "builtins.int" +</pre> <p>This can be useful when you want to debug how your type checker handles a particular piece of code.</p> <p>At runtime, this function prints the runtime type of its argument to <a class="reference internal" href="sys#sys.stderr" title="sys.stderr"><code>sys.stderr</code></a> and returns the argument unchanged (allowing the call to be used within an expression):</p> <pre data-language="python">x = reveal_type(1) # prints "Runtime type is int" +print(x) # prints "1" +</pre> <p>Note that the runtime type may be different from (more or less specific than) the type statically inferred by a type checker.</p> <p>Most type checkers support <code>reveal_type()</code> anywhere, even if the name is not imported from <code>typing</code>. Importing the name from <code>typing</code>, however, allows your code to run without runtime errors and communicates intent more clearly.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd> +</dl> <dl class="py function"> <dt class="sig sig-object py" id="typing.dataclass_transform"> +<code>@typing.dataclass_transform(*, eq_default=True, order_default=False, kw_only_default=False, frozen_default=False, field_specifiers=(), **kwargs)</code> </dt> <dd> +<p>Decorator to mark an object as providing <a class="reference internal" href="dataclasses#dataclasses.dataclass" title="dataclasses.dataclass"><code>dataclass</code></a>-like behavior.</p> <p><code>dataclass_transform</code> may be used to decorate a class, metaclass, or a function that is itself a decorator. The presence of <code>@dataclass_transform()</code> tells a static type checker that the decorated object performs runtime “magic” that transforms a class in a similar way to <a class="reference internal" href="dataclasses#dataclasses.dataclass" title="dataclasses.dataclass"><code>@dataclasses.dataclass</code></a>.</p> <p>Example usage with a decorator function:</p> <pre data-language="python">@dataclass_transform() +def create_model[T](cls: type[T]) -> type[T]: + ... + return cls + +@create_model +class CustomerModel: + id: int + name: str +</pre> <p>On a base class:</p> <pre data-language="python">@dataclass_transform() +class ModelBase: ... + +class CustomerModel(ModelBase): + id: int + name: str +</pre> <p>On a metaclass:</p> <pre data-language="python">@dataclass_transform() +class ModelMeta(type): ... + +class ModelBase(metaclass=ModelMeta): ... + +class CustomerModel(ModelBase): + id: int + name: str +</pre> <p>The <code>CustomerModel</code> classes defined above will be treated by type checkers similarly to classes created with <a class="reference internal" href="dataclasses#dataclasses.dataclass" title="dataclasses.dataclass"><code>@dataclasses.dataclass</code></a>. For example, type checkers will assume these classes have <code>__init__</code> methods that accept <code>id</code> and <code>name</code>.</p> <p>The decorated class, metaclass, or function may accept the following bool arguments which type checkers will assume have the same effect as they would have on the <a class="reference internal" href="dataclasses#dataclasses.dataclass" title="dataclasses.dataclass"><code>@dataclasses.dataclass</code></a> decorator: <code>init</code>, <code>eq</code>, <code>order</code>, <code>unsafe_hash</code>, <code>frozen</code>, <code>match_args</code>, <code>kw_only</code>, and <code>slots</code>. It must be possible for the value of these arguments (<code>True</code> or <code>False</code>) to be statically evaluated.</p> <p>The arguments to the <code>dataclass_transform</code> decorator can be used to customize the default behaviors of the decorated class, metaclass, or function:</p> <dl class="field-list simple"> <dt class="field-odd">Parameters</dt> <dd class="field-odd"> +<ul class="simple"> <li> +<strong>eq_default</strong> (<a class="reference internal" href="functions#bool" title="bool">bool</a>) – Indicates whether the <code>eq</code> parameter is assumed to be <code>True</code> or <code>False</code> if it is omitted by the caller. Defaults to <code>True</code>.</li> <li> +<strong>order_default</strong> (<a class="reference internal" href="functions#bool" title="bool">bool</a>) – Indicates whether the <code>order</code> parameter is assumed to be <code>True</code> or <code>False</code> if it is omitted by the caller. Defaults to <code>False</code>.</li> <li> +<strong>kw_only_default</strong> (<a class="reference internal" href="functions#bool" title="bool">bool</a>) – Indicates whether the <code>kw_only</code> parameter is assumed to be <code>True</code> or <code>False</code> if it is omitted by the caller. Defaults to <code>False</code>.</li> <li> +<p><strong>frozen_default</strong> (<a class="reference internal" href="functions#bool" title="bool">bool</a>) – </p> +<p>Indicates whether the <code>frozen</code> parameter is assumed to be <code>True</code> or <code>False</code> if it is omitted by the caller. Defaults to <code>False</code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> </li> <li> +<strong>field_specifiers</strong> (<a class="reference internal" href="stdtypes#tuple" title="tuple">tuple</a><em>[</em><a class="reference internal" href="collections.abc#collections.abc.Callable" title="collections.abc.Callable">Callable</a><em>[</em><em>...</em><em>, </em><em>Any</em><em>]</em><em>, </em><em>...</em><em>]</em>) – Specifies a static list of supported classes or functions that describe fields, similar to <a class="reference internal" href="dataclasses#dataclasses.field" title="dataclasses.field"><code>dataclasses.field()</code></a>. Defaults to <code>()</code>.</li> <li> +<strong>**kwargs</strong> (<em>Any</em>) – Arbitrary other keyword arguments are accepted in order to allow for possible future extensions.</li> </ul> </dd> </dl> <p>Type checkers recognize the following optional parameters on field specifiers:</p> <table class="colwidths-given docutils align-default" id="id7"> <caption><span class="caption-text"><strong>Recognised parameters for field specifiers</strong></span></caption> <thead> <tr> +<th class="head"><p>Parameter name</p></th> <th class="head"><p>Description</p></th> </tr> </thead> <tr> +<td><p><code>init</code></p></td> <td><p>Indicates whether the field should be included in the synthesized <code>__init__</code> method. If unspecified, <code>init</code> defaults to <code>True</code>.</p></td> </tr> <tr> +<td><p><code>default</code></p></td> <td><p>Provides the default value for the field.</p></td> </tr> <tr> +<td><p><code>default_factory</code></p></td> <td><p>Provides a runtime callback that returns the default value for the field. If neither <code>default</code> nor <code>default_factory</code> are specified, the field is assumed to have no default value and must be provided a value when the class is instantiated.</p></td> </tr> <tr> +<td><p><code>factory</code></p></td> <td><p>An alias for the <code>default_factory</code> parameter on field specifiers.</p></td> </tr> <tr> +<td><p><code>kw_only</code></p></td> <td><p>Indicates whether the field should be marked as keyword-only. If <code>True</code>, the field will be keyword-only. If <code>False</code>, it will not be keyword-only. If unspecified, the value of the <code>kw_only</code> parameter on the object decorated with <code>dataclass_transform</code> will be used, or if that is unspecified, the value of <code>kw_only_default</code> on <code>dataclass_transform</code> will be used.</p></td> </tr> <tr> +<td><p><code>alias</code></p></td> <td><p>Provides an alternative name for the field. This alternative name is used in the synthesized <code>__init__</code> method.</p></td> </tr> </table> <p>At runtime, this decorator records its arguments in the <code>__dataclass_transform__</code> attribute on the decorated object. It has no other runtime effect.</p> <p>See <span class="target" id="index-53"></span><a class="pep reference external" href="https://peps.python.org/pep-0681/"><strong>PEP 681</strong></a> for more details.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd> +</dl> <span class="target" id="overload"></span><dl class="py function"> <dt class="sig sig-object py" id="typing.overload"> +<code>@typing.overload</code> </dt> <dd> +<p>Decorator for creating overloaded functions and methods.</p> <p>The <code>@overload</code> decorator allows describing functions and methods that support multiple different combinations of argument types. A series of <code>@overload</code>-decorated definitions must be followed by exactly one non-<code>@overload</code>-decorated definition (for the same function/method).</p> <p><code>@overload</code>-decorated definitions are for the benefit of the type checker only, since they will be overwritten by the non-<code>@overload</code>-decorated definition. The non-<code>@overload</code>-decorated definition, meanwhile, will be used at runtime but should be ignored by a type checker. At runtime, calling an <code>@overload</code>-decorated function directly will raise <a class="reference internal" href="exceptions#NotImplementedError" title="NotImplementedError"><code>NotImplementedError</code></a>.</p> <p>An example of overload that gives a more precise type than can be expressed using a union or a type variable:</p> <pre data-language="python">@overload +def process(response: None) -> None: + ... +@overload +def process(response: int) -> tuple[int, str]: + ... +@overload +def process(response: bytes) -> str: + ... +def process(response): + ... # actual implementation goes here +</pre> <p>See <span class="target" id="index-54"></span><a class="pep reference external" href="https://peps.python.org/pep-0484/"><strong>PEP 484</strong></a> for more details and comparison with other typing semantics.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Overloaded functions can now be introspected at runtime using <a class="reference internal" href="#typing.get_overloads" title="typing.get_overloads"><code>get_overloads()</code></a>.</p> </div> </dd> +</dl> <dl class="py function"> <dt class="sig sig-object py" id="typing.get_overloads"> +<code>typing.get_overloads(func)</code> </dt> <dd> +<p>Return a sequence of <a class="reference internal" href="#typing.overload" title="typing.overload"><code>@overload</code></a>-decorated definitions for <em>func</em>.</p> <p><em>func</em> is the function object for the implementation of the overloaded function. For example, given the definition of <code>process</code> in the documentation for <a class="reference internal" href="#typing.overload" title="typing.overload"><code>@overload</code></a>, <code>get_overloads(process)</code> will return a sequence of three function objects for the three defined overloads. If called on a function with no overloads, <code>get_overloads()</code> returns an empty sequence.</p> <p><code>get_overloads()</code> can be used for introspecting an overloaded function at runtime.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd> +</dl> <dl class="py function"> <dt class="sig sig-object py" id="typing.clear_overloads"> +<code>typing.clear_overloads()</code> </dt> <dd> +<p>Clear all registered overloads in the internal registry.</p> <p>This can be used to reclaim the memory used by the registry.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd> +</dl> <dl class="py function"> <dt class="sig sig-object py" id="typing.final"> +<code>@typing.final</code> </dt> <dd> +<p>Decorator to indicate final methods and final classes.</p> <p>Decorating a method with <code>@final</code> indicates to a type checker that the method cannot be overridden in a subclass. Decorating a class with <code>@final</code> indicates that it cannot be subclassed.</p> <p>For example:</p> <pre data-language="python">class Base: + @final + def done(self) -> None: + ... +class Sub(Base): + def done(self) -> None: # Error reported by type checker + ... + +@final +class Leaf: + ... +class Other(Leaf): # Error reported by type checker + ... +</pre> <p>There is no runtime checking of these properties. See <span class="target" id="index-55"></span><a class="pep reference external" href="https://peps.python.org/pep-0591/"><strong>PEP 591</strong></a> for more details.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>The decorator will now attempt to set a <code>__final__</code> attribute to <code>True</code> on the decorated object. Thus, a check like <code>if getattr(obj, "__final__", False)</code> can be used at runtime to determine whether an object <code>obj</code> has been marked as final. If the decorated object does not support setting attributes, the decorator returns the object unchanged without raising an exception.</p> </div> </dd> +</dl> <dl class="py function"> <dt class="sig sig-object py" id="typing.no_type_check"> +<code>@typing.no_type_check</code> </dt> <dd> +<p>Decorator to indicate that annotations are not type hints.</p> <p>This works as a class or function <a class="reference internal" href="../glossary#term-decorator"><span class="xref std std-term">decorator</span></a>. With a class, it applies recursively to all methods and classes defined in that class (but not to methods defined in its superclasses or subclasses). Type checkers will ignore all annotations in a function or class with this decorator.</p> <p><code>@no_type_check</code> mutates the decorated object in place.</p> </dd> +</dl> <dl class="py function"> <dt class="sig sig-object py" id="typing.no_type_check_decorator"> +<code>@typing.no_type_check_decorator</code> </dt> <dd> +<p>Decorator to give another decorator the <a class="reference internal" href="#typing.no_type_check" title="typing.no_type_check"><code>no_type_check()</code></a> effect.</p> <p>This wraps the decorator with something that wraps the decorated function in <a class="reference internal" href="#typing.no_type_check" title="typing.no_type_check"><code>no_type_check()</code></a>.</p> </dd> +</dl> <dl class="py function"> <dt class="sig sig-object py" id="typing.override"> +<code>@typing.override</code> </dt> <dd> +<p>Decorator to indicate that a method in a subclass is intended to override a method or attribute in a superclass.</p> <p>Type checkers should emit an error if a method decorated with <code>@override</code> does not, in fact, override anything. This helps prevent bugs that may occur when a base class is changed without an equivalent change to a child class.</p> <p>For example:</p> <pre data-language="python">class Base: + def log_status(self) -> None: + ... + +class Sub(Base): + @override + def log_status(self) -> None: # Okay: overrides Base.log_status + ... + + @override + def done(self) -> None: # Error reported by type checker + ... +</pre> <p>There is no runtime checking of this property.</p> <p>The decorator will attempt to set an <code>__override__</code> attribute to <code>True</code> on the decorated object. Thus, a check like <code>if getattr(obj, "__override__", False)</code> can be used at runtime to determine whether an object <code>obj</code> has been marked as an override. If the decorated object does not support setting attributes, the decorator returns the object unchanged without raising an exception.</p> <p>See <span class="target" id="index-56"></span><a class="pep reference external" href="https://peps.python.org/pep-0698/"><strong>PEP 698</strong></a> for more details.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> </dd> +</dl> <dl class="py function"> <dt class="sig sig-object py" id="typing.type_check_only"> +<code>@typing.type_check_only</code> </dt> <dd> +<p>Decorator to mark a class or function as unavailable at runtime.</p> <p>This decorator is itself not available at runtime. It is mainly intended to mark classes that are defined in type stub files if an implementation returns an instance of a private class:</p> <pre data-language="python">@type_check_only +class Response: # private or not available at runtime + code: int + def get_header(self, name: str) -> str: ... + +def fetch_response() -> Response: ... +</pre> <p>Note that returning instances of private classes is not recommended. It is usually preferable to make such classes public.</p> </dd> +</dl> </section> <section id="introspection-helpers"> <h3>Introspection helpers</h3> <dl class="py function"> <dt class="sig sig-object py" id="typing.get_type_hints"> +<code>typing.get_type_hints(obj, globalns=None, localns=None, include_extras=False)</code> </dt> <dd> +<p>Return a dictionary containing type hints for a function, method, module or class object.</p> <p>This is often the same as <code>obj.__annotations__</code>. In addition, forward references encoded as string literals are handled by evaluating them in <code>globals</code> and <code>locals</code> namespaces. For a class <code>C</code>, return a dictionary constructed by merging all the <code>__annotations__</code> along <code>C.__mro__</code> in reverse order.</p> <p>The function recursively replaces all <code>Annotated[T, ...]</code> with <code>T</code>, unless <code>include_extras</code> is set to <code>True</code> (see <a class="reference internal" href="#typing.Annotated" title="typing.Annotated"><code>Annotated</code></a> for more information). For example:</p> <pre data-language="python">class Student(NamedTuple): + name: Annotated[str, 'some marker'] + +assert get_type_hints(Student) == {'name': str} +assert get_type_hints(Student, include_extras=False) == {'name': str} +assert get_type_hints(Student, include_extras=True) == { + 'name': Annotated[str, 'some marker'] +} +</pre> <div class="admonition note"> <p class="admonition-title">Note</p> <p><a class="reference internal" href="#typing.get_type_hints" title="typing.get_type_hints"><code>get_type_hints()</code></a> does not work with imported <a class="reference internal" href="#type-aliases"><span class="std std-ref">type aliases</span></a> that include forward references. Enabling postponed evaluation of annotations (<span class="target" id="index-57"></span><a class="pep reference external" href="https://peps.python.org/pep-0563/"><strong>PEP 563</strong></a>) may remove the need for most forward references.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9: </span>Added <code>include_extras</code> parameter as part of <span class="target" id="index-58"></span><a class="pep reference external" href="https://peps.python.org/pep-0593/"><strong>PEP 593</strong></a>. See the documentation on <a class="reference internal" href="#typing.Annotated" title="typing.Annotated"><code>Annotated</code></a> for more information.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Previously, <code>Optional[t]</code> was added for function and method annotations if a default value equal to <code>None</code> was set. Now the annotation is returned unchanged.</p> </div> </dd> +</dl> <dl class="py function"> <dt class="sig sig-object py" id="typing.get_origin"> +<code>typing.get_origin(tp)</code> </dt> <dd> +<p>Get the unsubscripted version of a type: for a typing object of the form <code>X[Y, Z, ...]</code> return <code>X</code>.</p> <p>If <code>X</code> is a typing-module alias for a builtin or <a class="reference internal" href="collections#module-collections" title="collections: Container datatypes"><code>collections</code></a> class, it will be normalized to the original class. If <code>X</code> is an instance of <a class="reference internal" href="#typing.ParamSpecArgs" title="typing.ParamSpecArgs"><code>ParamSpecArgs</code></a> or <a class="reference internal" href="#typing.ParamSpecKwargs" title="typing.ParamSpecKwargs"><code>ParamSpecKwargs</code></a>, return the underlying <a class="reference internal" href="#typing.ParamSpec" title="typing.ParamSpec"><code>ParamSpec</code></a>. Return <code>None</code> for unsupported objects.</p> <p>Examples:</p> <pre data-language="python">assert get_origin(str) is None +assert get_origin(Dict[str, int]) is dict +assert get_origin(Union[int, str]) is Union +P = ParamSpec('P') +assert get_origin(P.args) is P +assert get_origin(P.kwargs) is P +</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd> +</dl> <dl class="py function"> <dt class="sig sig-object py" id="typing.get_args"> +<code>typing.get_args(tp)</code> </dt> <dd> +<p>Get type arguments with all substitutions performed: for a typing object of the form <code>X[Y, Z, ...]</code> return <code>(Y, Z, ...)</code>.</p> <p>If <code>X</code> is a union or <a class="reference internal" href="#typing.Literal" title="typing.Literal"><code>Literal</code></a> contained in another generic type, the order of <code>(Y, Z, ...)</code> may be different from the order of the original arguments <code>[Y, Z, ...]</code> due to type caching. Return <code>()</code> for unsupported objects.</p> <p>Examples:</p> <pre data-language="python">assert get_args(int) == () +assert get_args(Dict[int, str]) == (int, str) +assert get_args(Union[int, str]) == (int, str) +</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd> +</dl> <dl class="py function"> <dt class="sig sig-object py" id="typing.is_typeddict"> +<code>typing.is_typeddict(tp)</code> </dt> <dd> +<p>Check if a type is a <a class="reference internal" href="#typing.TypedDict" title="typing.TypedDict"><code>TypedDict</code></a>.</p> <p>For example:</p> <pre data-language="python">class Film(TypedDict): + title: str + year: int + +assert is_typeddict(Film) +assert not is_typeddict(list | str) + +# TypedDict is a factory for creating typed dicts, +# not a typed dict itself +assert not is_typeddict(TypedDict) +</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.ForwardRef"> +<code>class typing.ForwardRef</code> </dt> <dd> +<p>Class used for internal typing representation of string forward references.</p> <p>For example, <code>List["SomeClass"]</code> is implicitly transformed into <code>List[ForwardRef("SomeClass")]</code>. <code>ForwardRef</code> should not be instantiated by a user, but may be used by introspection tools.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p><span class="target" id="index-59"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> generic types such as <code>list["SomeClass"]</code> will not be implicitly transformed into <code>list[ForwardRef("SomeClass")]</code> and thus will not automatically resolve to <code>list[SomeClass]</code>.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.4.</span></p> </div> </dd> +</dl> </section> <section id="constant"> <h3>Constant</h3> <dl class="py data"> <dt class="sig sig-object py" id="typing.TYPE_CHECKING"> +<code>typing.TYPE_CHECKING</code> </dt> <dd> +<p>A special constant that is assumed to be <code>True</code> by 3rd party static type checkers. It is <code>False</code> at runtime.</p> <p>Usage:</p> <pre data-language="python">if TYPE_CHECKING: + import expensive_mod + +def fun(arg: 'expensive_mod.SomeType') -> None: + local_var: expensive_mod.AnotherType = other_fun() +</pre> <p>The first type annotation must be enclosed in quotes, making it a “forward reference”, to hide the <code>expensive_mod</code> reference from the interpreter runtime. Type annotations for local variables are not evaluated, so the second annotation does not need to be enclosed in quotes.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>If <code>from __future__ import annotations</code> is used, annotations are not evaluated at function definition time. Instead, they are stored as strings in <code>__annotations__</code>. This makes it unnecessary to use quotes around the annotation (see <span class="target" id="index-60"></span><a class="pep reference external" href="https://peps.python.org/pep-0563/"><strong>PEP 563</strong></a>).</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.2.</span></p> </div> </dd> +</dl> </section> <section id="deprecated-aliases"> <span id="generic-concrete-collections"></span><span id="id6"></span><h3>Deprecated aliases</h3> <p>This module defines several deprecated aliases to pre-existing standard library classes. These were originally included in the typing module in order to support parameterizing these generic classes using <code>[]</code>. However, the aliases became redundant in Python 3.9 when the corresponding pre-existing classes were enhanced to support <code>[]</code> (see <span class="target" id="index-61"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a>).</p> <p>The redundant types are deprecated as of Python 3.9. However, while the aliases may be removed at some point, removal of these aliases is not currently planned. As such, no deprecation warnings are currently issued by the interpreter for these aliases.</p> <p>If at some point it is decided to remove these deprecated aliases, a deprecation warning will be issued by the interpreter for at least two releases prior to removal. The aliases are guaranteed to remain in the typing module without deprecation warnings until at least Python 3.14.</p> <p>Type checkers are encouraged to flag uses of the deprecated types if the program they are checking targets a minimum Python version of 3.9 or newer.</p> <section id="aliases-to-built-in-types"> <span id="corresponding-to-built-in-types"></span><h4>Aliases to built-in types</h4> <dl class="py class"> <dt class="sig sig-object py" id="typing.Dict"> +<code>class typing.Dict(dict, MutableMapping[KT, VT])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a>.</p> <p>Note that to annotate arguments, it is preferred to use an abstract collection type such as <a class="reference internal" href="#typing.Mapping" title="typing.Mapping"><code>Mapping</code></a> rather than to use <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> or <code>typing.Dict</code>.</p> <p>This type can be used as follows:</p> <pre data-language="python">def count_words(text: str) -> Dict[str, int]: + ... +</pre> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="stdtypes#dict" title="dict"><code>builtins.dict</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-62"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.List"> +<code>class typing.List(list, MutableSequence[T])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="stdtypes#list" title="list"><code>list</code></a>.</p> <p>Note that to annotate arguments, it is preferred to use an abstract collection type such as <a class="reference internal" href="#typing.Sequence" title="typing.Sequence"><code>Sequence</code></a> or <a class="reference internal" href="#typing.Iterable" title="typing.Iterable"><code>Iterable</code></a> rather than to use <a class="reference internal" href="stdtypes#list" title="list"><code>list</code></a> or <code>typing.List</code>.</p> <p>This type may be used as follows:</p> <pre data-language="python">def vec2[T: (int, float)](x: T, y: T) -> List[T]: + return [x, y] + +def keep_positives[T: (int, float)](vector: Sequence[T]) -> List[T]: + return [item for item in vector if item > 0] +</pre> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="stdtypes#list" title="list"><code>builtins.list</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-63"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.Set"> +<code>class typing.Set(set, MutableSet[T])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="stdtypes#set" title="set"><code>builtins.set</code></a>.</p> <p>Note that to annotate arguments, it is preferred to use an abstract collection type such as <a class="reference internal" href="#typing.AbstractSet" title="typing.AbstractSet"><code>AbstractSet</code></a> rather than to use <a class="reference internal" href="stdtypes#set" title="set"><code>set</code></a> or <code>typing.Set</code>.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="stdtypes#set" title="set"><code>builtins.set</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-64"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.FrozenSet"> +<code>class typing.FrozenSet(frozenset, AbstractSet[T_co])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="stdtypes#frozenset" title="frozenset"><code>builtins.frozenset</code></a>.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="stdtypes#frozenset" title="frozenset"><code>builtins.frozenset</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-65"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="typing.Tuple"> +<code>typing.Tuple</code> </dt> <dd> +<p>Deprecated alias for <a class="reference internal" href="stdtypes#tuple" title="tuple"><code>tuple</code></a>.</p> <p><a class="reference internal" href="stdtypes#tuple" title="tuple"><code>tuple</code></a> and <code>Tuple</code> are special-cased in the type system; see <a class="reference internal" href="#annotating-tuples"><span class="std std-ref">Annotating tuples</span></a> for more details.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="stdtypes#tuple" title="tuple"><code>builtins.tuple</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-66"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.Type"> +<code>class typing.Type(Generic[CT_co])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="functions#type" title="type"><code>type</code></a>.</p> <p>See <a class="reference internal" href="#type-of-class-objects"><span class="std std-ref">The type of class objects</span></a> for details on using <a class="reference internal" href="functions#type" title="type"><code>type</code></a> or <code>typing.Type</code> in type annotations.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.2.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="functions#type" title="type"><code>builtins.type</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-67"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> </section> <section id="aliases-to-types-in-collections"> <span id="corresponding-to-types-in-collections"></span><h4>Aliases to types in <a class="reference internal" href="collections#module-collections" title="collections: Container datatypes"><code>collections</code></a> +</h4> <dl class="py class"> <dt class="sig sig-object py" id="typing.DefaultDict"> +<code>class typing.DefaultDict(collections.defaultdict, MutableMapping[KT, VT])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="collections#collections.defaultdict" title="collections.defaultdict"><code>collections.defaultdict</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.2.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="collections#collections.defaultdict" title="collections.defaultdict"><code>collections.defaultdict</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-68"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.OrderedDict"> +<code>class typing.OrderedDict(collections.OrderedDict, MutableMapping[KT, VT])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="collections#collections.OrderedDict" title="collections.OrderedDict"><code>collections.OrderedDict</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.2.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="collections#collections.OrderedDict" title="collections.OrderedDict"><code>collections.OrderedDict</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-69"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.ChainMap"> +<code>class typing.ChainMap(collections.ChainMap, MutableMapping[KT, VT])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="collections#collections.ChainMap" title="collections.ChainMap"><code>collections.ChainMap</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.4.</span></p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.1.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="collections#collections.ChainMap" title="collections.ChainMap"><code>collections.ChainMap</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-70"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.Counter"> +<code>class typing.Counter(collections.Counter, Dict[T, int])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="collections#collections.Counter" title="collections.Counter"><code>collections.Counter</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.4.</span></p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.1.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="collections#collections.Counter" title="collections.Counter"><code>collections.Counter</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-71"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.Deque"> +<code>class typing.Deque(deque, MutableSequence[T])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="collections#collections.deque" title="collections.deque"><code>collections.deque</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.4.</span></p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.1.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="collections#collections.deque" title="collections.deque"><code>collections.deque</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-72"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> </section> <section id="aliases-to-other-concrete-types"> <span id="other-concrete-types"></span><h4>Aliases to other concrete types</h4> <div class="deprecated-removed"> <p><span class="versionmodified">Deprecated since version 3.8, will be removed in version 3.13: </span>The <code>typing.io</code> namespace is deprecated and will be removed. These types should be directly imported from <code>typing</code> instead.</p> </div> <dl class="py class"> <dt class="sig sig-object py" id="typing.Pattern"> +<code>class typing.Pattern</code> </dt> <dt class="sig sig-object py" id="typing.Match"> +<code>class typing.Match</code> </dt> <dd> +<p>Deprecated aliases corresponding to the return types from <a class="reference internal" href="re#re.compile" title="re.compile"><code>re.compile()</code></a> and <a class="reference internal" href="re#re.match" title="re.match"><code>re.match()</code></a>.</p> <p>These types (and the corresponding functions) are generic over <a class="reference internal" href="#typing.AnyStr" title="typing.AnyStr"><code>AnyStr</code></a>. <code>Pattern</code> can be specialised as <code>Pattern[str]</code> or <code>Pattern[bytes]</code>; <code>Match</code> can be specialised as <code>Match[str]</code> or <code>Match[bytes]</code>.</p> <div class="deprecated-removed"> <p><span class="versionmodified">Deprecated since version 3.8, will be removed in version 3.13: </span>The <code>typing.re</code> namespace is deprecated and will be removed. These types should be directly imported from <code>typing</code> instead.</p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span>Classes <code>Pattern</code> and <code>Match</code> from <a class="reference internal" href="re#module-re" title="re: Regular expression operations."><code>re</code></a> now support <code>[]</code>. See <span class="target" id="index-73"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.Text"> +<code>class typing.Text</code> </dt> <dd> +<p>Deprecated alias for <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a>.</p> <p><code>Text</code> is provided to supply a forward compatible path for Python 2 code: in Python 2, <code>Text</code> is an alias for <code>unicode</code>.</p> <p>Use <code>Text</code> to indicate that a value must contain a unicode string in a manner that is compatible with both Python 2 and Python 3:</p> <pre data-language="python">def add_unicode_checkmark(text: Text) -> Text: + return text + u' \u2713' +</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.2.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.11: </span>Python 2 is no longer supported, and most type checkers also no longer support type checking Python 2 code. Removal of the alias is not currently planned, but users are encouraged to use <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a> instead of <code>Text</code>.</p> </div> </dd> +</dl> </section> <section id="aliases-to-container-abcs-in-collections-abc"> <span id="corresponding-to-collections-in-collections-abc"></span><span id="abstract-base-classes"></span><h4>Aliases to container ABCs in <a class="reference internal" href="collections.abc#module-collections.abc" title="collections.abc: Abstract base classes for containers"><code>collections.abc</code></a> +</h4> <dl class="py class"> <dt class="sig sig-object py" id="typing.AbstractSet"> +<code>class typing.AbstractSet(Collection[T_co])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="collections.abc#collections.abc.Set" title="collections.abc.Set"><code>collections.abc.Set</code></a>.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="collections.abc#collections.abc.Set" title="collections.abc.Set"><code>collections.abc.Set</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-74"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.ByteString"> +<code>class typing.ByteString(Sequence[int])</code> </dt> <dd> +<p>This type represents the types <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a>, <a class="reference internal" href="stdtypes#bytearray" title="bytearray"><code>bytearray</code></a>, and <a class="reference internal" href="stdtypes#memoryview" title="memoryview"><code>memoryview</code></a> of byte sequences.</p> <div class="deprecated-removed"> <p><span class="versionmodified">Deprecated since version 3.9, will be removed in version 3.14: </span>Prefer <a class="reference internal" href="collections.abc#collections.abc.Buffer" title="collections.abc.Buffer"><code>collections.abc.Buffer</code></a>, or a union like <code>bytes | bytearray | memoryview</code>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.Collection"> +<code>class typing.Collection(Sized, Iterable[T_co], Container[T_co])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="collections.abc#collections.abc.Collection" title="collections.abc.Collection"><code>collections.abc.Collection</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.0.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="collections.abc#collections.abc.Collection" title="collections.abc.Collection"><code>collections.abc.Collection</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-75"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.Container"> +<code>class typing.Container(Generic[T_co])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="collections.abc#collections.abc.Container" title="collections.abc.Container"><code>collections.abc.Container</code></a>.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="collections.abc#collections.abc.Container" title="collections.abc.Container"><code>collections.abc.Container</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-76"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.ItemsView"> +<code>class typing.ItemsView(MappingView, AbstractSet[tuple[KT_co, VT_co]])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="collections.abc#collections.abc.ItemsView" title="collections.abc.ItemsView"><code>collections.abc.ItemsView</code></a>.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="collections.abc#collections.abc.ItemsView" title="collections.abc.ItemsView"><code>collections.abc.ItemsView</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-77"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.KeysView"> +<code>class typing.KeysView(MappingView, AbstractSet[KT_co])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="collections.abc#collections.abc.KeysView" title="collections.abc.KeysView"><code>collections.abc.KeysView</code></a>.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="collections.abc#collections.abc.KeysView" title="collections.abc.KeysView"><code>collections.abc.KeysView</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-78"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.Mapping"> +<code>class typing.Mapping(Collection[KT], Generic[KT, VT_co])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="collections.abc#collections.abc.Mapping" title="collections.abc.Mapping"><code>collections.abc.Mapping</code></a>.</p> <p>This type can be used as follows:</p> <pre data-language="python">def get_position_in_index(word_list: Mapping[str, int], word: str) -> int: + return word_list[word] +</pre> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="collections.abc#collections.abc.Mapping" title="collections.abc.Mapping"><code>collections.abc.Mapping</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-79"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.MappingView"> +<code>class typing.MappingView(Sized)</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="collections.abc#collections.abc.MappingView" title="collections.abc.MappingView"><code>collections.abc.MappingView</code></a>.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="collections.abc#collections.abc.MappingView" title="collections.abc.MappingView"><code>collections.abc.MappingView</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-80"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.MutableMapping"> +<code>class typing.MutableMapping(Mapping[KT, VT])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="collections.abc#collections.abc.MutableMapping" title="collections.abc.MutableMapping"><code>collections.abc.MutableMapping</code></a>.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="collections.abc#collections.abc.MutableMapping" title="collections.abc.MutableMapping"><code>collections.abc.MutableMapping</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-81"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.MutableSequence"> +<code>class typing.MutableSequence(Sequence[T])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="collections.abc#collections.abc.MutableSequence" title="collections.abc.MutableSequence"><code>collections.abc.MutableSequence</code></a>.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="collections.abc#collections.abc.MutableSequence" title="collections.abc.MutableSequence"><code>collections.abc.MutableSequence</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-82"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.MutableSet"> +<code>class typing.MutableSet(AbstractSet[T])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="collections.abc#collections.abc.MutableSet" title="collections.abc.MutableSet"><code>collections.abc.MutableSet</code></a>.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="collections.abc#collections.abc.MutableSet" title="collections.abc.MutableSet"><code>collections.abc.MutableSet</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-83"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.Sequence"> +<code>class typing.Sequence(Reversible[T_co], Collection[T_co])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="collections.abc#collections.abc.Sequence" title="collections.abc.Sequence"><code>collections.abc.Sequence</code></a>.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="collections.abc#collections.abc.Sequence" title="collections.abc.Sequence"><code>collections.abc.Sequence</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-84"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.ValuesView"> +<code>class typing.ValuesView(MappingView, Collection[_VT_co])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="collections.abc#collections.abc.ValuesView" title="collections.abc.ValuesView"><code>collections.abc.ValuesView</code></a>.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="collections.abc#collections.abc.ValuesView" title="collections.abc.ValuesView"><code>collections.abc.ValuesView</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-85"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> </section> <section id="aliases-to-asynchronous-abcs-in-collections-abc"> <span id="asynchronous-programming"></span><h4>Aliases to asynchronous ABCs in <a class="reference internal" href="collections.abc#module-collections.abc" title="collections.abc: Abstract base classes for containers"><code>collections.abc</code></a> +</h4> <dl class="py class"> <dt class="sig sig-object py" id="typing.Coroutine"> +<code>class typing.Coroutine(Awaitable[ReturnType], Generic[YieldType, SendType, ReturnType])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="collections.abc#collections.abc.Coroutine" title="collections.abc.Coroutine"><code>collections.abc.Coroutine</code></a>.</p> <p>The variance and order of type variables correspond to those of <a class="reference internal" href="#typing.Generator" title="typing.Generator"><code>Generator</code></a>, for example:</p> <pre data-language="python">from collections.abc import Coroutine +c: Coroutine[list[str], str, int] # Some coroutine defined elsewhere +x = c.send('hi') # Inferred type of 'x' is list[str] +async def bar() -> None: + y = await c # Inferred type of 'y' is int +</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.3.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="collections.abc#collections.abc.Coroutine" title="collections.abc.Coroutine"><code>collections.abc.Coroutine</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-86"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.AsyncGenerator"> +<code>class typing.AsyncGenerator(AsyncIterator[YieldType], Generic[YieldType, SendType])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="collections.abc#collections.abc.AsyncGenerator" title="collections.abc.AsyncGenerator"><code>collections.abc.AsyncGenerator</code></a>.</p> <p>An async generator can be annotated by the generic type <code>AsyncGenerator[YieldType, SendType]</code>. For example:</p> <pre data-language="python">async def echo_round() -> AsyncGenerator[int, float]: + sent = yield 0 + while sent >= 0.0: + rounded = await round(sent) + sent = yield rounded +</pre> <p>Unlike normal generators, async generators cannot return a value, so there is no <code>ReturnType</code> type parameter. As with <a class="reference internal" href="#typing.Generator" title="typing.Generator"><code>Generator</code></a>, the <code>SendType</code> behaves contravariantly.</p> <p>If your generator will only yield values, set the <code>SendType</code> to <code>None</code>:</p> <pre data-language="python">async def infinite_stream(start: int) -> AsyncGenerator[int, None]: + while True: + yield start + start = await increment(start) +</pre> <p>Alternatively, annotate your generator as having a return type of either <code>AsyncIterable[YieldType]</code> or <code>AsyncIterator[YieldType]</code>:</p> <pre data-language="python">async def infinite_stream(start: int) -> AsyncIterator[int]: + while True: + yield start + start = await increment(start) +</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.1.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="collections.abc#collections.abc.AsyncGenerator" title="collections.abc.AsyncGenerator"><code>collections.abc.AsyncGenerator</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-87"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.AsyncIterable"> +<code>class typing.AsyncIterable(Generic[T_co])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="collections.abc#collections.abc.AsyncIterable" title="collections.abc.AsyncIterable"><code>collections.abc.AsyncIterable</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.2.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="collections.abc#collections.abc.AsyncIterable" title="collections.abc.AsyncIterable"><code>collections.abc.AsyncIterable</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-88"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.AsyncIterator"> +<code>class typing.AsyncIterator(AsyncIterable[T_co])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="collections.abc#collections.abc.AsyncIterator" title="collections.abc.AsyncIterator"><code>collections.abc.AsyncIterator</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.2.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="collections.abc#collections.abc.AsyncIterator" title="collections.abc.AsyncIterator"><code>collections.abc.AsyncIterator</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-89"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.Awaitable"> +<code>class typing.Awaitable(Generic[T_co])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="collections.abc#collections.abc.Awaitable" title="collections.abc.Awaitable"><code>collections.abc.Awaitable</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.2.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="collections.abc#collections.abc.Awaitable" title="collections.abc.Awaitable"><code>collections.abc.Awaitable</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-90"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> </section> <section id="aliases-to-other-abcs-in-collections-abc"> <span id="corresponding-to-other-types-in-collections-abc"></span><h4>Aliases to other ABCs in <a class="reference internal" href="collections.abc#module-collections.abc" title="collections.abc: Abstract base classes for containers"><code>collections.abc</code></a> +</h4> <dl class="py class"> <dt class="sig sig-object py" id="typing.Iterable"> +<code>class typing.Iterable(Generic[T_co])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="collections.abc#collections.abc.Iterable" title="collections.abc.Iterable"><code>collections.abc.Iterable</code></a>.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="collections.abc#collections.abc.Iterable" title="collections.abc.Iterable"><code>collections.abc.Iterable</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-91"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.Iterator"> +<code>class typing.Iterator(Iterable[T_co])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="collections.abc#collections.abc.Iterator" title="collections.abc.Iterator"><code>collections.abc.Iterator</code></a>.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="collections.abc#collections.abc.Iterator" title="collections.abc.Iterator"><code>collections.abc.Iterator</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-92"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="typing.Callable"> +<code>typing.Callable</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="collections.abc#collections.abc.Callable" title="collections.abc.Callable"><code>collections.abc.Callable</code></a>.</p> <p>See <a class="reference internal" href="#annotating-callables"><span class="std std-ref">Annotating callable objects</span></a> for details on how to use <a class="reference internal" href="collections.abc#collections.abc.Callable" title="collections.abc.Callable"><code>collections.abc.Callable</code></a> and <code>typing.Callable</code> in type annotations.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="collections.abc#collections.abc.Callable" title="collections.abc.Callable"><code>collections.abc.Callable</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-93"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span><code>Callable</code> now supports <a class="reference internal" href="#typing.ParamSpec" title="typing.ParamSpec"><code>ParamSpec</code></a> and <a class="reference internal" href="#typing.Concatenate" title="typing.Concatenate"><code>Concatenate</code></a>. See <span class="target" id="index-94"></span><a class="pep reference external" href="https://peps.python.org/pep-0612/"><strong>PEP 612</strong></a> for more details.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.Generator"> +<code>class typing.Generator(Iterator[YieldType], Generic[YieldType, SendType, ReturnType])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="collections.abc#collections.abc.Generator" title="collections.abc.Generator"><code>collections.abc.Generator</code></a>.</p> <p>A generator can be annotated by the generic type <code>Generator[YieldType, SendType, ReturnType]</code>. For example:</p> <pre data-language="python">def echo_round() -> Generator[int, float, str]: + sent = yield 0 + while sent >= 0: + sent = yield round(sent) + return 'Done' +</pre> <p>Note that unlike many other generics in the typing module, the <code>SendType</code> of <a class="reference internal" href="#typing.Generator" title="typing.Generator"><code>Generator</code></a> behaves contravariantly, not covariantly or invariantly.</p> <p>If your generator will only yield values, set the <code>SendType</code> and <code>ReturnType</code> to <code>None</code>:</p> <pre data-language="python">def infinite_stream(start: int) -> Generator[int, None, None]: + while True: + yield start + start += 1 +</pre> <p>Alternatively, annotate your generator as having a return type of either <code>Iterable[YieldType]</code> or <code>Iterator[YieldType]</code>:</p> <pre data-language="python">def infinite_stream(start: int) -> Iterator[int]: + while True: + yield start + start += 1 +</pre> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="collections.abc#collections.abc.Generator" title="collections.abc.Generator"><code>collections.abc.Generator</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-95"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.Hashable"> +<code>class typing.Hashable</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="collections.abc#collections.abc.Hashable" title="collections.abc.Hashable"><code>collections.abc.Hashable</code></a>.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.12: </span>Use <a class="reference internal" href="collections.abc#collections.abc.Hashable" title="collections.abc.Hashable"><code>collections.abc.Hashable</code></a> directly instead.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.Reversible"> +<code>class typing.Reversible(Iterable[T_co])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="collections.abc#collections.abc.Reversible" title="collections.abc.Reversible"><code>collections.abc.Reversible</code></a>.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="collections.abc#collections.abc.Reversible" title="collections.abc.Reversible"><code>collections.abc.Reversible</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-96"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.Sized"> +<code>class typing.Sized</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="collections.abc#collections.abc.Sized" title="collections.abc.Sized"><code>collections.abc.Sized</code></a>.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.12: </span>Use <a class="reference internal" href="collections.abc#collections.abc.Sized" title="collections.abc.Sized"><code>collections.abc.Sized</code></a> directly instead.</p> </div> </dd> +</dl> </section> <section id="aliases-to-contextlib-abcs"> <span id="context-manager-types"></span><h4>Aliases to <a class="reference internal" href="contextlib#module-contextlib" title="contextlib: Utilities for with-statement contexts."><code>contextlib</code></a> ABCs</h4> <dl class="py class"> <dt class="sig sig-object py" id="typing.ContextManager"> +<code>class typing.ContextManager(Generic[T_co])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="contextlib#contextlib.AbstractContextManager" title="contextlib.AbstractContextManager"><code>contextlib.AbstractContextManager</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.4.</span></p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.0.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="contextlib#contextlib.AbstractContextManager" title="contextlib.AbstractContextManager"><code>contextlib.AbstractContextManager</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-97"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="typing.AsyncContextManager"> +<code>class typing.AsyncContextManager(Generic[T_co])</code> </dt> <dd> +<p>Deprecated alias to <a class="reference internal" href="contextlib#contextlib.AbstractAsyncContextManager" title="contextlib.AbstractAsyncContextManager"><code>contextlib.AbstractAsyncContextManager</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.4.</span></p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.2.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span><a class="reference internal" href="contextlib#contextlib.AbstractAsyncContextManager" title="contextlib.AbstractAsyncContextManager"><code>contextlib.AbstractAsyncContextManager</code></a> now supports subscripting (<code>[]</code>). See <span class="target" id="index-98"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a class="reference internal" href="stdtypes#types-genericalias"><span class="std std-ref">Generic Alias Type</span></a>.</p> </div> </dd> +</dl> </section> </section> </section> <section id="deprecation-timeline-of-major-features"> <h2>Deprecation Timeline of Major Features</h2> <p>Certain features in <code>typing</code> are deprecated and may be removed in a future version of Python. The following table summarizes major deprecations for your convenience. This is subject to change, and not all deprecations are listed.</p> <table class="docutils align-default"> <thead> <tr> +<th class="head"><p>Feature</p></th> <th class="head"><p>Deprecated in</p></th> <th class="head"><p>Projected removal</p></th> <th class="head"><p>PEP/issue</p></th> </tr> </thead> <tr> +<td><p><code>typing.io</code> and <code>typing.re</code> submodules</p></td> <td><p>3.8</p></td> <td><p>3.13</p></td> <td><p><a class="reference external" href="https://bugs.python.org/issue?@action=redirect&bpo=38291">bpo-38291</a></p></td> </tr> <tr> +<td><p><code>typing</code> versions of standard collections</p></td> <td><p>3.9</p></td> <td><p>Undecided (see <a class="reference internal" href="#deprecated-aliases"><span class="std std-ref">Deprecated aliases</span></a> for more information)</p></td> <td><p><span class="target" id="index-99"></span><a class="pep reference external" href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a></p></td> </tr> <tr> +<td><p><a class="reference internal" href="#typing.ByteString" title="typing.ByteString"><code>typing.ByteString</code></a></p></td> <td><p>3.9</p></td> <td><p>3.14</p></td> <td><p><a class="reference external" href="https://github.com/python/cpython/issues/91896">gh-91896</a></p></td> </tr> <tr> +<td><p><a class="reference internal" href="#typing.Text" title="typing.Text"><code>typing.Text</code></a></p></td> <td><p>3.11</p></td> <td><p>Undecided</p></td> <td><p><a class="reference external" href="https://github.com/python/cpython/issues/92332">gh-92332</a></p></td> </tr> <tr> +<td><p><a class="reference internal" href="#typing.Hashable" title="typing.Hashable"><code>typing.Hashable</code></a> and <a class="reference internal" href="#typing.Sized" title="typing.Sized"><code>typing.Sized</code></a></p></td> <td><p>3.12</p></td> <td><p>Undecided</p></td> <td><p><a class="reference external" href="https://github.com/python/cpython/issues/94309">gh-94309</a></p></td> </tr> <tr> +<td><p><a class="reference internal" href="#typing.TypeAlias" title="typing.TypeAlias"><code>typing.TypeAlias</code></a></p></td> <td><p>3.12</p></td> <td><p>Undecided</p></td> <td><p><span class="target" id="index-100"></span><a class="pep reference external" href="https://peps.python.org/pep-0695/"><strong>PEP 695</strong></a></p></td> </tr> </table> </section> <div class="_attribution"> + <p class="_attribution-p"> + © 2001–2023 Python Software Foundation<br>Licensed under the PSF License.<br> + <a href="https://docs.python.org/3.12/library/typing.html" class="_attribution-link">https://docs.python.org/3.12/library/typing.html</a> + </p> +</div> |
