| 1 |
========================================= |
| 2 |
:mod:`!typing` --- Support for type hints |
| 3 |
========================================= |
| 4 |
|
| 5 |
.. testsetup:: * |
| 6 |
|
| 7 |
import typing |
| 8 |
from dataclasses import dataclass |
| 9 |
from typing import * |
| 10 |
|
| 11 |
.. module:: typing |
| 12 |
:synopsis: Support for type hints (see :pep:`484`). |
| 13 |
|
| 14 |
.. versionadded:: 3.5 |
| 15 |
|
| 16 |
**Source code:** :source:`Lib/typing.py` |
| 17 |
|
| 18 |
.. note:: |
| 19 |
|
| 20 |
The Python runtime does not enforce function and variable type annotations. |
| 21 |
They can be used by third party tools such as :term:`type checkers <static type checker>`, |
| 22 |
IDEs, linters, etc. |
| 23 |
|
| 24 |
-------------- |
| 25 |
|
| 26 |
This module provides runtime support for type hints. |
| 27 |
|
| 28 |
Consider the function below:: |
| 29 |
|
| 30 |
def surface_area_of_cube(edge_length: float) -> str: |
| 31 |
return f"The surface area of the cube is {6 * edge_length ** 2}." |
| 32 |
|
| 33 |
The function ``surface_area_of_cube`` takes an argument expected to |
| 34 |
be an instance of :class:`float`, as indicated by the :term:`type hint` |
| 35 |
``edge_length: float``. The function is expected to return an instance |
| 36 |
of :class:`str`, as indicated by the ``-> str`` hint. |
| 37 |
|
| 38 |
While type hints can be simple classes like :class:`float` or :class:`str`, |
| 39 |
they can also be more complex. The :mod:`typing` module provides a vocabulary of |
| 40 |
more advanced type hints. |
| 41 |
|
| 42 |
New features are frequently added to the ``typing`` module. |
| 43 |
The :pypi:`typing_extensions` package |
| 44 |
provides backports of these new features to older versions of Python. |
| 45 |
|
| 46 |
.. seealso:: |
| 47 |
|
| 48 |
`Typing cheat sheet <https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html>`_ |
| 49 |
A quick overview of type hints (hosted at the mypy docs) |
| 50 |
|
| 51 |
Type System Reference section of `the mypy docs <https://mypy.readthedocs.io/en/stable/index.html>`_ |
| 52 |
The Python typing system is standardised via PEPs, so this reference |
| 53 |
should broadly apply to most Python type checkers. (Some parts may still |
| 54 |
be specific to mypy.) |
| 55 |
|
| 56 |
`Static Typing with Python <https://typing.python.org/en/latest/>`_ |
| 57 |
Type-checker-agnostic documentation written by the community detailing |
| 58 |
type system features, useful typing related tools and typing best |
| 59 |
practices. |
| 60 |
|
| 61 |
.. _relevant-peps: |
| 62 |
|
| 63 |
Specification for the Python Type System |
| 64 |
======================================== |
| 65 |
|
| 66 |
The canonical, up-to-date specification of the Python type system can be |
| 67 |
found at `Specification for the Python type system <https://typing.python.org/en/latest/spec/index.html>`_. |
| 68 |
|
| 69 |
.. _type-aliases: |
| 70 |
|
| 71 |
Type aliases |
| 72 |
============ |
| 73 |
|
| 74 |
A type alias is defined using the :keyword:`type` statement, which creates |
| 75 |
an instance of :class:`TypeAliasType`. In this example, |
| 76 |
``Vector`` and ``list[float]`` will be treated equivalently by static type |
| 77 |
checkers:: |
| 78 |
|
| 79 |
type Vector = list[float] |
| 80 |
|
| 81 |
def scale(scalar: float, vector: Vector) -> Vector: |
| 82 |
return [scalar * num for num in vector] |
| 83 |
|
| 84 |
# passes type checking; a list of floats qualifies as a Vector. |
| 85 |
new_vector = scale(2.0, [1.0, -4.2, 5.4]) |
| 86 |
|
| 87 |
Type aliases are useful for simplifying complex type signatures. For example:: |
| 88 |
|
| 89 |
from collections.abc import Sequence |
| 90 |
|
| 91 |
type ConnectionOptions = dict[str, str] |
| 92 |
type Address = tuple[str, int] |
| 93 |
type Server = tuple[Address, ConnectionOptions] |
| 94 |
|
| 95 |
def broadcast_message(message: str, servers: Sequence[Server]) -> None: |
| 96 |
... |
| 97 |
|
| 98 |
# The static type checker will treat the previous type signature as |
| 99 |
# being exactly equivalent to this one. |
| 100 |
def broadcast_message( |
| 101 |
message: str, |
| 102 |
servers: Sequence[tuple[tuple[str, int], dict[str, str]]] |
| 103 |
) -> None: |
| 104 |
... |
| 105 |
|
| 106 |
The :keyword:`type` statement is new in Python 3.12. For backwards |
| 107 |
compatibility, type aliases can also be created through simple assignment:: |
| 108 |
|
| 109 |
Vector = list[float] |
| 110 |
|
| 111 |
Or marked with :data:`TypeAlias` to make it explicit that this is a type alias, |
| 112 |
not a normal variable assignment:: |
| 113 |
|
| 114 |
from typing import TypeAlias |
| 115 |
|
| 116 |
Vector: TypeAlias = list[float] |
| 117 |
|
| 118 |
.. _distinct: |
| 119 |
|
| 120 |
NewType |
| 121 |
======= |
| 122 |
|
| 123 |
Use the :class:`NewType` helper to create distinct types:: |
| 124 |
|
| 125 |
from typing import NewType |
| 126 |
|
| 127 |
UserId = NewType('UserId', int) |
| 128 |
some_id = UserId(524313) |
| 129 |
|
| 130 |
The static type checker will treat the new type as if it were a subclass |
| 131 |
of the original type. This is useful in helping catch logical errors:: |
| 132 |
|
| 133 |
def get_user_name(user_id: UserId) -> str: |
| 134 |
... |
| 135 |
|
| 136 |
# passes type checking |
| 137 |
user_a = get_user_name(UserId(42351)) |
| 138 |
|
| 139 |
# fails type checking; an int is not a UserId |
| 140 |
user_b = get_user_name(-1) |
| 141 |
|
| 142 |
You may still perform all ``int`` operations on a variable of type ``UserId``, |
| 143 |
but the result will always be of type ``int``. This lets you pass in a |
| 144 |
``UserId`` wherever an ``int`` might be expected, but will prevent you from |
| 145 |
accidentally creating a ``UserId`` in an invalid way:: |
| 146 |
|
| 147 |
# 'output' is of type 'int', not 'UserId' |
| 148 |
output = UserId(23413) + UserId(54341) |
| 149 |
|
| 150 |
Note that these checks are enforced only by the static type checker. At runtime, |
| 151 |
the statement ``Derived = NewType('Derived', Base)`` will make ``Derived`` a |
| 152 |
callable that immediately returns whatever parameter you pass it. That means |
| 153 |
the expression ``Derived(some_value)`` does not create a new class or introduce |
| 154 |
much overhead beyond that of a regular function call. |
| 155 |
|
| 156 |
More precisely, the expression ``some_value is Derived(some_value)`` is always |
| 157 |
true at runtime. |
| 158 |
|
| 159 |
It is invalid to create a subtype of ``Derived``:: |
| 160 |
|
| 161 |
from typing import NewType |
| 162 |
|
| 163 |
UserId = NewType('UserId', int) |
| 164 |
|
| 165 |
# Fails at runtime and does not pass type checking |
| 166 |
class AdminUserId(UserId): pass |
| 167 |
|
| 168 |
However, it is possible to create a :class:`NewType` based on a 'derived' ``NewType``:: |
| 169 |
|
| 170 |
from typing import NewType |
| 171 |
|
| 172 |
UserId = NewType('UserId', int) |
| 173 |
|
| 174 |
ProUserId = NewType('ProUserId', UserId) |
| 175 |
|
| 176 |
and typechecking for ``ProUserId`` will work as expected. |
| 177 |
|
| 178 |
See :pep:`484` for more details. |
| 179 |
|
| 180 |
.. note:: |
| 181 |
|
| 182 |
Recall that the use of a type alias declares two types to be *equivalent* to |
| 183 |
one another. Doing ``type Alias = Original`` will make the static type checker |
| 184 |
treat ``Alias`` as being *exactly equivalent* to ``Original`` in all cases. |
| 185 |
This is useful when you want to simplify complex type signatures. |
| 186 |
|
| 187 |
In contrast, ``NewType`` declares one type to be a *subtype* of another. |
| 188 |
Doing ``Derived = NewType('Derived', Original)`` will make the static type |
| 189 |
checker treat ``Derived`` as a *subclass* of ``Original``, which means a |
| 190 |
value of type ``Original`` cannot be used in places where a value of type |
| 191 |
``Derived`` is expected. This is useful when you want to prevent logic |
| 192 |
errors with minimal runtime cost. |
| 193 |
|
| 194 |
.. versionadded:: 3.5.2 |
| 195 |
|
| 196 |
.. versionchanged:: 3.10 |
| 197 |
``NewType`` is now a class rather than a function. As a result, there is |
| 198 |
some additional runtime cost when calling ``NewType`` over a regular |
| 199 |
function. |
| 200 |
|
| 201 |
.. versionchanged:: 3.11 |
| 202 |
The performance of calling ``NewType`` has been restored to its level in |
| 203 |
Python 3.9. |
| 204 |
|
| 205 |
.. _annotating-callables: |
| 206 |
|
| 207 |
Annotating callable objects |
| 208 |
=========================== |
| 209 |
|
| 210 |
Functions -- or other :term:`callable` objects -- can be annotated using |
| 211 |
:class:`collections.abc.Callable` or deprecated :data:`typing.Callable`. |
| 212 |
``Callable[[int], str]`` signifies a function that takes a single parameter |
| 213 |
of type :class:`int` and returns a :class:`str`. |
| 214 |
|
| 215 |
For example: |
| 216 |
|
| 217 |
.. testcode:: |
| 218 |
|
| 219 |
from collections.abc import Callable, Awaitable |
| 220 |
|
| 221 |
def feeder(get_next_item: Callable[[], str]) -> None: |
| 222 |
... # Body |
| 223 |
|
| 224 |
def async_query(on_success: Callable[[int], None], |
| 225 |
on_error: Callable[[int, Exception], None]) -> None: |
| 226 |
... # Body |
| 227 |
|
| 228 |
async def on_update(value: str) -> None: |
| 229 |
... # Body |
| 230 |
|
| 231 |
callback: Callable[[str], Awaitable[None]] = on_update |
| 232 |
|
| 233 |
.. index:: single: ...; ellipsis literal |
| 234 |
|
| 235 |
The subscription syntax must always be used with exactly two values: the |
| 236 |
argument list and the return type. The argument list must be a list of types, |
| 237 |
a :class:`ParamSpec`, :data:`Concatenate`, or an ellipsis (``...``). The return type must |
| 238 |
be a single type. |
| 239 |
|
| 240 |
If a literal ellipsis ``...`` is given as the argument list, it indicates that |
| 241 |
a callable with any arbitrary parameter list would be acceptable: |
| 242 |
|
| 243 |
.. testcode:: |
| 244 |
|
| 245 |
def concat(x: str, y: str) -> str: |
| 246 |
return x + y |
| 247 |
|
| 248 |
x: Callable[..., str] |
| 249 |
x = str # OK |
| 250 |
x = concat # Also OK |
| 251 |
|
| 252 |
``Callable`` cannot express complex signatures such as functions that take a |
| 253 |
variadic number of arguments, :ref:`overloaded functions <overload>`, or |
| 254 |
functions that have keyword-only parameters. However, these signatures can be |
| 255 |
expressed by defining a :class:`Protocol` class with a |
| 256 |
:meth:`~object.__call__` method: |
| 257 |
|
| 258 |
.. testcode:: |
| 259 |
|
| 260 |
from collections.abc import Iterable |
| 261 |
from typing import Protocol |
| 262 |
|
| 263 |
class Combiner(Protocol): |
| 264 |
def __call__(self, *vals: bytes, maxlen: int | None = None) -> list[bytes]: ... |
| 265 |
|
| 266 |
def batch_proc(data: Iterable[bytes], cb_results: Combiner) -> bytes: |
| 267 |
for item in data: |
| 268 |
... |
| 269 |
|
| 270 |
def good_cb(*vals: bytes, maxlen: int | None = None) -> list[bytes]: |
| 271 |
... |
| 272 |
def bad_cb(*vals: bytes, maxitems: int | None) -> list[bytes]: |
| 273 |
... |
| 274 |
|
| 275 |
batch_proc([], good_cb) # OK |
| 276 |
batch_proc([], bad_cb) # Error! Argument 2 has incompatible type because of |
| 277 |
# different name and kind in the callback |
| 278 |
|
| 279 |
Callables which take other callables as arguments may indicate that their |
| 280 |
parameter types are dependent on each other using :class:`ParamSpec`. |
| 281 |
Additionally, if that callable adds or removes arguments from other |
| 282 |
callables, the :data:`Concatenate` operator may be used. They |
| 283 |
take the form ``Callable[ParamSpecVariable, ReturnType]`` and |
| 284 |
``Callable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], ReturnType]`` |
| 285 |
respectively. |
| 286 |
|
| 287 |
.. versionchanged:: 3.10 |
| 288 |
``Callable`` now supports :class:`ParamSpec` and :data:`Concatenate`. |
| 289 |
See :pep:`612` for more details. |
| 290 |
|
| 291 |
.. seealso:: |
| 292 |
The documentation for :class:`ParamSpec` and :class:`Concatenate` provides |
| 293 |
examples of usage in ``Callable``. |
| 294 |
|
| 295 |
.. _generics: |
| 296 |
|
| 297 |
Generics |
| 298 |
======== |
| 299 |
|
| 300 |
Since type information about objects kept in containers cannot be statically |
| 301 |
inferred in a generic way, many container classes in the standard library support |
| 302 |
subscription to denote the expected types of container elements. |
| 303 |
|
| 304 |
.. testcode:: |
| 305 |
|
| 306 |
from collections.abc import Mapping, Sequence |
| 307 |
|
| 308 |
class Employee: ... |
| 309 |
|
| 310 |
# Sequence[Employee] indicates that all elements in the sequence |
| 311 |
# must be instances of "Employee". |
| 312 |
# Mapping[str, str] indicates that all keys and all values in the mapping |
| 313 |
# must be strings. |
| 314 |
def notify_by_email(employees: Sequence[Employee], |
| 315 |
overrides: Mapping[str, str]) -> None: ... |
| 316 |
|
| 317 |
Generic functions and classes can be parameterized by using |
| 318 |
:ref:`type parameter syntax <type-params>`:: |
| 319 |
|
| 320 |
from collections.abc import Sequence |
| 321 |
|
| 322 |
def first[T](l: Sequence[T]) -> T: # Function is generic over the TypeVar "T" |
| 323 |
return l[0] |
| 324 |
|
| 325 |
Or by using the :class:`TypeVar` factory directly:: |
| 326 |
|
| 327 |
from collections.abc import Sequence |
| 328 |
from typing import TypeVar |
| 329 |
|
| 330 |
U = TypeVar('U') # Declare type variable "U" |
| 331 |
|
| 332 |
def second(l: Sequence[U]) -> U: # Function is generic over the TypeVar "U" |
| 333 |
return l[1] |
| 334 |
|
| 335 |
.. versionchanged:: 3.12 |
| 336 |
Syntactic support for generics is new in Python 3.12. |
| 337 |
|
| 338 |
.. _annotating-tuples: |
| 339 |
|
| 340 |
Annotating tuples |
| 341 |
================= |
| 342 |
|
| 343 |
For most containers in Python, the typing system assumes that all elements in |
| 344 |
the container will be of the same type. For example:: |
| 345 |
|
| 346 |
from collections.abc import Mapping |
| 347 |
|
| 348 |
# Type checker will infer that all elements in ``x`` are meant to be ints |
| 349 |
x: list[int] = [] |
| 350 |
|
| 351 |
# Type checker error: ``list`` only accepts a single type argument: |
| 352 |
y: list[int, str] = [1, 'foo'] |
| 353 |
|
| 354 |
# Type checker will infer that all keys in ``z`` are meant to be strings, |
| 355 |
# and that all values in ``z`` are meant to be either strings or ints |
| 356 |
z: Mapping[str, str | int] = {} |
| 357 |
|
| 358 |
:class:`list` only accepts one type argument, so a type checker would emit an |
| 359 |
error on the ``y`` assignment above. Similarly, |
| 360 |
:class:`~collections.abc.Mapping` only accepts two type arguments: the first |
| 361 |
indicates the type of the keys, and the second indicates the type of the |
| 362 |
values. |
| 363 |
|
| 364 |
Unlike most other Python containers, however, it is common in idiomatic Python |
| 365 |
code for tuples to have elements which are not all of the same type. For this |
| 366 |
reason, tuples are special-cased in Python's typing system. :class:`tuple` |
| 367 |
accepts *any number* of type arguments:: |
| 368 |
|
| 369 |
# OK: ``x`` is assigned to a tuple of length 1 where the sole element is an int |
| 370 |
x: tuple[int] = (5,) |
| 371 |
|
| 372 |
# OK: ``y`` is assigned to a tuple of length 2; |
| 373 |
# element 1 is an int, element 2 is a str |
| 374 |
y: tuple[int, str] = (5, "foo") |
| 375 |
|
| 376 |
# Error: the type annotation indicates a tuple of length 1, |
| 377 |
# but ``z`` has been assigned to a tuple of length 3 |
| 378 |
z: tuple[int] = (1, 2, 3) |
| 379 |
|
| 380 |
.. index:: single: ...; ellipsis literal |
| 381 |
|
| 382 |
To denote a tuple which could be of *any* length, and in which all elements are |
| 383 |
of the same type ``T``, use the literal ellipsis ``...``: ``tuple[T, ...]``. |
| 384 |
To denote an empty tuple, use |
| 385 |
``tuple[()]``. Using plain ``tuple`` as an annotation is equivalent to using |
| 386 |
``tuple[Any, ...]``:: |
| 387 |
|
| 388 |
x: tuple[int, ...] = (1, 2) |
| 389 |
# These reassignments are OK: ``tuple[int, ...]`` indicates x can be of any length |
| 390 |
x = (1, 2, 3) |
| 391 |
x = () |
| 392 |
# This reassignment is an error: all elements in ``x`` must be ints |
| 393 |
x = ("foo", "bar") |
| 394 |
|
| 395 |
# ``y`` can only ever be assigned to an empty tuple |
| 396 |
y: tuple[()] = () |
| 397 |
|
| 398 |
z: tuple = ("foo", "bar") |
| 399 |
# These reassignments are OK: plain ``tuple`` is equivalent to ``tuple[Any, ...]`` |
| 400 |
z = (1, 2, 3) |
| 401 |
z = () |
| 402 |
|
| 403 |
.. _type-of-class-objects: |
| 404 |
|
| 405 |
The type of class objects |
| 406 |
========================= |
| 407 |
|
| 408 |
A variable annotated with ``C`` may accept a value of type ``C``. In |
| 409 |
contrast, a variable annotated with ``type[C]`` (or deprecated |
| 410 |
:class:`typing.Type[C] <Type>`) may accept values that are classes |
| 411 |
themselves -- specifically, it will accept the *class object* of ``C``. For |
| 412 |
example:: |
| 413 |
|
| 414 |
a = 3 # Has type ``int`` |
| 415 |
b = int # Has type ``type[int]`` |
| 416 |
c = type(a) # Also has type ``type[int]`` |
| 417 |
|
| 418 |
Note that ``type[C]`` is covariant:: |
| 419 |
|
| 420 |
class User: ... |
| 421 |
class ProUser(User): ... |
| 422 |
class TeamUser(User): ... |
| 423 |
|
| 424 |
def make_new_user(user_class: type[User]) -> User: |
| 425 |
# ... |
| 426 |
return user_class() |
| 427 |
|
| 428 |
make_new_user(User) # OK |
| 429 |
make_new_user(ProUser) # Also OK: ``type[ProUser]`` is a subtype of ``type[User]`` |
| 430 |
make_new_user(TeamUser) # Still fine |
| 431 |
make_new_user(User()) # Error: expected ``type[User]`` but got ``User`` |
| 432 |
make_new_user(int) # Error: ``type[int]`` is not a subtype of ``type[User]`` |
| 433 |
|
| 434 |
The only legal parameters for :class:`type` are classes, :data:`Any`, |
| 435 |
:ref:`type variables <generics>`, and unions of any of these types. |
| 436 |
For example:: |
| 437 |
|
| 438 |
def new_non_team_user(user_class: type[BasicUser | ProUser]): ... |
| 439 |
|
| 440 |
new_non_team_user(BasicUser) # OK |
| 441 |
new_non_team_user(ProUser) # OK |
| 442 |
new_non_team_user(TeamUser) # Error: ``type[TeamUser]`` is not a subtype |
| 443 |
# of ``type[BasicUser | ProUser]`` |
| 444 |
new_non_team_user(User) # Also an error |
| 445 |
|
| 446 |
``type[Any]`` is equivalent to :class:`type`, which is the root of Python's |
| 447 |
:ref:`metaclass hierarchy <metaclasses>`. |
| 448 |
|
| 449 |
|
| 450 |
.. _annotating-generators-and-coroutines: |
| 451 |
|
| 452 |
Annotating generators and coroutines |
| 453 |
==================================== |
| 454 |
|
| 455 |
A generator can be annotated using the generic type |
| 456 |
:class:`Generator[YieldType, SendType, ReturnType] <collections.abc.Generator>`. |
| 457 |
For example:: |
| 458 |
|
| 459 |
def echo_round() -> Generator[int, float, str]: |
| 460 |
sent = yield 0 |
| 461 |
while sent >= 0: |
| 462 |
sent = yield round(sent) |
| 463 |
return 'Done' |
| 464 |
|
| 465 |
Note that unlike many other generic classes in the standard library, |
| 466 |
the ``SendType`` of :class:`~collections.abc.Generator` behaves |
| 467 |
contravariantly, not covariantly or invariantly. |
| 468 |
|
| 469 |
The ``SendType`` and ``ReturnType`` parameters default to :const:`!None`:: |
| 470 |
|
| 471 |
def infinite_stream(start: int) -> Generator[int]: |
| 472 |
while True: |
| 473 |
yield start |
| 474 |
start += 1 |
| 475 |
|
| 476 |
It is also possible to set these types explicitly:: |
| 477 |
|
| 478 |
def infinite_stream(start: int) -> Generator[int, None, None]: |
| 479 |
while True: |
| 480 |
yield start |
| 481 |
start += 1 |
| 482 |
|
| 483 |
Simple generators that only ever yield values can also be annotated |
| 484 |
as having a return type of either |
| 485 |
:class:`Iterable[YieldType] <collections.abc.Iterable>` |
| 486 |
or :class:`Iterator[YieldType] <collections.abc.Iterator>`:: |
| 487 |
|
| 488 |
def infinite_stream(start: int) -> Iterator[int]: |
| 489 |
while True: |
| 490 |
yield start |
| 491 |
start += 1 |
| 492 |
|
| 493 |
Async generators are handled in a similar fashion, but don't |
| 494 |
expect a ``ReturnType`` type argument |
| 495 |
(:class:`AsyncGenerator[YieldType, SendType] <collections.abc.AsyncGenerator>`). |
| 496 |
The ``SendType`` argument defaults to :const:`!None`, so the following definitions |
| 497 |
are equivalent:: |
| 498 |
|
| 499 |
async def infinite_stream(start: int) -> AsyncGenerator[int]: |
| 500 |
while True: |
| 501 |
yield start |
| 502 |
start = await increment(start) |
| 503 |
|
| 504 |
async def infinite_stream(start: int) -> AsyncGenerator[int, None]: |
| 505 |
while True: |
| 506 |
yield start |
| 507 |
start = await increment(start) |
| 508 |
|
| 509 |
As in the synchronous case, |
| 510 |
:class:`AsyncIterable[YieldType] <collections.abc.AsyncIterable>` |
| 511 |
and :class:`AsyncIterator[YieldType] <collections.abc.AsyncIterator>` are |
| 512 |
available as well:: |
| 513 |
|
| 514 |
async def infinite_stream(start: int) -> AsyncIterator[int]: |
| 515 |
while True: |
| 516 |
yield start |
| 517 |
start = await increment(start) |
| 518 |
|
| 519 |
Coroutines can be annotated using |
| 520 |
:class:`Coroutine[YieldType, SendType, ReturnType] <collections.abc.Coroutine>`. |
| 521 |
Generic arguments correspond to those of :class:`~collections.abc.Generator`, |
| 522 |
for example:: |
| 523 |
|
| 524 |
from collections.abc import Coroutine |
| 525 |
c: Coroutine[list[str], str, int] # Some coroutine defined elsewhere |
| 526 |
x = c.send('hi') # Inferred type of 'x' is list[str] |
| 527 |
async def bar() -> None: |
| 528 |
y = await c # Inferred type of 'y' is int |
| 529 |
|
| 530 |
.. _user-defined-generics: |
| 531 |
|
| 532 |
User-defined generic types |
| 533 |
========================== |
| 534 |
|
| 535 |
A user-defined class can be defined as a generic class. |
| 536 |
|
| 537 |
:: |
| 538 |
|
| 539 |
from logging import Logger |
| 540 |
|
| 541 |
class LoggedVar[T]: |
| 542 |
def __init__(self, value: T, name: str, logger: Logger) -> None: |
| 543 |
self.name = name |
| 544 |
self.logger = logger |
| 545 |
self.value = value |
| 546 |
|
| 547 |
def set(self, new: T) -> None: |
| 548 |
self.log('Set ' + repr(self.value)) |
| 549 |
self.value = new |
| 550 |
|
| 551 |
def get(self) -> T: |
| 552 |
self.log('Get ' + repr(self.value)) |
| 553 |
return self.value |
| 554 |
|
| 555 |
def log(self, message: str) -> None: |
| 556 |
self.logger.info('%s: %s', self.name, message) |
| 557 |
|
| 558 |
This syntax indicates that the class ``LoggedVar`` is parameterised around a |
| 559 |
single :ref:`type variable <typevar>` ``T`` . This also makes ``T`` valid as |
| 560 |
a type within the class body. |
| 561 |
|
| 562 |
Generic classes implicitly inherit from :class:`Generic`. For compatibility |
| 563 |
with Python 3.11 and lower, it is also possible to inherit explicitly from |
| 564 |
:class:`Generic` to indicate a generic class:: |
| 565 |
|
| 566 |
from typing import TypeVar, Generic |
| 567 |
|
| 568 |
T = TypeVar('T') |
| 569 |
|
| 570 |
class LoggedVar(Generic[T]): |
| 571 |
... |
| 572 |
|
| 573 |
Generic classes have :meth:`~object.__class_getitem__` methods, meaning they |
| 574 |
can be parameterised at runtime (e.g. ``LoggedVar[int]`` below):: |
| 575 |
|
| 576 |
from collections.abc import Iterable |
| 577 |
|
| 578 |
def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None: |
| 579 |
for var in vars: |
| 580 |
var.set(0) |
| 581 |
|
| 582 |
A generic type can have any number of type variables. All varieties of |
| 583 |
:class:`TypeVar` are permissible as parameters for a generic type:: |
| 584 |
|
| 585 |
from typing import TypeVar, Generic, Sequence |
| 586 |
|
| 587 |
class WeirdTrio[T, B: Sequence[bytes], S: (int, str)]: |
| 588 |
... |
| 589 |
|
| 590 |
OldT = TypeVar('OldT', contravariant=True) |
| 591 |
OldB = TypeVar('OldB', bound=Sequence[bytes], covariant=True) |
| 592 |
OldS = TypeVar('OldS', int, str) |
| 593 |
|
| 594 |
class OldWeirdTrio(Generic[OldT, OldB, OldS]): |
| 595 |
... |
| 596 |
|
| 597 |
Each type variable argument to :class:`Generic` must be distinct. |
| 598 |
This is thus invalid:: |
| 599 |
|
| 600 |
from typing import TypeVar, Generic |
| 601 |
... |
| 602 |
|
| 603 |
class Pair[M, M]: # SyntaxError |
| 604 |
... |
| 605 |
|
| 606 |
T = TypeVar('T') |
| 607 |
|
| 608 |
class Pair(Generic[T, T]): # INVALID |
| 609 |
... |
| 610 |
|
| 611 |
Generic classes can also inherit from other classes:: |
| 612 |
|
| 613 |
from collections.abc import Sized |
| 614 |
|
| 615 |
class LinkedList[T](Sized): |
| 616 |
... |
| 617 |
|
| 618 |
When inheriting from generic classes, some type parameters could be fixed:: |
| 619 |
|
| 620 |
from collections.abc import Mapping |
| 621 |
|
| 622 |
class MyDict[T](Mapping[str, T]): |
| 623 |
... |
| 624 |
|
| 625 |
In this case ``MyDict`` has a single parameter, ``T``. |
| 626 |
|
| 627 |
Using a generic class without specifying type parameters assumes |
| 628 |
:data:`Any` for each position. In the following example, ``MyIterable`` is |
| 629 |
not generic but implicitly inherits from ``Iterable[Any]``: |
| 630 |
|
| 631 |
.. testcode:: |
| 632 |
|
| 633 |
from collections.abc import Iterable |
| 634 |
|
| 635 |
class MyIterable(Iterable): # Same as Iterable[Any] |
| 636 |
... |
| 637 |
|
| 638 |
User-defined generic type aliases are also supported. Examples:: |
| 639 |
|
| 640 |
from collections.abc import Iterable |
| 641 |
|
| 642 |
type Response[S] = Iterable[S] | int |
| 643 |
|
| 644 |
# Return type here is same as Iterable[str] | int |
| 645 |
def response(query: str) -> Response[str]: |
| 646 |
... |
| 647 |
|
| 648 |
type Vec[T] = Iterable[tuple[T, T]] |
| 649 |
|
| 650 |
def inproduct[T: (int, float, complex)](v: Vec[T]) -> T: # Same as Iterable[tuple[T, T]] |
| 651 |
return sum(x*y for x, y in v) |
| 652 |
|
| 653 |
For backward compatibility, generic type aliases can also be created |
| 654 |
through a simple assignment:: |
| 655 |
|
| 656 |
from collections.abc import Iterable |
| 657 |
from typing import TypeVar |
| 658 |
|
| 659 |
S = TypeVar("S") |
| 660 |
Response = Iterable[S] | int |
| 661 |
|
| 662 |
.. versionchanged:: 3.7 |
| 663 |
:class:`Generic` no longer has a custom metaclass. |
| 664 |
|
| 665 |
.. versionchanged:: 3.12 |
| 666 |
Syntactic support for generics and type aliases is new in version 3.12. |
| 667 |
Previously, generic classes had to explicitly inherit from :class:`Generic` |
| 668 |
or contain a type variable in one of their bases. |
| 669 |
|
| 670 |
User-defined generics for parameter expressions are also supported via parameter |
| 671 |
specification variables in the form ``[**P]``. The behavior is consistent |
| 672 |
with type variables' described above as parameter specification variables are |
| 673 |
treated by the :mod:`!typing` module as a specialized type variable. The one exception |
| 674 |
to this is that a list of types can be used to substitute a :class:`ParamSpec`:: |
| 675 |
|
| 676 |
>>> class Z[T, **P]: ... # T is a TypeVar; P is a ParamSpec |
| 677 |
... |
| 678 |
>>> Z[int, [dict, float]] |
| 679 |
__main__.Z[int, [dict, float]] |
| 680 |
|
| 681 |
Classes generic over a :class:`ParamSpec` can also be created using explicit |
| 682 |
inheritance from :class:`Generic`. In this case, ``**`` is not used:: |
| 683 |
|
| 684 |
from typing import ParamSpec, Generic |
| 685 |
|
| 686 |
P = ParamSpec('P') |
| 687 |
|
| 688 |
class Z(Generic[P]): |
| 689 |
... |
| 690 |
|
| 691 |
Another difference between :class:`TypeVar` and :class:`ParamSpec` is that a |
| 692 |
generic with only one parameter specification variable will accept |
| 693 |
parameter lists in the forms ``X[[Type1, Type2, ...]]`` and also |
| 694 |
``X[Type1, Type2, ...]`` for aesthetic reasons. Internally, the latter is converted |
| 695 |
to the former, so the following are equivalent:: |
| 696 |
|
| 697 |
>>> class X[**P]: ... |
| 698 |
... |
| 699 |
>>> X[int, str] |
| 700 |
__main__.X[[int, str]] |
| 701 |
>>> X[[int, str]] |
| 702 |
__main__.X[[int, str]] |
| 703 |
|
| 704 |
Note that generics with :class:`ParamSpec` may not have correct |
| 705 |
``__parameters__`` after substitution in some cases because they |
| 706 |
are intended primarily for static type checking. |
| 707 |
|
| 708 |
.. versionchanged:: 3.10 |
| 709 |
:class:`Generic` can now be parameterized over parameter expressions. |
| 710 |
See :class:`ParamSpec` and :pep:`612` for more details. |
| 711 |
|
| 712 |
A user-defined generic class can have ABCs as base classes without a metaclass |
| 713 |
conflict. Generic metaclasses are not supported. The outcome of parameterizing |
| 714 |
generics is cached, and most types in the :mod:`!typing` module are :term:`hashable` and |
| 715 |
comparable for equality. |
| 716 |
|
| 717 |
|
| 718 |
The :data:`Any` type |
| 719 |
==================== |
| 720 |
|
| 721 |
A special kind of type is :data:`Any`. A static type checker will treat |
| 722 |
every type as assignable to :data:`Any` and :data:`Any` as assignable to |
| 723 |
every type. |
| 724 |
|
| 725 |
This means that it is possible to perform any operation or method call on a |
| 726 |
value of type :data:`Any` and assign it to any variable:: |
| 727 |
|
| 728 |
from typing import Any |
| 729 |
|
| 730 |
a: Any = None |
| 731 |
a = [] # OK |
| 732 |
a = 2 # OK |
| 733 |
|
| 734 |
s: str = '' |
| 735 |
s = a # OK |
| 736 |
|
| 737 |
def foo(item: Any) -> int: |
| 738 |
# Passes type checking; 'item' could be any type, |
| 739 |
# and that type might have a 'bar' method |
| 740 |
item.bar() |
| 741 |
... |
| 742 |
|
| 743 |
Notice that no type checking is performed when assigning a value of type |
| 744 |
:data:`Any` to a more precise type. For example, the static type checker did |
| 745 |
not report an error when assigning ``a`` to ``s`` even though ``s`` was |
| 746 |
declared to be of type :class:`str` and receives an :class:`int` value at |
| 747 |
runtime! |
| 748 |
|
| 749 |
Furthermore, all functions without a return type or parameter types will |
| 750 |
implicitly default to using :data:`Any`:: |
| 751 |
|
| 752 |
def legacy_parser(text): |
| 753 |
... |
| 754 |
return data |
| 755 |
|
| 756 |
# A static type checker will treat the above |
| 757 |
# as having the same signature as: |
| 758 |
def legacy_parser(text: Any) -> Any: |
| 759 |
... |
| 760 |
return data |
| 761 |
|
| 762 |
This behavior allows :data:`Any` to be used as an *escape hatch* when you |
| 763 |
need to mix dynamically and statically typed code. |
| 764 |
|
| 765 |
Contrast the behavior of :data:`Any` with the behavior of :class:`object`. |
| 766 |
Similar to :data:`Any`, every type is a subtype of :class:`object`. However, |
| 767 |
unlike :data:`Any`, the reverse is not true: :class:`object` is *not* a |
| 768 |
subtype of every other type. |
| 769 |
|
| 770 |
That means when the type of a value is :class:`object`, a type checker will |
| 771 |
reject almost all operations on it, and assigning it to a variable (or using |
| 772 |
it as a return value) of a more specialized type is a type error. For example:: |
| 773 |
|
| 774 |
def hash_a(item: object) -> int: |
| 775 |
# Fails type checking; an object does not have a 'magic' method. |
| 776 |
item.magic() |
| 777 |
... |
| 778 |
|
| 779 |
def hash_b(item: Any) -> int: |
| 780 |
# Passes type checking |
| 781 |
item.magic() |
| 782 |
... |
| 783 |
|
| 784 |
# Passes type checking, since ints and strs are subclasses of object |
| 785 |
hash_a(42) |
| 786 |
hash_a("foo") |
| 787 |
|
| 788 |
# Passes type checking, since Any is assignable to all types |
| 789 |
hash_b(42) |
| 790 |
hash_b("foo") |
| 791 |
|
| 792 |
Use :class:`object` to indicate that a value could be any type in a typesafe |
| 793 |
manner. Use :data:`Any` to indicate that a value is dynamically typed. |
| 794 |
|
| 795 |
|
| 796 |
Nominal vs structural subtyping |
| 797 |
=============================== |
| 798 |
|
| 799 |
Initially :pep:`484` defined the Python static type system as using |
| 800 |
*nominal subtyping*. This means that a class ``A`` is allowed where |
| 801 |
a class ``B`` is expected if and only if ``A`` is a subclass of ``B``. |
| 802 |
|
| 803 |
This requirement previously also applied to abstract base classes, such as |
| 804 |
:class:`~collections.abc.Iterable`. The problem with this approach is that a class had |
| 805 |
to be explicitly marked to support them, which is unpythonic and unlike |
| 806 |
what one would normally do in idiomatic dynamically typed Python code. |
| 807 |
For example, this conforms to :pep:`484`:: |
| 808 |
|
| 809 |
from collections.abc import Sized, Iterable, Iterator |
| 810 |
|
| 811 |
class Bucket(Sized, Iterable[int]): |
| 812 |
... |
| 813 |
def __len__(self) -> int: ... |
| 814 |
def __iter__(self) -> Iterator[int]: ... |
| 815 |
|
| 816 |
:pep:`544` solves this problem by allowing users to write |
| 817 |
the above code without explicit base classes in the class definition, |
| 818 |
allowing ``Bucket`` to be implicitly considered a subtype of both ``Sized`` |
| 819 |
and ``Iterable[int]`` by static type checkers. This is known as |
| 820 |
*structural subtyping* (or static duck-typing):: |
| 821 |
|
| 822 |
from collections.abc import Iterator, Iterable |
| 823 |
|
| 824 |
class Bucket: # Note: no base classes |
| 825 |
... |
| 826 |
def __len__(self) -> int: ... |
| 827 |
def __iter__(self) -> Iterator[int]: ... |
| 828 |
|
| 829 |
def collect(items: Iterable[int]) -> int: ... |
| 830 |
result = collect(Bucket()) # Passes type check |
| 831 |
|
| 832 |
Moreover, by subclassing a special class :class:`Protocol`, a user |
| 833 |
can define new custom protocols to fully enjoy structural subtyping |
| 834 |
(see examples below). |
| 835 |
|
| 836 |
Module contents |
| 837 |
=============== |
| 838 |
|
| 839 |
The ``typing`` module defines the following classes, functions and decorators. |
| 840 |
|
| 841 |
Special typing primitives |
| 842 |
------------------------- |
| 843 |
|
| 844 |
Special types |
| 845 |
""""""""""""" |
| 846 |
|
| 847 |
These can be used as types in annotations. They do not support subscription |
| 848 |
using ``[]``. |
| 849 |
|
| 850 |
.. data:: Any |
| 851 |
|
| 852 |
Special type indicating an unconstrained type. |
| 853 |
|
| 854 |
* Every type is assignable to :data:`Any`. |
| 855 |
* :data:`Any` is assignable to every type. |
| 856 |
|
| 857 |
.. versionchanged:: 3.11 |
| 858 |
:data:`Any` can now be used as a base class. This can be useful for |
| 859 |
avoiding type checker errors with classes that can duck type anywhere or |
| 860 |
are highly dynamic. |
| 861 |
|
| 862 |
.. data:: AnyStr |
| 863 |
|
| 864 |
A :ref:`constrained type variable <typing-constrained-typevar>`. |
| 865 |
|
| 866 |
Definition:: |
| 867 |
|
| 868 |
AnyStr = TypeVar('AnyStr', str, bytes) |
| 869 |
|
| 870 |
``AnyStr`` is meant to be used for functions that may accept :class:`str` or |
| 871 |
:class:`bytes` arguments but cannot allow the two to mix. |
| 872 |
|
| 873 |
For example:: |
| 874 |
|
| 875 |
def concat(a: AnyStr, b: AnyStr) -> AnyStr: |
| 876 |
return a + b |
| 877 |
|
| 878 |
concat("foo", "bar") # OK, output has type 'str' |
| 879 |
concat(b"foo", b"bar") # OK, output has type 'bytes' |
| 880 |
concat("foo", b"bar") # Error, cannot mix str and bytes |
| 881 |
|
| 882 |
Note that, despite its name, ``AnyStr`` has nothing to do with the |
| 883 |
:class:`Any` type, nor does it mean "any string". In particular, ``AnyStr`` |
| 884 |
and ``str | bytes`` are different from each other and have different use |
| 885 |
cases:: |
| 886 |
|
| 887 |
# Invalid use of AnyStr: |
| 888 |
# The type variable is used only once in the function signature, |
| 889 |
# so cannot be "solved" by the type checker |
| 890 |
def greet_bad(cond: bool) -> AnyStr: |
| 891 |
return "hi there!" if cond else b"greetings!" |
| 892 |
|
| 893 |
# The better way of annotating this function: |
| 894 |
def greet_proper(cond: bool) -> str | bytes: |
| 895 |
return "hi there!" if cond else b"greetings!" |
| 896 |
|
| 897 |
.. deprecated-removed:: 3.13 3.18 |
| 898 |
Deprecated in favor of the new :ref:`type parameter syntax <type-params>`. |
| 899 |
Use ``class A[T: (str, bytes)]: ...`` instead of importing ``AnyStr``. See |
| 900 |
:pep:`695` for more details. |
| 901 |
|
| 902 |
In Python 3.16, ``AnyStr`` will be removed from ``typing.__all__``, and |
| 903 |
deprecation warnings will be emitted at runtime when it is accessed or |
| 904 |
imported from ``typing``. ``AnyStr`` will be removed from ``typing`` |
| 905 |
in Python 3.18. |
| 906 |
|
| 907 |
.. data:: LiteralString |
| 908 |
|
| 909 |
Special type that includes only literal strings. |
| 910 |
|
| 911 |
Any string |
| 912 |
literal is compatible with ``LiteralString``, as is another |
| 913 |
``LiteralString``. However, an object typed as just ``str`` is not. |
| 914 |
A string created by composing ``LiteralString``-typed objects |
| 915 |
is also acceptable as a ``LiteralString``. |
| 916 |
|
| 917 |
Example: |
| 918 |
|
| 919 |
.. testcode:: |
| 920 |
|
| 921 |
def run_query(sql: LiteralString) -> None: |
| 922 |
... |
| 923 |
|
| 924 |
def caller(arbitrary_string: str, literal_string: LiteralString) -> None: |
| 925 |
run_query("SELECT * FROM students") # OK |
| 926 |
run_query(literal_string) # OK |
| 927 |
run_query("SELECT * FROM " + literal_string) # OK |
| 928 |
run_query(arbitrary_string) # type checker error |
| 929 |
run_query( # type checker error |
| 930 |
f"SELECT * FROM students WHERE name = {arbitrary_string}" |
| 931 |
) |
| 932 |
|
| 933 |
``LiteralString`` is useful for sensitive APIs where arbitrary user-generated |
| 934 |
strings could generate problems. For example, the two cases above |
| 935 |
that generate type checker errors could be vulnerable to an SQL |
| 936 |
injection attack. |
| 937 |
|
| 938 |
See :pep:`675` for more details. |
| 939 |
|
| 940 |
.. versionadded:: 3.11 |
| 941 |
|
| 942 |
.. data:: Never |
| 943 |
NoReturn |
| 944 |
|
| 945 |
:data:`!Never` and :data:`!NoReturn` represent the |
| 946 |
`bottom type <https://en.wikipedia.org/wiki/Bottom_type>`_, |
| 947 |
a type that has no members. |
| 948 |
|
| 949 |
They can be used to indicate that a function never returns, |
| 950 |
such as :func:`sys.exit`:: |
| 951 |
|
| 952 |
from typing import Never # or NoReturn |
| 953 |
|
| 954 |
def stop() -> Never: |
| 955 |
raise RuntimeError('no way') |
| 956 |
|
| 957 |
Or to define a function that should never be |
| 958 |
called, as there are no valid arguments, such as |
| 959 |
:func:`assert_never`:: |
| 960 |
|
| 961 |
from typing import Never # or NoReturn |
| 962 |
|
| 963 |
def never_call_me(arg: Never) -> None: |
| 964 |
pass |
| 965 |
|
| 966 |
def int_or_str(arg: int | str) -> None: |
| 967 |
never_call_me(arg) # type checker error |
| 968 |
match arg: |
| 969 |
case int(): |
| 970 |
print("It's an int") |
| 971 |
case str(): |
| 972 |
print("It's a str") |
| 973 |
case _: |
| 974 |
never_call_me(arg) # OK, arg is of type Never (or NoReturn) |
| 975 |
|
| 976 |
:data:`!Never` and :data:`!NoReturn` have the same meaning in the type system |
| 977 |
and static type checkers treat both equivalently. |
| 978 |
|
| 979 |
.. versionadded:: 3.6.2 |
| 980 |
|
| 981 |
Added :data:`NoReturn`. |
| 982 |
|
| 983 |
.. versionadded:: 3.11 |
| 984 |
|
| 985 |
Added :data:`Never`. |
| 986 |
|
| 987 |
.. data:: Self |
| 988 |
|
| 989 |
Special type to represent the current enclosed class. |
| 990 |
|
| 991 |
For example:: |
| 992 |
|
| 993 |
from typing import Self, reveal_type |
| 994 |
|
| 995 |
class Foo: |
| 996 |
def return_self(self) -> Self: |
| 997 |
... |
| 998 |
return self |
| 999 |
|
| 1000 |
class SubclassOfFoo(Foo): pass |
| 1001 |
|
| 1002 |
reveal_type(Foo().return_self()) # Revealed type is "Foo" |
| 1003 |
reveal_type(SubclassOfFoo().return_self()) # Revealed type is "SubclassOfFoo" |
| 1004 |
|
| 1005 |
This annotation is semantically equivalent to the following, |
| 1006 |
albeit in a more succinct fashion:: |
| 1007 |
|
| 1008 |
from typing import TypeVar |
| 1009 |
|
| 1010 |
Self = TypeVar("Self", bound="Foo") |
| 1011 |
|
| 1012 |
class Foo: |
| 1013 |
def return_self(self: Self) -> Self: |
| 1014 |
... |
| 1015 |
return self |
| 1016 |
|
| 1017 |
In general, if something returns ``self``, as in the above examples, you |
| 1018 |
should use ``Self`` as the return annotation. If ``Foo.return_self`` was |
| 1019 |
annotated as returning ``"Foo"``, then the type checker would infer the |
| 1020 |
object returned from ``SubclassOfFoo.return_self`` as being of type ``Foo`` |
| 1021 |
rather than ``SubclassOfFoo``. |
| 1022 |
|
| 1023 |
Other common use cases include: |
| 1024 |
|
| 1025 |
- :class:`classmethod`\s that are used as alternative constructors and return instances |
| 1026 |
of the ``cls`` parameter. |
| 1027 |
- Annotating an :meth:`~object.__enter__` method which returns self. |
| 1028 |
|
| 1029 |
You should not use ``Self`` as the return annotation if the method is not |
| 1030 |
guaranteed to return an instance of a subclass when the class is |
| 1031 |
subclassed:: |
| 1032 |
|
| 1033 |
class Eggs: |
| 1034 |
# Self would be an incorrect return annotation here, |
| 1035 |
# as the object returned is always an instance of Eggs, |
| 1036 |
# even in subclasses |
| 1037 |
def returns_eggs(self) -> "Eggs": |
| 1038 |
return Eggs() |
| 1039 |
|
| 1040 |
See :pep:`673` for more details. |
| 1041 |
|
| 1042 |
.. versionadded:: 3.11 |
| 1043 |
|
| 1044 |
.. data:: TypeAlias |
| 1045 |
|
| 1046 |
Special annotation for explicitly declaring a :ref:`type alias <type-aliases>`. |
| 1047 |
|
| 1048 |
For example:: |
| 1049 |
|
| 1050 |
from typing import TypeAlias |
| 1051 |
|
| 1052 |
Factors: TypeAlias = list[int] |
| 1053 |
|
| 1054 |
``TypeAlias`` is particularly useful on older Python versions for annotating |
| 1055 |
aliases that make use of forward references, as it can be hard for type |
| 1056 |
checkers to distinguish these from normal variable assignments: |
| 1057 |
|
| 1058 |
.. testcode:: |
| 1059 |
|
| 1060 |
from typing import Generic, TypeAlias, TypeVar |
| 1061 |
|
| 1062 |
T = TypeVar("T") |
| 1063 |
|
| 1064 |
# "Box" does not exist yet, |
| 1065 |
# so we have to use quotes for the forward reference on Python <3.12. |
| 1066 |
# Using ``TypeAlias`` tells the type checker that this is a type alias declaration, |
| 1067 |
# not a variable assignment to a string. |
| 1068 |
BoxOfStrings: TypeAlias = "Box[str]" |
| 1069 |
|
| 1070 |
class Box(Generic[T]): |
| 1071 |
@classmethod |
| 1072 |
def make_box_of_strings(cls) -> BoxOfStrings: ... |
| 1073 |
|
| 1074 |
See :pep:`613` for more details. |
| 1075 |
|
| 1076 |
.. versionadded:: 3.10 |
| 1077 |
|
| 1078 |
.. deprecated:: 3.12 |
| 1079 |
:data:`TypeAlias` is deprecated in favor of the :keyword:`type` statement, |
| 1080 |
which creates instances of :class:`TypeAliasType` |
| 1081 |
and which natively supports forward references. |
| 1082 |
Note that while :data:`TypeAlias` and :class:`TypeAliasType` serve |
| 1083 |
similar purposes and have similar names, they are distinct and the |
| 1084 |
latter is not the type of the former. |
| 1085 |
Removal of :data:`TypeAlias` is not currently planned, but users |
| 1086 |
are encouraged to migrate to :keyword:`type` statements. |
| 1087 |
|
| 1088 |
Special forms |
| 1089 |
""""""""""""" |
| 1090 |
|
| 1091 |
These can be used as types in annotations. They all support subscription using |
| 1092 |
``[]``, but each has a unique syntax. |
| 1093 |
|
| 1094 |
.. class:: Union |
| 1095 |
|
| 1096 |
Union type; ``Union[X, Y]`` is equivalent to ``X | Y`` and means either X or Y. |
| 1097 |
|
| 1098 |
To define a union, use e.g. ``Union[int, str]`` or the shorthand ``int | str``. Using that shorthand is recommended. Details: |
| 1099 |
|
| 1100 |
* The arguments must be types and there must be at least one. |
| 1101 |
|
| 1102 |
* Unions of unions are flattened, e.g.:: |
| 1103 |
|
| 1104 |
Union[Union[int, str], float] == Union[int, str, float] |
| 1105 |
|
| 1106 |
However, this does not apply to unions referenced through a type |
| 1107 |
alias, to avoid forcing evaluation of the underlying :class:`TypeAliasType`:: |
| 1108 |
|
| 1109 |
type A = Union[int, str] |
| 1110 |
Union[A, float] != Union[int, str, float] |
| 1111 |
|
| 1112 |
* Unions of a single argument vanish, e.g.:: |
| 1113 |
|
| 1114 |
Union[int] == int # The constructor actually returns int |
| 1115 |
|
| 1116 |
* Redundant arguments are skipped, e.g.:: |
| 1117 |
|
| 1118 |
Union[int, str, int] == Union[int, str] == int | str |
| 1119 |
|
| 1120 |
* When comparing unions, the argument order is ignored, e.g.:: |
| 1121 |
|
| 1122 |
Union[int, str] == Union[str, int] |
| 1123 |
|
| 1124 |
* You cannot subclass or instantiate a ``Union``. |
| 1125 |
|
| 1126 |
* You cannot write ``Union[X][Y]``. |
| 1127 |
|
| 1128 |
.. versionchanged:: 3.7 |
| 1129 |
Don't remove explicit subclasses from unions at runtime. |
| 1130 |
|
| 1131 |
.. versionchanged:: 3.10 |
| 1132 |
Unions can now be written as ``X | Y``. See |
| 1133 |
:ref:`union type expressions<types-union>`. |
| 1134 |
|
| 1135 |
.. versionchanged:: 3.14 |
| 1136 |
:class:`types.UnionType` is now an alias for :class:`Union`, and both |
| 1137 |
``Union[int, str]`` and ``int | str`` create instances of the same class. |
| 1138 |
To check whether an object is a ``Union`` at runtime, use |
| 1139 |
``isinstance(obj, Union)``. For compatibility with earlier versions of |
| 1140 |
Python, use |
| 1141 |
``get_origin(obj) is typing.Union or get_origin(obj) is types.UnionType``. |
| 1142 |
|
| 1143 |
.. data:: Optional |
| 1144 |
|
| 1145 |
``Optional[X]`` is equivalent to ``X | None`` (or ``Union[X, None]``). |
| 1146 |
|
| 1147 |
Note that this is not the same concept as an optional argument, |
| 1148 |
which is one that has a default. An optional argument with a |
| 1149 |
default does not require the ``Optional`` qualifier on its type |
| 1150 |
annotation just because it is optional. For example:: |
| 1151 |
|
| 1152 |
def foo(arg: int = 0) -> None: |
| 1153 |
... |
| 1154 |
|
| 1155 |
On the other hand, if an explicit value of ``None`` is allowed, the |
| 1156 |
use of ``Optional`` is appropriate, whether the argument is optional |
| 1157 |
or not. For example:: |
| 1158 |
|
| 1159 |
def foo(arg: Optional[int] = None) -> None: |
| 1160 |
... |
| 1161 |
|
| 1162 |
.. versionchanged:: 3.10 |
| 1163 |
Optional can now be written as ``X | None``. See |
| 1164 |
:ref:`union type expressions<types-union>`. |
| 1165 |
|
| 1166 |
.. data:: Concatenate |
| 1167 |
|
| 1168 |
Special form for annotating higher-order functions. |
| 1169 |
|
| 1170 |
.. index:: single: ...; ellipsis literal |
| 1171 |
|
| 1172 |
``Concatenate`` can be used in conjunction with :ref:`Callable <annotating-callables>` and |
| 1173 |
:class:`ParamSpec` to annotate a higher-order callable which adds, removes, |
| 1174 |
or transforms parameters of another |
| 1175 |
callable. Usage is in the form |
| 1176 |
``Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable]``. ``Concatenate`` |
| 1177 |
is valid when used in :ref:`Callable <annotating-callables>` type hints |
| 1178 |
and when instantiating user-defined generic classes with :class:`ParamSpec` parameters. |
| 1179 |
The last parameter to ``Concatenate`` must be a :class:`ParamSpec` or |
| 1180 |
ellipsis (``...``). |
| 1181 |
|
| 1182 |
For example, to annotate a decorator ``with_lock`` which provides a |
| 1183 |
:class:`threading.Lock` to the decorated function, ``Concatenate`` can be |
| 1184 |
used to indicate that ``with_lock`` expects a callable which takes in a |
| 1185 |
``Lock`` as the first argument, and returns a callable with a different type |
| 1186 |
signature. In this case, the :class:`ParamSpec` indicates that the returned |
| 1187 |
callable's parameter types are dependent on the parameter types of the |
| 1188 |
callable being passed in:: |
| 1189 |
|
| 1190 |
from collections.abc import Callable |
| 1191 |
from threading import Lock |
| 1192 |
from typing import Concatenate |
| 1193 |
|
| 1194 |
# Use this lock to ensure that only one thread is executing a function |
| 1195 |
# at any time. |
| 1196 |
my_lock = Lock() |
| 1197 |
|
| 1198 |
def with_lock[**P, R](f: Callable[Concatenate[Lock, P], R]) -> Callable[P, R]: |
| 1199 |
'''A type-safe decorator which provides a lock.''' |
| 1200 |
def inner(*args: P.args, **kwargs: P.kwargs) -> R: |
| 1201 |
# Provide the lock as the first argument. |
| 1202 |
return f(my_lock, *args, **kwargs) |
| 1203 |
return inner |
| 1204 |
|
| 1205 |
@with_lock |
| 1206 |
def sum_threadsafe(lock: Lock, numbers: list[float]) -> float: |
| 1207 |
'''Add a list of numbers together in a thread-safe manner.''' |
| 1208 |
with lock: |
| 1209 |
return sum(numbers) |
| 1210 |
|
| 1211 |
# We don't need to pass in the lock ourselves thanks to the decorator. |
| 1212 |
sum_threadsafe([1.1, 2.2, 3.3]) |
| 1213 |
|
| 1214 |
.. versionadded:: 3.10 |
| 1215 |
|
| 1216 |
.. seealso:: |
| 1217 |
|
| 1218 |
* :pep:`612` -- Parameter Specification Variables (the PEP which introduced |
| 1219 |
``ParamSpec`` and ``Concatenate``) |
| 1220 |
* :class:`ParamSpec` |
| 1221 |
* :ref:`annotating-callables` |
| 1222 |
|
| 1223 |
.. data:: Literal |
| 1224 |
|
| 1225 |
Special typing form to define "literal types". |
| 1226 |
|
| 1227 |
``Literal`` can be used to indicate to type checkers that the |
| 1228 |
annotated object has a value equivalent to one of the |
| 1229 |
provided literals. |
| 1230 |
|
| 1231 |
For example:: |
| 1232 |
|
| 1233 |
def validate_simple(data: Any) -> Literal[True]: # always returns True |
| 1234 |
... |
| 1235 |
|
| 1236 |
type Mode = Literal['r', 'rb', 'w', 'wb'] |
| 1237 |
def open_helper(file: str, mode: Mode) -> str: |
| 1238 |
... |
| 1239 |
|
| 1240 |
open_helper('/some/path', 'r') # Passes type check |
| 1241 |
open_helper('/other/path', 'typo') # Error in type checker |
| 1242 |
|
| 1243 |
``Literal[...]`` cannot be subclassed. At runtime, an arbitrary value |
| 1244 |
is allowed as type argument to ``Literal[...]``, but type checkers may |
| 1245 |
impose restrictions. See :pep:`586` for more details about literal types. |
| 1246 |
|
| 1247 |
Additional details: |
| 1248 |
|
| 1249 |
* The arguments must be literal values and there must be at least one. |
| 1250 |
|
| 1251 |
* Nested ``Literal`` types are flattened, e.g.:: |
| 1252 |
|
| 1253 |
assert Literal[Literal[1, 2], 3] == Literal[1, 2, 3] |
| 1254 |
|
| 1255 |
However, this does not apply to ``Literal`` types referenced through a type |
| 1256 |
alias, to avoid forcing evaluation of the underlying :class:`TypeAliasType`:: |
| 1257 |
|
| 1258 |
type A = Literal[1, 2] |
| 1259 |
assert Literal[A, 3] != Literal[1, 2, 3] |
| 1260 |
|
| 1261 |
* Redundant arguments are skipped, e.g.:: |
| 1262 |
|
| 1263 |
assert Literal[1, 2, 1] == Literal[1, 2] |
| 1264 |
|
| 1265 |
* When comparing literals, the argument order is ignored, e.g.:: |
| 1266 |
|
| 1267 |
assert Literal[1, 2] == Literal[2, 1] |
| 1268 |
|
| 1269 |
* You cannot subclass or instantiate a ``Literal``. |
| 1270 |
|
| 1271 |
* You cannot write ``Literal[X][Y]``. |
| 1272 |
|
| 1273 |
.. versionadded:: 3.8 |
| 1274 |
|
| 1275 |
.. versionchanged:: 3.9.1 |
| 1276 |
``Literal`` now de-duplicates parameters. Equality comparisons of |
| 1277 |
``Literal`` objects are no longer order dependent. ``Literal`` objects |
| 1278 |
will now raise a :exc:`TypeError` exception during equality comparisons |
| 1279 |
if one of their parameters are not :term:`hashable`. |
| 1280 |
|
| 1281 |
.. data:: ClassVar |
| 1282 |
|
| 1283 |
Special type construct to mark class variables. |
| 1284 |
|
| 1285 |
As introduced in :pep:`526`, a variable annotation wrapped in ClassVar |
| 1286 |
indicates that a given attribute is intended to be used as a class variable |
| 1287 |
and should not be set on instances of that class. Usage:: |
| 1288 |
|
| 1289 |
class Starship: |
| 1290 |
stats: ClassVar[dict[str, int]] = {} # class variable |
| 1291 |
damage: int = 10 # instance variable |
| 1292 |
|
| 1293 |
:data:`ClassVar` accepts only types and cannot be further subscribed. |
| 1294 |
|
| 1295 |
:data:`ClassVar` is not a class itself, and cannot |
| 1296 |
be used with :func:`isinstance` or :func:`issubclass`. |
| 1297 |
:data:`ClassVar` does not change Python runtime behavior, but |
| 1298 |
it can be used by static type checkers. For example, a type checker |
| 1299 |
might flag the following code as an error:: |
| 1300 |
|
| 1301 |
enterprise_d = Starship(3000) |
| 1302 |
enterprise_d.stats = {} # Error, setting class variable on instance |
| 1303 |
Starship.stats = {} # This is OK |
| 1304 |
|
| 1305 |
.. versionadded:: 3.5.3 |
| 1306 |
|
| 1307 |
.. versionchanged:: 3.13 |
| 1308 |
|
| 1309 |
:data:`ClassVar` can now be nested in :data:`Final` and vice versa. |
| 1310 |
|
| 1311 |
.. data:: Final |
| 1312 |
|
| 1313 |
Special typing construct to indicate final names to type checkers. |
| 1314 |
|
| 1315 |
Final names cannot be reassigned in any scope. Final names declared in class |
| 1316 |
scopes cannot be overridden in subclasses. |
| 1317 |
|
| 1318 |
For example:: |
| 1319 |
|
| 1320 |
MAX_SIZE: Final = 9000 |
| 1321 |
MAX_SIZE += 1 # Error reported by type checker |
| 1322 |
|
| 1323 |
class Connection: |
| 1324 |
TIMEOUT: Final[int] = 10 |
| 1325 |
|
| 1326 |
class FastConnector(Connection): |
| 1327 |
TIMEOUT = 1 # Error reported by type checker |
| 1328 |
|
| 1329 |
There is no runtime checking of these properties. See :pep:`591` for |
| 1330 |
more details. |
| 1331 |
|
| 1332 |
.. versionadded:: 3.8 |
| 1333 |
|
| 1334 |
.. versionchanged:: 3.13 |
| 1335 |
|
| 1336 |
:data:`Final` can now be nested in :data:`ClassVar` and vice versa. |
| 1337 |
|
| 1338 |
.. data:: Required |
| 1339 |
|
| 1340 |
Special typing construct to mark a :class:`TypedDict` key as required. |
| 1341 |
|
| 1342 |
This is mainly useful for ``total=False`` TypedDicts. See :class:`TypedDict` |
| 1343 |
and :pep:`655` for more details. |
| 1344 |
|
| 1345 |
.. versionadded:: 3.11 |
| 1346 |
|
| 1347 |
.. data:: NotRequired |
| 1348 |
|
| 1349 |
Special typing construct to mark a :class:`TypedDict` key as potentially |
| 1350 |
missing. |
| 1351 |
|
| 1352 |
See :class:`TypedDict` and :pep:`655` for more details. |
| 1353 |
|
| 1354 |
.. versionadded:: 3.11 |
| 1355 |
|
| 1356 |
.. data:: ReadOnly |
| 1357 |
|
| 1358 |
A special typing construct to mark an item of a :class:`TypedDict` as read-only. |
| 1359 |
|
| 1360 |
For example:: |
| 1361 |
|
| 1362 |
class Movie(TypedDict): |
| 1363 |
title: ReadOnly[str] |
| 1364 |
year: int |
| 1365 |
|
| 1366 |
def mutate_movie(m: Movie) -> None: |
| 1367 |
m["year"] = 1999 # allowed |
| 1368 |
m["title"] = "The Matrix" # type checker error |
| 1369 |
|
| 1370 |
There is no runtime checking for this property. |
| 1371 |
|
| 1372 |
See :class:`TypedDict` and :pep:`705` for more details. |
| 1373 |
|
| 1374 |
.. versionadded:: 3.13 |
| 1375 |
|
| 1376 |
.. data:: Annotated |
| 1377 |
|
| 1378 |
Special typing form to add context-specific metadata to an annotation. |
| 1379 |
|
| 1380 |
Add metadata ``x`` to a given type ``T`` by using the annotation |
| 1381 |
``Annotated[T, x]``. Metadata added using ``Annotated`` can be used by |
| 1382 |
static analysis tools or at runtime. At runtime, the metadata is stored |
| 1383 |
in a :attr:`!__metadata__` attribute. |
| 1384 |
|
| 1385 |
If a library or tool encounters an annotation ``Annotated[T, x]`` and has |
| 1386 |
no special logic for the metadata, it should ignore the metadata and simply |
| 1387 |
treat the annotation as ``T``. As such, ``Annotated`` can be useful for code |
| 1388 |
that wants to use annotations for purposes outside Python's static typing |
| 1389 |
system. |
| 1390 |
|
| 1391 |
Using ``Annotated[T, x]`` as an annotation still allows for static |
| 1392 |
typechecking of ``T``, as type checkers will simply ignore the metadata ``x``. |
| 1393 |
In this way, ``Annotated`` differs from the |
| 1394 |
:deco:`no_type_check` decorator, which can also be used for |
| 1395 |
adding annotations outside the scope of the typing system, but |
| 1396 |
completely disables typechecking for a function or class. |
| 1397 |
|
| 1398 |
The responsibility of how to interpret the metadata |
| 1399 |
lies with the tool or library encountering an |
| 1400 |
``Annotated`` annotation. A tool or library encountering an ``Annotated`` type |
| 1401 |
can scan through the metadata elements to determine if they are of interest |
| 1402 |
(e.g., using :func:`isinstance`). |
| 1403 |
|
| 1404 |
.. describe:: Annotated[<type>, <metadata>] |
| 1405 |
|
| 1406 |
Here is an example of how you might use ``Annotated`` to add metadata to |
| 1407 |
type annotations if you were doing range analysis: |
| 1408 |
|
| 1409 |
.. testcode:: |
| 1410 |
|
| 1411 |
@dataclass |
| 1412 |
class ValueRange: |
| 1413 |
lo: int |
| 1414 |
hi: int |
| 1415 |
|
| 1416 |
T1 = Annotated[int, ValueRange(-10, 5)] |
| 1417 |
T2 = Annotated[T1, ValueRange(-20, 3)] |
| 1418 |
|
| 1419 |
The first argument to ``Annotated`` must be a valid type. Multiple metadata |
| 1420 |
elements can be supplied as ``Annotated`` supports variadic arguments. The |
| 1421 |
order of the metadata elements is preserved and matters for equality checks:: |
| 1422 |
|
| 1423 |
@dataclass |
| 1424 |
class ctype: |
| 1425 |
kind: str |
| 1426 |
|
| 1427 |
a1 = Annotated[int, ValueRange(3, 10), ctype("char")] |
| 1428 |
a2 = Annotated[int, ctype("char"), ValueRange(3, 10)] |
| 1429 |
|
| 1430 |
assert a1 != a2 # Order matters |
| 1431 |
|
| 1432 |
It is up to the tool consuming the annotations to decide whether the |
| 1433 |
client is allowed to add multiple metadata elements to one annotation and how to |
| 1434 |
merge those annotations. |
| 1435 |
|
| 1436 |
Nested ``Annotated`` types are flattened. The order of the metadata elements |
| 1437 |
starts with the innermost annotation:: |
| 1438 |
|
| 1439 |
assert Annotated[Annotated[int, ValueRange(3, 10)], ctype("char")] == Annotated[ |
| 1440 |
int, ValueRange(3, 10), ctype("char") |
| 1441 |
] |
| 1442 |
|
| 1443 |
However, this does not apply to ``Annotated`` types referenced through a type |
| 1444 |
alias, to avoid forcing evaluation of the underlying :class:`TypeAliasType`:: |
| 1445 |
|
| 1446 |
type From3To10[T] = Annotated[T, ValueRange(3, 10)] |
| 1447 |
assert Annotated[From3To10[int], ctype("char")] != Annotated[ |
| 1448 |
int, ValueRange(3, 10), ctype("char") |
| 1449 |
] |
| 1450 |
|
| 1451 |
Duplicated metadata elements are not removed:: |
| 1452 |
|
| 1453 |
assert Annotated[int, ValueRange(3, 10)] != Annotated[ |
| 1454 |
int, ValueRange(3, 10), ValueRange(3, 10) |
| 1455 |
] |
| 1456 |
|
| 1457 |
``Annotated`` can be used with nested and generic aliases: |
| 1458 |
|
| 1459 |
.. testcode:: |
| 1460 |
|
| 1461 |
@dataclass |
| 1462 |
class MaxLen: |
| 1463 |
value: int |
| 1464 |
|
| 1465 |
type Vec[T] = Annotated[list[tuple[T, T]], MaxLen(10)] |
| 1466 |
|
| 1467 |
# When used in a type annotation, a type checker will treat "V" the same as |
| 1468 |
# ``Annotated[list[tuple[int, int]], MaxLen(10)]``: |
| 1469 |
type V = Vec[int] |
| 1470 |
|
| 1471 |
``Annotated`` cannot be used with an unpacked :class:`TypeVarTuple`:: |
| 1472 |
|
| 1473 |
type Variadic[*Ts] = Annotated[*Ts, Ann1] = Annotated[T1, T2, T3, ..., Ann1] # NOT valid |
| 1474 |
|
| 1475 |
where ``T1``, ``T2``, ... are :class:`TypeVars <TypeVar>`. This is invalid as |
| 1476 |
only one type should be passed to Annotated. |
| 1477 |
|
| 1478 |
By default, :func:`get_type_hints` strips the metadata from annotations. |
| 1479 |
Pass ``include_extras=True`` to have the metadata preserved: |
| 1480 |
|
| 1481 |
.. doctest:: |
| 1482 |
|
| 1483 |
>>> from typing import Annotated, get_type_hints |
| 1484 |
>>> def func(x: Annotated[int, "metadata"]) -> None: pass |
| 1485 |
... |
| 1486 |
>>> get_type_hints(func) |
| 1487 |
{'x': <class 'int'>, 'return': <class 'NoneType'>} |
| 1488 |
>>> get_type_hints(func, include_extras=True) |
| 1489 |
{'x': typing.Annotated[int, 'metadata'], 'return': <class 'NoneType'>} |
| 1490 |
|
| 1491 |
At runtime, the metadata associated with an ``Annotated`` type can be |
| 1492 |
retrieved via the :attr:`!__metadata__` attribute: |
| 1493 |
|
| 1494 |
.. doctest:: |
| 1495 |
|
| 1496 |
>>> from typing import Annotated |
| 1497 |
>>> X = Annotated[int, "very", "important", "metadata"] |
| 1498 |
>>> X |
| 1499 |
typing.Annotated[int, 'very', 'important', 'metadata'] |
| 1500 |
>>> X.__metadata__ |
| 1501 |
('very', 'important', 'metadata') |
| 1502 |
|
| 1503 |
If you want to retrieve the original type wrapped by ``Annotated``, use the |
| 1504 |
:attr:`!__origin__` attribute: |
| 1505 |
|
| 1506 |
.. doctest:: |
| 1507 |
|
| 1508 |
>>> from typing import Annotated, get_origin |
| 1509 |
>>> Password = Annotated[str, "secret"] |
| 1510 |
>>> Password.__origin__ |
| 1511 |
<class 'str'> |
| 1512 |
|
| 1513 |
Note that using :func:`get_origin` will return ``Annotated`` itself: |
| 1514 |
|
| 1515 |
.. doctest:: |
| 1516 |
|
| 1517 |
>>> get_origin(Password) |
| 1518 |
typing.Annotated |
| 1519 |
|
| 1520 |
.. seealso:: |
| 1521 |
|
| 1522 |
:pep:`593` - Flexible function and variable annotations |
| 1523 |
The PEP introducing ``Annotated`` to the standard library. |
| 1524 |
|
| 1525 |
.. versionadded:: 3.9 |
| 1526 |
|
| 1527 |
|
| 1528 |
.. data:: TypeIs |
| 1529 |
|
| 1530 |
Special typing construct for marking user-defined type predicate functions. |
| 1531 |
|
| 1532 |
``TypeIs`` can be used to annotate the return type of a user-defined |
| 1533 |
type predicate function. ``TypeIs`` only accepts a single type argument. |
| 1534 |
At runtime, functions marked this way should return a boolean and take at |
| 1535 |
least one positional argument. |
| 1536 |
|
| 1537 |
``TypeIs`` aims to benefit *type narrowing* -- a technique used by static |
| 1538 |
type checkers to determine a more precise type of an expression within a |
| 1539 |
program's code flow. Usually type narrowing is done by analyzing |
| 1540 |
conditional code flow and applying the narrowing to a block of code. The |
| 1541 |
conditional expression here is sometimes referred to as a "type predicate":: |
| 1542 |
|
| 1543 |
def is_str(val: str | float): |
| 1544 |
# "isinstance" type predicate |
| 1545 |
if isinstance(val, str): |
| 1546 |
# Type of ``val`` is narrowed to ``str`` |
| 1547 |
... |
| 1548 |
else: |
| 1549 |
# Else, type of ``val`` is narrowed to ``float``. |
| 1550 |
... |
| 1551 |
|
| 1552 |
Sometimes it would be convenient to use a user-defined boolean function |
| 1553 |
as a type predicate. Such a function should use ``TypeIs[...]`` or |
| 1554 |
:data:`TypeGuard` as its return type to alert static type checkers to |
| 1555 |
this intention. ``TypeIs`` usually has more intuitive behavior than |
| 1556 |
``TypeGuard``, but it cannot be used when the input and output types |
| 1557 |
are incompatible (e.g., ``list[object]`` to ``list[int]``) or when the |
| 1558 |
function does not return ``True`` for all instances of the narrowed type. |
| 1559 |
|
| 1560 |
Using ``-> TypeIs[NarrowedType]`` tells the static type checker that for a given |
| 1561 |
function: |
| 1562 |
|
| 1563 |
1. The return value is a boolean. |
| 1564 |
2. If the return value is ``True``, the type of its argument |
| 1565 |
is the intersection of the argument's original type and ``NarrowedType``. |
| 1566 |
3. If the return value is ``False``, the type of its argument |
| 1567 |
is narrowed to exclude ``NarrowedType``. |
| 1568 |
|
| 1569 |
For example:: |
| 1570 |
|
| 1571 |
from typing import assert_type, final, TypeIs |
| 1572 |
|
| 1573 |
class Parent: pass |
| 1574 |
class Child(Parent): pass |
| 1575 |
@final |
| 1576 |
class Unrelated: pass |
| 1577 |
|
| 1578 |
def is_parent(val: object) -> TypeIs[Parent]: |
| 1579 |
return isinstance(val, Parent) |
| 1580 |
|
| 1581 |
def run(arg: Child | Unrelated): |
| 1582 |
if is_parent(arg): |
| 1583 |
# Type of ``arg`` is narrowed to the intersection |
| 1584 |
# of ``Parent`` and ``Child``, which is equivalent to |
| 1585 |
# ``Child``. |
| 1586 |
assert_type(arg, Child) |
| 1587 |
else: |
| 1588 |
# Type of ``arg`` is narrowed to exclude ``Parent``, |
| 1589 |
# so only ``Unrelated`` is left. |
| 1590 |
assert_type(arg, Unrelated) |
| 1591 |
|
| 1592 |
The type inside ``TypeIs`` must be consistent with the type of the |
| 1593 |
function's argument; if it is not, static type checkers will raise |
| 1594 |
an error. An incorrectly written ``TypeIs`` function can lead to |
| 1595 |
unsound behavior in the type system; it is the user's responsibility |
| 1596 |
to write such functions in a type-safe manner. |
| 1597 |
|
| 1598 |
If a ``TypeIs`` function is a class or instance method, then the type in |
| 1599 |
``TypeIs`` maps to the type of the second parameter (after ``cls`` or |
| 1600 |
``self``). |
| 1601 |
|
| 1602 |
In short, the form ``def foo(arg: TypeA) -> TypeIs[TypeB]: ...``, |
| 1603 |
means that if ``foo(arg)`` returns ``True``, then ``arg`` is an instance |
| 1604 |
of ``TypeB``, and if it returns ``False``, it is not an instance of ``TypeB``. |
| 1605 |
|
| 1606 |
``TypeIs`` also works with type variables. For more information, see |
| 1607 |
:pep:`742` (Narrowing types with ``TypeIs``). |
| 1608 |
|
| 1609 |
.. versionadded:: 3.13 |
| 1610 |
|
| 1611 |
|
| 1612 |
.. data:: TypeGuard |
| 1613 |
|
| 1614 |
Special typing construct for marking user-defined type predicate functions. |
| 1615 |
|
| 1616 |
Type predicate functions are user-defined functions that return whether their |
| 1617 |
argument is an instance of a particular type. |
| 1618 |
``TypeGuard`` works similarly to :data:`TypeIs`, but has subtly different |
| 1619 |
effects on type checking behavior (see below). |
| 1620 |
|
| 1621 |
Using ``-> TypeGuard`` tells the static type checker that for a given |
| 1622 |
function: |
| 1623 |
|
| 1624 |
1. The return value is a boolean. |
| 1625 |
2. If the return value is ``True``, the type of its argument |
| 1626 |
is the type inside ``TypeGuard``. |
| 1627 |
|
| 1628 |
``TypeGuard`` also works with type variables. See :pep:`647` for more details. |
| 1629 |
|
| 1630 |
For example:: |
| 1631 |
|
| 1632 |
def is_str_list(val: list[object]) -> TypeGuard[list[str]]: |
| 1633 |
'''Determines whether all objects in the list are strings''' |
| 1634 |
return all(isinstance(x, str) for x in val) |
| 1635 |
|
| 1636 |
def func1(val: list[object]): |
| 1637 |
if is_str_list(val): |
| 1638 |
# Type of ``val`` is narrowed to ``list[str]``. |
| 1639 |
print(" ".join(val)) |
| 1640 |
else: |
| 1641 |
# Type of ``val`` remains as ``list[object]``. |
| 1642 |
print("Not a list of strings!") |
| 1643 |
|
| 1644 |
``TypeIs`` and ``TypeGuard`` differ in the following ways: |
| 1645 |
|
| 1646 |
* ``TypeIs`` requires the narrowed type to be a subtype of the input type, while |
| 1647 |
``TypeGuard`` does not. The main reason is to allow for things like |
| 1648 |
narrowing ``list[object]`` to ``list[str]`` even though the latter |
| 1649 |
is not a subtype of the former, since ``list`` is invariant. |
| 1650 |
* When a ``TypeGuard`` function returns ``True``, type checkers narrow the type of the |
| 1651 |
variable to exactly the ``TypeGuard`` type. When a ``TypeIs`` function returns ``True``, |
| 1652 |
type checkers can infer a more precise type combining the previously known type of the |
| 1653 |
variable with the ``TypeIs`` type. (Technically, this is known as an intersection type.) |
| 1654 |
* When a ``TypeGuard`` function returns ``False``, type checkers cannot narrow the type of |
| 1655 |
the variable at all. When a ``TypeIs`` function returns ``False``, type checkers can narrow |
| 1656 |
the type of the variable to exclude the ``TypeIs`` type. |
| 1657 |
|
| 1658 |
.. versionadded:: 3.10 |
| 1659 |
|
| 1660 |
|
| 1661 |
.. data:: Unpack |
| 1662 |
|
| 1663 |
Typing operator to conceptually mark an object as having been unpacked. |
| 1664 |
|
| 1665 |
For example, using the unpack operator ``*`` on a |
| 1666 |
:ref:`type variable tuple <typevartuple>` is equivalent to using ``Unpack`` |
| 1667 |
to mark the type variable tuple as having been unpacked:: |
| 1668 |
|
| 1669 |
Ts = TypeVarTuple('Ts') |
| 1670 |
tup: tuple[*Ts] |
| 1671 |
# Effectively does: |
| 1672 |
tup: tuple[Unpack[Ts]] |
| 1673 |
|
| 1674 |
In fact, ``Unpack`` can be used interchangeably with ``*`` in the context |
| 1675 |
of :class:`typing.TypeVarTuple <TypeVarTuple>` and |
| 1676 |
:class:`builtins.tuple <tuple>` types. You might see ``Unpack`` being used |
| 1677 |
explicitly in older versions of Python, where ``*`` couldn't be used in |
| 1678 |
certain places:: |
| 1679 |
|
| 1680 |
# In older versions of Python, TypeVarTuple and Unpack |
| 1681 |
# are located in the `typing_extensions` backports package. |
| 1682 |
from typing_extensions import TypeVarTuple, Unpack |
| 1683 |
|
| 1684 |
Ts = TypeVarTuple('Ts') |
| 1685 |
tup: tuple[*Ts] # Syntax error on Python <= 3.10! |
| 1686 |
tup: tuple[Unpack[Ts]] # Semantically equivalent, and backwards-compatible |
| 1687 |
|
| 1688 |
``Unpack`` can also be used along with :class:`typing.TypedDict` for typing |
| 1689 |
``**kwargs`` in a function signature:: |
| 1690 |
|
| 1691 |
from typing import TypedDict, Unpack |
| 1692 |
|
| 1693 |
class Movie(TypedDict): |
| 1694 |
name: str |
| 1695 |
year: int |
| 1696 |
|
| 1697 |
# This function expects two keyword arguments - `name` of type `str` |
| 1698 |
# and `year` of type `int`. |
| 1699 |
def foo(**kwargs: Unpack[Movie]): ... |
| 1700 |
|
| 1701 |
See :pep:`692` for more details on using ``Unpack`` for ``**kwargs`` typing. |
| 1702 |
|
| 1703 |
.. versionadded:: 3.11 |
| 1704 |
|
| 1705 |
Building generic types and type aliases |
| 1706 |
""""""""""""""""""""""""""""""""""""""" |
| 1707 |
|
| 1708 |
The following classes should not be used directly as annotations. |
| 1709 |
Their intended purpose is to be building blocks |
| 1710 |
for creating generic types and type aliases. |
| 1711 |
|
| 1712 |
These objects can be created through special syntax |
| 1713 |
(:ref:`type parameter lists <type-params>` and the :keyword:`type` statement). |
| 1714 |
For compatibility with Python 3.11 and earlier, they can also be created |
| 1715 |
without the dedicated syntax, as documented below. |
| 1716 |
|
| 1717 |
.. class:: Generic |
| 1718 |
|
| 1719 |
Abstract base class for generic types. |
| 1720 |
|
| 1721 |
A generic type is typically declared by adding a list of type parameters |
| 1722 |
after the class name:: |
| 1723 |
|
| 1724 |
class Mapping[KT, VT]: |
| 1725 |
def __getitem__(self, key: KT) -> VT: |
| 1726 |
... |
| 1727 |
# Etc. |
| 1728 |
|
| 1729 |
Such a class implicitly inherits from ``Generic``. |
| 1730 |
The runtime semantics of this syntax are discussed in the |
| 1731 |
:ref:`Language Reference <generic-classes>`. |
| 1732 |
|
| 1733 |
This class can then be used as follows:: |
| 1734 |
|
| 1735 |
def lookup_name[X, Y](mapping: Mapping[X, Y], key: X, default: Y) -> Y: |
| 1736 |
try: |
| 1737 |
return mapping[key] |
| 1738 |
except KeyError: |
| 1739 |
return default |
| 1740 |
|
| 1741 |
Here the brackets after the function name indicate a |
| 1742 |
:ref:`generic function <generic-functions>`. |
| 1743 |
|
| 1744 |
For backwards compatibility, generic classes can also be |
| 1745 |
declared by explicitly inheriting from |
| 1746 |
``Generic``. In this case, the type parameters must be declared |
| 1747 |
separately:: |
| 1748 |
|
| 1749 |
KT = TypeVar('KT') |
| 1750 |
VT = TypeVar('VT') |
| 1751 |
|
| 1752 |
class Mapping(Generic[KT, VT]): |
| 1753 |
def __getitem__(self, key: KT) -> VT: |
| 1754 |
... |
| 1755 |
# Etc. |
| 1756 |
|
| 1757 |
.. _typevar: |
| 1758 |
|
| 1759 |
.. class:: TypeVar(name, *constraints, bound=None, covariant=False, contravariant=False, infer_variance=False, default=typing.NoDefault) |
| 1760 |
|
| 1761 |
Type variable. |
| 1762 |
|
| 1763 |
The preferred way to construct a type variable is via the dedicated syntax |
| 1764 |
for :ref:`generic functions <generic-functions>`, |
| 1765 |
:ref:`generic classes <generic-classes>`, and |
| 1766 |
:ref:`generic type aliases <generic-type-aliases>`:: |
| 1767 |
|
| 1768 |
class Sequence[T]: # T is a TypeVar |
| 1769 |
... |
| 1770 |
|
| 1771 |
This syntax can also be used to create bounded and constrained type |
| 1772 |
variables:: |
| 1773 |
|
| 1774 |
class StrSequence[S: str]: # S is a TypeVar with a `str` upper bound; |
| 1775 |
... # we can say that S is "bounded by `str`" |
| 1776 |
|
| 1777 |
|
| 1778 |
class StrOrBytesSequence[A: (str, bytes)]: # A is a TypeVar constrained to str or bytes |
| 1779 |
... |
| 1780 |
|
| 1781 |
However, if desired, reusable type variables can also be constructed manually, like so:: |
| 1782 |
|
| 1783 |
T = TypeVar('T') # Can be anything |
| 1784 |
S = TypeVar('S', bound=str) # Can be any subtype of str |
| 1785 |
A = TypeVar('A', str, bytes) # Must be exactly str or bytes |
| 1786 |
|
| 1787 |
Type variables exist primarily for the benefit of static type |
| 1788 |
checkers. They serve as the parameters for generic types as well |
| 1789 |
as for generic function and type alias definitions. |
| 1790 |
See :class:`Generic` for more |
| 1791 |
information on generic types. Generic functions work as follows:: |
| 1792 |
|
| 1793 |
def repeat[T](x: T, n: int) -> Sequence[T]: |
| 1794 |
"""Return a list containing n references to x.""" |
| 1795 |
return [x]*n |
| 1796 |
|
| 1797 |
|
| 1798 |
def print_capitalized[S: str](x: S) -> S: |
| 1799 |
"""Print x capitalized, and return x.""" |
| 1800 |
print(x.capitalize()) |
| 1801 |
return x |
| 1802 |
|
| 1803 |
|
| 1804 |
def concatenate[A: (str, bytes)](x: A, y: A) -> A: |
| 1805 |
"""Add two strings or bytes objects together.""" |
| 1806 |
return x + y |
| 1807 |
|
| 1808 |
Note that type variables can be *bounded*, *constrained*, or neither, but |
| 1809 |
cannot be both bounded *and* constrained. |
| 1810 |
|
| 1811 |
The variance of type variables is inferred by type checkers when they are created |
| 1812 |
through the :ref:`type parameter syntax <type-params>` or when |
| 1813 |
``infer_variance=True`` is passed. |
| 1814 |
Manually created type variables may be explicitly marked covariant or contravariant by passing |
| 1815 |
``covariant=True`` or ``contravariant=True``. |
| 1816 |
By default, manually created type variables are invariant. |
| 1817 |
See :pep:`484` and :pep:`695` for more details. |
| 1818 |
|
| 1819 |
Bounded type variables and constrained type variables have different |
| 1820 |
semantics in several important ways. Using a *bounded* type variable means |
| 1821 |
that the ``TypeVar`` will be solved using the most specific type possible:: |
| 1822 |
|
| 1823 |
x = print_capitalized('a string') |
| 1824 |
reveal_type(x) # revealed type is str |
| 1825 |
|
| 1826 |
class StringSubclass(str): |
| 1827 |
pass |
| 1828 |
|
| 1829 |
y = print_capitalized(StringSubclass('another string')) |
| 1830 |
reveal_type(y) # revealed type is StringSubclass |
| 1831 |
|
| 1832 |
z = print_capitalized(45) # error: int is not a subtype of str |
| 1833 |
|
| 1834 |
The upper bound of a type variable can be a concrete type, abstract type |
| 1835 |
(ABC or Protocol), or even a union of types:: |
| 1836 |
|
| 1837 |
# Can be anything with an __abs__ method |
| 1838 |
def print_abs[T: SupportsAbs](arg: T) -> None: |
| 1839 |
print("Absolute value:", abs(arg)) |
| 1840 |
|
| 1841 |
U = TypeVar('U', bound=str|bytes) # Can be any subtype of the union str|bytes |
| 1842 |
V = TypeVar('V', bound=SupportsAbs) # Can be anything with an __abs__ method |
| 1843 |
|
| 1844 |
.. _typing-constrained-typevar: |
| 1845 |
|
| 1846 |
Using a *constrained* type variable, however, means that the ``TypeVar`` |
| 1847 |
can only ever be solved as being exactly one of the constraints given:: |
| 1848 |
|
| 1849 |
a = concatenate('one', 'two') |
| 1850 |
reveal_type(a) # revealed type is str |
| 1851 |
|
| 1852 |
b = concatenate(StringSubclass('one'), StringSubclass('two')) |
| 1853 |
reveal_type(b) # revealed type is str, despite StringSubclass being passed in |
| 1854 |
|
| 1855 |
c = concatenate('one', b'two') # error: type variable 'A' can be either str or bytes in a function call, but not both |
| 1856 |
|
| 1857 |
At runtime, ``isinstance(x, T)`` will raise :exc:`TypeError`. |
| 1858 |
|
| 1859 |
.. attribute:: __name__ |
| 1860 |
|
| 1861 |
The name of the type variable. |
| 1862 |
|
| 1863 |
.. attribute:: __covariant__ |
| 1864 |
|
| 1865 |
Whether the type var has been explicitly marked as covariant. |
| 1866 |
|
| 1867 |
.. attribute:: __contravariant__ |
| 1868 |
|
| 1869 |
Whether the type var has been explicitly marked as contravariant. |
| 1870 |
|
| 1871 |
.. attribute:: __infer_variance__ |
| 1872 |
|
| 1873 |
Whether the type variable's variance should be inferred by type checkers. |
| 1874 |
|
| 1875 |
.. versionadded:: 3.12 |
| 1876 |
|
| 1877 |
.. attribute:: __bound__ |
| 1878 |
|
| 1879 |
The upper bound of the type variable, if any. |
| 1880 |
|
| 1881 |
.. versionchanged:: 3.12 |
| 1882 |
|
| 1883 |
For type variables created through :ref:`type parameter syntax <type-params>`, |
| 1884 |
the bound is evaluated only when the attribute is accessed, not when |
| 1885 |
the type variable is created (see :ref:`lazy-evaluation`). |
| 1886 |
|
| 1887 |
.. method:: evaluate_bound |
| 1888 |
|
| 1889 |
An :term:`evaluate function` corresponding to the :attr:`~TypeVar.__bound__` attribute. |
| 1890 |
When called directly, this method supports only the :attr:`~annotationlib.Format.VALUE` |
| 1891 |
format, which is equivalent to accessing the :attr:`~TypeVar.__bound__` attribute directly, |
| 1892 |
but the method object can be passed to :func:`annotationlib.call_evaluate_function` |
| 1893 |
to evaluate the value in a different format. |
| 1894 |
|
| 1895 |
.. versionadded:: 3.14 |
| 1896 |
|
| 1897 |
.. attribute:: __constraints__ |
| 1898 |
|
| 1899 |
A tuple containing the constraints of the type variable, if any. |
| 1900 |
|
| 1901 |
.. versionchanged:: 3.12 |
| 1902 |
|
| 1903 |
For type variables created through :ref:`type parameter syntax <type-params>`, |
| 1904 |
the constraints are evaluated only when the attribute is accessed, not when |
| 1905 |
the type variable is created (see :ref:`lazy-evaluation`). |
| 1906 |
|
| 1907 |
.. method:: evaluate_constraints |
| 1908 |
|
| 1909 |
An :term:`evaluate function` corresponding to the :attr:`~TypeVar.__constraints__` attribute. |
| 1910 |
When called directly, this method supports only the :attr:`~annotationlib.Format.VALUE` |
| 1911 |
format, which is equivalent to accessing the :attr:`~TypeVar.__constraints__` attribute directly, |
| 1912 |
but the method object can be passed to :func:`annotationlib.call_evaluate_function` |
| 1913 |
to evaluate the value in a different format. |
| 1914 |
|
| 1915 |
.. versionadded:: 3.14 |
| 1916 |
|
| 1917 |
.. attribute:: __default__ |
| 1918 |
|
| 1919 |
The default value of the type variable, or :data:`typing.NoDefault` if it |
| 1920 |
has no default. |
| 1921 |
|
| 1922 |
.. versionadded:: 3.13 |
| 1923 |
|
| 1924 |
.. method:: evaluate_default |
| 1925 |
|
| 1926 |
An :term:`evaluate function` corresponding to the :attr:`~TypeVar.__default__` attribute. |
| 1927 |
When called directly, this method supports only the :attr:`~annotationlib.Format.VALUE` |
| 1928 |
format, which is equivalent to accessing the :attr:`~TypeVar.__default__` attribute directly, |
| 1929 |
but the method object can be passed to :func:`annotationlib.call_evaluate_function` |
| 1930 |
to evaluate the value in a different format. |
| 1931 |
|
| 1932 |
.. versionadded:: 3.14 |
| 1933 |
|
| 1934 |
.. method:: has_default() |
| 1935 |
|
| 1936 |
Return whether or not the type variable has a default value. This is equivalent |
| 1937 |
to checking whether :attr:`__default__` is not the :data:`typing.NoDefault` |
| 1938 |
singleton, except that it does not force evaluation of the |
| 1939 |
:ref:`lazily evaluated <lazy-evaluation>` default value. |
| 1940 |
|
| 1941 |
.. versionadded:: 3.13 |
| 1942 |
|
| 1943 |
.. versionchanged:: 3.12 |
| 1944 |
|
| 1945 |
Type variables can now be declared using the |
| 1946 |
:ref:`type parameter <type-params>` syntax introduced by :pep:`695`. |
| 1947 |
The ``infer_variance`` parameter was added. |
| 1948 |
|
| 1949 |
.. versionchanged:: 3.13 |
| 1950 |
|
| 1951 |
Support for default values was added. |
| 1952 |
|
| 1953 |
.. _typevartuple: |
| 1954 |
|
| 1955 |
.. class:: TypeVarTuple(name, *, default=typing.NoDefault) |
| 1956 |
|
| 1957 |
Type variable tuple. A specialized form of :ref:`type variable <typevar>` |
| 1958 |
that enables *variadic* generics. |
| 1959 |
|
| 1960 |
Type variable tuples can be declared in :ref:`type parameter lists <type-params>` |
| 1961 |
using a single asterisk (``*``) before the name:: |
| 1962 |
|
| 1963 |
def move_first_element_to_last[T, *Ts](tup: tuple[T, *Ts]) -> tuple[*Ts, T]: |
| 1964 |
return (*tup[1:], tup[0]) |
| 1965 |
|
| 1966 |
Or by explicitly invoking the ``TypeVarTuple`` constructor:: |
| 1967 |
|
| 1968 |
T = TypeVar("T") |
| 1969 |
Ts = TypeVarTuple("Ts") |
| 1970 |
|
| 1971 |
def move_first_element_to_last(tup: tuple[T, *Ts]) -> tuple[*Ts, T]: |
| 1972 |
return (*tup[1:], tup[0]) |
| 1973 |
|
| 1974 |
A normal type variable enables parameterization with a single type. A type |
| 1975 |
variable tuple, in contrast, allows parameterization with an |
| 1976 |
*arbitrary* number of types by acting like an *arbitrary* number of type |
| 1977 |
variables wrapped in a tuple. For example:: |
| 1978 |
|
| 1979 |
# T is bound to int, Ts is bound to () |
| 1980 |
# Return value is (1,), which has type tuple[int] |
| 1981 |
move_first_element_to_last(tup=(1,)) |
| 1982 |
|
| 1983 |
# T is bound to int, Ts is bound to (str,) |
| 1984 |
# Return value is ('spam', 1), which has type tuple[str, int] |
| 1985 |
move_first_element_to_last(tup=(1, 'spam')) |
| 1986 |
|
| 1987 |
# T is bound to int, Ts is bound to (str, float) |
| 1988 |
# Return value is ('spam', 3.0, 1), which has type tuple[str, float, int] |
| 1989 |
move_first_element_to_last(tup=(1, 'spam', 3.0)) |
| 1990 |
|
| 1991 |
# This fails to type check (and fails at runtime) |
| 1992 |
# because tuple[()] is not compatible with tuple[T, *Ts] |
| 1993 |
# (at least one element is required) |
| 1994 |
move_first_element_to_last(tup=()) |
| 1995 |
|
| 1996 |
Note the use of the unpacking operator ``*`` in ``tuple[T, *Ts]``. |
| 1997 |
Conceptually, you can think of ``Ts`` as a tuple of type variables |
| 1998 |
``(T1, T2, ...)``. ``tuple[T, *Ts]`` would then become |
| 1999 |
``tuple[T, *(T1, T2, ...)]``, which is equivalent to |
| 2000 |
``tuple[T, T1, T2, ...]``. (Note that in older versions of Python, you might |
| 2001 |
see this written using :data:`Unpack <Unpack>` instead, as |
| 2002 |
``Unpack[Ts]``.) |
| 2003 |
|
| 2004 |
Type variable tuples must *always* be unpacked. This helps distinguish type |
| 2005 |
variable tuples from normal type variables:: |
| 2006 |
|
| 2007 |
x: Ts # Not valid |
| 2008 |
x: tuple[Ts] # Not valid |
| 2009 |
x: tuple[*Ts] # The correct way to do it |
| 2010 |
|
| 2011 |
Type variable tuples can be used in the same contexts as normal type |
| 2012 |
variables. For example, in class definitions, arguments, and return types:: |
| 2013 |
|
| 2014 |
class Array[*Shape]: |
| 2015 |
def __getitem__(self, key: tuple[*Shape]) -> float: ... |
| 2016 |
def __abs__(self) -> "Array[*Shape]": ... |
| 2017 |
def get_shape(self) -> tuple[*Shape]: ... |
| 2018 |
|
| 2019 |
Type variable tuples can be happily combined with normal type variables: |
| 2020 |
|
| 2021 |
.. testcode:: |
| 2022 |
|
| 2023 |
class Array[DType, *Shape]: # This is fine |
| 2024 |
pass |
| 2025 |
|
| 2026 |
class Array2[*Shape, DType]: # This would also be fine |
| 2027 |
pass |
| 2028 |
|
| 2029 |
class Height: ... |
| 2030 |
class Width: ... |
| 2031 |
|
| 2032 |
float_array_1d: Array[float, Height] = Array() # Totally fine |
| 2033 |
int_array_2d: Array[int, Height, Width] = Array() # Yup, fine too |
| 2034 |
|
| 2035 |
However, note that at most one type variable tuple may appear in a single |
| 2036 |
list of type arguments or type parameters:: |
| 2037 |
|
| 2038 |
x: tuple[*Ts, *Ts] # Not valid |
| 2039 |
class Array[*Shape, *Shape]: # Not valid |
| 2040 |
pass |
| 2041 |
|
| 2042 |
Finally, an unpacked type variable tuple can be used as the type annotation |
| 2043 |
of ``*args``:: |
| 2044 |
|
| 2045 |
def call_soon[*Ts]( |
| 2046 |
callback: Callable[[*Ts], None], |
| 2047 |
*args: *Ts |
| 2048 |
) -> None: |
| 2049 |
... |
| 2050 |
callback(*args) |
| 2051 |
|
| 2052 |
In contrast to non-unpacked annotations of ``*args`` - e.g. ``*args: int``, |
| 2053 |
which would specify that *all* arguments are ``int`` - ``*args: *Ts`` |
| 2054 |
enables reference to the types of the *individual* arguments in ``*args``. |
| 2055 |
Here, this allows us to ensure the types of the ``*args`` passed |
| 2056 |
to ``call_soon`` match the types of the (positional) arguments of |
| 2057 |
``callback``. |
| 2058 |
|
| 2059 |
See :pep:`646` for more details on type variable tuples. |
| 2060 |
|
| 2061 |
.. attribute:: __name__ |
| 2062 |
|
| 2063 |
The name of the type variable tuple. |
| 2064 |
|
| 2065 |
.. attribute:: __default__ |
| 2066 |
|
| 2067 |
The default value of the type variable tuple, or :data:`typing.NoDefault` if it |
| 2068 |
has no default. |
| 2069 |
|
| 2070 |
.. versionadded:: 3.13 |
| 2071 |
|
| 2072 |
.. method:: evaluate_default |
| 2073 |
|
| 2074 |
An :term:`evaluate function` corresponding to the :attr:`~TypeVarTuple.__default__` attribute. |
| 2075 |
When called directly, this method supports only the :attr:`~annotationlib.Format.VALUE` |
| 2076 |
format, which is equivalent to accessing the :attr:`~TypeVarTuple.__default__` attribute directly, |
| 2077 |
but the method object can be passed to :func:`annotationlib.call_evaluate_function` |
| 2078 |
to evaluate the value in a different format. |
| 2079 |
|
| 2080 |
.. versionadded:: 3.14 |
| 2081 |
|
| 2082 |
.. method:: has_default() |
| 2083 |
|
| 2084 |
Return whether or not the type variable tuple has a default value. This is equivalent |
| 2085 |
to checking whether :attr:`__default__` is not the :data:`typing.NoDefault` |
| 2086 |
singleton, except that it does not force evaluation of the |
| 2087 |
:ref:`lazily evaluated <lazy-evaluation>` default value. |
| 2088 |
|
| 2089 |
.. versionadded:: 3.13 |
| 2090 |
|
| 2091 |
.. versionadded:: 3.11 |
| 2092 |
|
| 2093 |
.. versionchanged:: 3.12 |
| 2094 |
|
| 2095 |
Type variable tuples can now be declared using the |
| 2096 |
:ref:`type parameter <type-params>` syntax introduced by :pep:`695`. |
| 2097 |
|
| 2098 |
.. versionchanged:: 3.13 |
| 2099 |
|
| 2100 |
Support for default values was added. |
| 2101 |
|
| 2102 |
.. class:: ParamSpec(name, *, bound=None, covariant=False, contravariant=False, default=typing.NoDefault) |
| 2103 |
|
| 2104 |
Parameter specification variable. A specialized version of |
| 2105 |
:ref:`type variables <typevar>`. |
| 2106 |
|
| 2107 |
In :ref:`type parameter lists <type-params>`, parameter specifications |
| 2108 |
can be declared with two asterisks (``**``):: |
| 2109 |
|
| 2110 |
type IntFunc[**P] = Callable[P, int] |
| 2111 |
|
| 2112 |
For compatibility with Python 3.11 and earlier, ``ParamSpec`` objects |
| 2113 |
can also be created as follows:: |
| 2114 |
|
| 2115 |
P = ParamSpec('P') |
| 2116 |
|
| 2117 |
Parameter specification variables exist primarily for the benefit of static |
| 2118 |
type checkers. They are used to forward the parameter types of one |
| 2119 |
callable to another callable -- a pattern commonly found in higher order |
| 2120 |
functions and decorators. They are only valid when used in ``Concatenate``, |
| 2121 |
or as the first argument to ``Callable``, or as parameters for user-defined |
| 2122 |
Generics. See :class:`Generic` for more information on generic types. |
| 2123 |
|
| 2124 |
For example, to add basic logging to a function, one can create a decorator |
| 2125 |
``add_logging`` to log function calls. The parameter specification variable |
| 2126 |
tells the type checker that the callable passed into the decorator and the |
| 2127 |
new callable returned by it have inter-dependent type parameters:: |
| 2128 |
|
| 2129 |
from collections.abc import Callable |
| 2130 |
import logging |
| 2131 |
|
| 2132 |
def add_logging[T, **P](f: Callable[P, T]) -> Callable[P, T]: |
| 2133 |
'''A type-safe decorator to add logging to a function.''' |
| 2134 |
def inner(*args: P.args, **kwargs: P.kwargs) -> T: |
| 2135 |
logging.info(f'{f.__name__} was called') |
| 2136 |
return f(*args, **kwargs) |
| 2137 |
return inner |
| 2138 |
|
| 2139 |
@add_logging |
| 2140 |
def add_two(x: float, y: float) -> float: |
| 2141 |
'''Add two numbers together.''' |
| 2142 |
return x + y |
| 2143 |
|
| 2144 |
Without ``ParamSpec``, the simplest way to annotate this previously was to |
| 2145 |
use a :class:`TypeVar` with upper bound ``Callable[..., Any]``. However this |
| 2146 |
causes two problems: |
| 2147 |
|
| 2148 |
1. The type checker can't type check the ``inner`` function because |
| 2149 |
``*args`` and ``**kwargs`` have to be typed :data:`Any`. |
| 2150 |
2. :func:`~cast` may be required in the body of the ``add_logging`` |
| 2151 |
decorator when returning the ``inner`` function, or the static type |
| 2152 |
checker must be told to ignore the ``return inner``. |
| 2153 |
|
| 2154 |
.. attribute:: args |
| 2155 |
.. attribute:: kwargs |
| 2156 |
|
| 2157 |
Since ``ParamSpec`` captures both positional and keyword parameters, |
| 2158 |
``P.args`` and ``P.kwargs`` can be used to split a ``ParamSpec`` into its |
| 2159 |
components. ``P.args`` represents the tuple of positional parameters in a |
| 2160 |
given call and should only be used to annotate ``*args``. ``P.kwargs`` |
| 2161 |
represents the mapping of keyword parameters to their values in a given call, |
| 2162 |
and should be only be used to annotate ``**kwargs``. Both |
| 2163 |
attributes require the annotated parameter to be in scope. At runtime, |
| 2164 |
``P.args`` and ``P.kwargs`` are instances respectively of |
| 2165 |
:class:`ParamSpecArgs` and :class:`ParamSpecKwargs`. |
| 2166 |
|
| 2167 |
.. attribute:: __name__ |
| 2168 |
|
| 2169 |
The name of the parameter specification. |
| 2170 |
|
| 2171 |
.. attribute:: __default__ |
| 2172 |
|
| 2173 |
The default value of the parameter specification, or :data:`typing.NoDefault` if it |
| 2174 |
has no default. |
| 2175 |
|
| 2176 |
.. versionadded:: 3.13 |
| 2177 |
|
| 2178 |
.. method:: evaluate_default |
| 2179 |
|
| 2180 |
An :term:`evaluate function` corresponding to the :attr:`~ParamSpec.__default__` attribute. |
| 2181 |
When called directly, this method supports only the :attr:`~annotationlib.Format.VALUE` |
| 2182 |
format, which is equivalent to accessing the :attr:`~ParamSpec.__default__` attribute directly, |
| 2183 |
but the method object can be passed to :func:`annotationlib.call_evaluate_function` |
| 2184 |
to evaluate the value in a different format. |
| 2185 |
|
| 2186 |
.. versionadded:: 3.14 |
| 2187 |
|
| 2188 |
.. method:: has_default() |
| 2189 |
|
| 2190 |
Return whether or not the parameter specification has a default value. This is equivalent |
| 2191 |
to checking whether :attr:`__default__` is not the :data:`typing.NoDefault` |
| 2192 |
singleton, except that it does not force evaluation of the |
| 2193 |
:ref:`lazily evaluated <lazy-evaluation>` default value. |
| 2194 |
|
| 2195 |
.. versionadded:: 3.13 |
| 2196 |
|
| 2197 |
Parameter specification variables created with ``covariant=True`` or |
| 2198 |
``contravariant=True`` can be used to declare covariant or contravariant |
| 2199 |
generic types. The ``bound`` argument is also accepted, similar to |
| 2200 |
:class:`TypeVar`. However the actual semantics of these keywords are yet to |
| 2201 |
be decided. |
| 2202 |
|
| 2203 |
.. versionadded:: 3.10 |
| 2204 |
|
| 2205 |
.. versionchanged:: 3.12 |
| 2206 |
|
| 2207 |
Parameter specifications can now be declared using the |
| 2208 |
:ref:`type parameter <type-params>` syntax introduced by :pep:`695`. |
| 2209 |
|
| 2210 |
.. versionchanged:: 3.13 |
| 2211 |
|
| 2212 |
Support for default values was added. |
| 2213 |
|
| 2214 |
.. note:: |
| 2215 |
Only parameter specification variables defined in global scope can |
| 2216 |
be pickled. |
| 2217 |
|
| 2218 |
.. seealso:: |
| 2219 |
* :pep:`612` -- Parameter Specification Variables (the PEP which introduced |
| 2220 |
``ParamSpec`` and ``Concatenate``) |
| 2221 |
* :data:`Concatenate` |
| 2222 |
* :ref:`annotating-callables` |
| 2223 |
|
| 2224 |
.. class:: ParamSpecArgs |
| 2225 |
ParamSpecKwargs |
| 2226 |
|
| 2227 |
Arguments and keyword arguments attributes of a :class:`ParamSpec`. The |
| 2228 |
``P.args`` attribute of a ``ParamSpec`` is an instance of ``ParamSpecArgs``, |
| 2229 |
and ``P.kwargs`` is an instance of ``ParamSpecKwargs``. They are intended |
| 2230 |
for runtime introspection and have no special meaning to static type checkers. |
| 2231 |
|
| 2232 |
Calling :func:`get_origin` on either of these objects will return the |
| 2233 |
original ``ParamSpec``: |
| 2234 |
|
| 2235 |
.. doctest:: |
| 2236 |
|
| 2237 |
>>> from typing import ParamSpec, get_origin |
| 2238 |
>>> P = ParamSpec("P") |
| 2239 |
>>> get_origin(P.args) is P |
| 2240 |
True |
| 2241 |
>>> get_origin(P.kwargs) is P |
| 2242 |
True |
| 2243 |
|
| 2244 |
.. versionadded:: 3.10 |
| 2245 |
|
| 2246 |
|
| 2247 |
.. class:: TypeAliasType(name, value, *, type_params=()) |
| 2248 |
|
| 2249 |
The type of type aliases created through the :keyword:`type` statement. |
| 2250 |
|
| 2251 |
Example: |
| 2252 |
|
| 2253 |
.. doctest:: |
| 2254 |
|
| 2255 |
>>> type Alias = int |
| 2256 |
>>> type(Alias) |
| 2257 |
<class 'typing.TypeAliasType'> |
| 2258 |
|
| 2259 |
.. versionadded:: 3.12 |
| 2260 |
|
| 2261 |
.. attribute:: __name__ |
| 2262 |
|
| 2263 |
The name of the type alias: |
| 2264 |
|
| 2265 |
.. doctest:: |
| 2266 |
|
| 2267 |
>>> type Alias = int |
| 2268 |
>>> Alias.__name__ |
| 2269 |
'Alias' |
| 2270 |
|
| 2271 |
.. attribute:: __module__ |
| 2272 |
|
| 2273 |
The name of the module in which the type alias was defined:: |
| 2274 |
|
| 2275 |
>>> type Alias = int |
| 2276 |
>>> Alias.__module__ |
| 2277 |
'__main__' |
| 2278 |
|
| 2279 |
.. attribute:: __type_params__ |
| 2280 |
|
| 2281 |
The type parameters of the type alias, or an empty tuple if the alias is |
| 2282 |
not generic: |
| 2283 |
|
| 2284 |
.. doctest:: |
| 2285 |
|
| 2286 |
>>> type ListOrSet[T] = list[T] | set[T] |
| 2287 |
>>> ListOrSet.__type_params__ |
| 2288 |
(T,) |
| 2289 |
>>> type NotGeneric = int |
| 2290 |
>>> NotGeneric.__type_params__ |
| 2291 |
() |
| 2292 |
|
| 2293 |
.. attribute:: __value__ |
| 2294 |
|
| 2295 |
The type alias's value. This is :ref:`lazily evaluated <lazy-evaluation>`, |
| 2296 |
so names used in the definition of the alias are not resolved until the |
| 2297 |
``__value__`` attribute is accessed: |
| 2298 |
|
| 2299 |
.. doctest:: |
| 2300 |
|
| 2301 |
>>> type Mutually = Recursive |
| 2302 |
>>> type Recursive = Mutually |
| 2303 |
>>> Mutually |
| 2304 |
Mutually |
| 2305 |
>>> Recursive |
| 2306 |
Recursive |
| 2307 |
>>> Mutually.__value__ |
| 2308 |
Recursive |
| 2309 |
>>> Recursive.__value__ |
| 2310 |
Mutually |
| 2311 |
|
| 2312 |
.. method:: evaluate_value |
| 2313 |
|
| 2314 |
An :term:`evaluate function` corresponding to the :attr:`__value__` attribute. |
| 2315 |
When called directly, this method supports only the :attr:`~annotationlib.Format.VALUE` |
| 2316 |
format, which is equivalent to accessing the :attr:`__value__` attribute directly, |
| 2317 |
but the method object can be passed to :func:`annotationlib.call_evaluate_function` |
| 2318 |
to evaluate the value in a different format: |
| 2319 |
|
| 2320 |
.. doctest:: |
| 2321 |
|
| 2322 |
>>> type Alias = undefined |
| 2323 |
>>> Alias.__value__ |
| 2324 |
Traceback (most recent call last): |
| 2325 |
... |
| 2326 |
NameError: name 'undefined' is not defined |
| 2327 |
>>> from annotationlib import Format, call_evaluate_function |
| 2328 |
>>> Alias.evaluate_value(Format.VALUE) |
| 2329 |
Traceback (most recent call last): |
| 2330 |
... |
| 2331 |
NameError: name 'undefined' is not defined |
| 2332 |
>>> call_evaluate_function(Alias.evaluate_value, Format.FORWARDREF) |
| 2333 |
ForwardRef('undefined') |
| 2334 |
|
| 2335 |
.. versionadded:: 3.14 |
| 2336 |
|
| 2337 |
.. rubric:: Unpacking |
| 2338 |
|
| 2339 |
Type aliases support star unpacking using the ``*Alias`` syntax. |
| 2340 |
This is equivalent to using ``Unpack[Alias]`` directly: |
| 2341 |
|
| 2342 |
.. doctest:: |
| 2343 |
|
| 2344 |
>>> type Alias = tuple[int, str] |
| 2345 |
>>> type Unpacked = tuple[bool, *Alias] |
| 2346 |
>>> Unpacked.__value__ |
| 2347 |
tuple[bool, typing.Unpack[Alias]] |
| 2348 |
|
| 2349 |
.. versionadded:: 3.14 |
| 2350 |
|
| 2351 |
|
| 2352 |
Other special directives |
| 2353 |
"""""""""""""""""""""""" |
| 2354 |
|
| 2355 |
These functions and classes should not be used directly as annotations. |
| 2356 |
Their intended purpose is to be building blocks for creating and declaring |
| 2357 |
types. |
| 2358 |
|
| 2359 |
.. class:: NamedTuple |
| 2360 |
|
| 2361 |
Typed version of :func:`collections.namedtuple`. |
| 2362 |
|
| 2363 |
Usage:: |
| 2364 |
|
| 2365 |
class Employee(NamedTuple): |
| 2366 |
name: str |
| 2367 |
id: int |
| 2368 |
|
| 2369 |
This is equivalent to:: |
| 2370 |
|
| 2371 |
Employee = collections.namedtuple('Employee', ['name', 'id']) |
| 2372 |
|
| 2373 |
To give a field a default value, you can assign to it in the class body:: |
| 2374 |
|
| 2375 |
class Employee(NamedTuple): |
| 2376 |
name: str |
| 2377 |
id: int = 3 |
| 2378 |
|
| 2379 |
employee = Employee('Guido') |
| 2380 |
assert employee.id == 3 |
| 2381 |
|
| 2382 |
Fields with a default value must come after any fields without a default. |
| 2383 |
|
| 2384 |
The types for each field name can be retrieved by calling |
| 2385 |
:func:`annotationlib.get_annotations` on the resulting class. (The field |
| 2386 |
names are in the ``_fields`` attribute and the default values are in the |
| 2387 |
``_field_defaults`` attribute, both of which are part of the :func:`~collections.namedtuple` |
| 2388 |
API.) |
| 2389 |
|
| 2390 |
``NamedTuple`` subclasses can also have docstrings and methods:: |
| 2391 |
|
| 2392 |
class Employee(NamedTuple): |
| 2393 |
"""Represents an employee.""" |
| 2394 |
name: str |
| 2395 |
id: int = 3 |
| 2396 |
|
| 2397 |
def __repr__(self) -> str: |
| 2398 |
return f'<Employee {self.name}, id={self.id}>' |
| 2399 |
|
| 2400 |
``NamedTuple`` subclasses can be generic:: |
| 2401 |
|
| 2402 |
class Group[T](NamedTuple): |
| 2403 |
key: T |
| 2404 |
group: list[T] |
| 2405 |
|
| 2406 |
Backward-compatible usage:: |
| 2407 |
|
| 2408 |
# For creating a generic NamedTuple on Python 3.11 |
| 2409 |
T = TypeVar("T") |
| 2410 |
|
| 2411 |
class Group(NamedTuple, Generic[T]): |
| 2412 |
key: T |
| 2413 |
group: list[T] |
| 2414 |
|
| 2415 |
# A functional syntax is also supported |
| 2416 |
Employee = NamedTuple('Employee', [('name', str), ('id', int)]) |
| 2417 |
|
| 2418 |
.. versionchanged:: 3.6 |
| 2419 |
Added support for :pep:`526` variable annotation syntax. |
| 2420 |
|
| 2421 |
.. versionchanged:: 3.6.1 |
| 2422 |
Added support for default values, methods, and docstrings. |
| 2423 |
|
| 2424 |
.. versionchanged:: 3.8 |
| 2425 |
The ``_field_types`` and ``__annotations__`` attributes are |
| 2426 |
now regular dictionaries instead of instances of ``OrderedDict``. |
| 2427 |
|
| 2428 |
.. versionchanged:: 3.9 |
| 2429 |
Removed the ``_field_types`` attribute in favor of the more |
| 2430 |
standard ``__annotations__`` attribute which has the same information. |
| 2431 |
|
| 2432 |
.. versionchanged:: 3.9 |
| 2433 |
``NamedTuple`` is now a function rather than a class. |
| 2434 |
It can still be used as a class base, as described above. |
| 2435 |
|
| 2436 |
.. versionchanged:: 3.11 |
| 2437 |
Added support for generic namedtuples. |
| 2438 |
|
| 2439 |
.. versionchanged:: 3.14 |
| 2440 |
Using :func:`super` (and the ``__class__`` :term:`closure variable`) in methods of ``NamedTuple`` subclasses |
| 2441 |
is unsupported and causes a :class:`TypeError`. |
| 2442 |
|
| 2443 |
.. deprecated-removed:: 3.13 3.15 |
| 2444 |
The undocumented keyword argument syntax for creating NamedTuple classes |
| 2445 |
(``NT = NamedTuple("NT", x=int)``) is deprecated, and will be disallowed |
| 2446 |
in 3.15. Use the class-based syntax or the functional syntax instead. |
| 2447 |
|
| 2448 |
.. deprecated-removed:: 3.13 3.15 |
| 2449 |
When using the functional syntax to create a NamedTuple class, failing to |
| 2450 |
pass a value to the 'fields' parameter (``NT = NamedTuple("NT")``) is |
| 2451 |
deprecated. Passing ``None`` to the 'fields' parameter |
| 2452 |
(``NT = NamedTuple("NT", None)``) is also deprecated. Both will be |
| 2453 |
disallowed in Python 3.15. To create a NamedTuple class with 0 fields, |
| 2454 |
use ``class NT(NamedTuple): pass`` or ``NT = NamedTuple("NT", [])``. |
| 2455 |
|
| 2456 |
.. class:: NewType(name, tp) |
| 2457 |
|
| 2458 |
Helper class to create low-overhead :ref:`distinct types <distinct>`. |
| 2459 |
|
| 2460 |
A ``NewType`` is considered a distinct type by a type checker. At runtime, |
| 2461 |
however, calling a ``NewType`` returns its argument unchanged. |
| 2462 |
|
| 2463 |
Usage:: |
| 2464 |
|
| 2465 |
UserId = NewType('UserId', int) # Declare the NewType "UserId" |
| 2466 |
first_user = UserId(1) # "UserId" returns the argument unchanged at runtime |
| 2467 |
|
| 2468 |
.. attribute:: __module__ |
| 2469 |
|
| 2470 |
The name of the module in which the new type is defined. |
| 2471 |
|
| 2472 |
.. attribute:: __name__ |
| 2473 |
|
| 2474 |
The name of the new type. |
| 2475 |
|
| 2476 |
.. attribute:: __supertype__ |
| 2477 |
|
| 2478 |
The type that the new type is based on. |
| 2479 |
|
| 2480 |
.. versionadded:: 3.5.2 |
| 2481 |
|
| 2482 |
.. versionchanged:: 3.10 |
| 2483 |
``NewType`` is now a class rather than a function. |
| 2484 |
|
| 2485 |
.. class:: Protocol(Generic) |
| 2486 |
|
| 2487 |
Base class for protocol classes. |
| 2488 |
|
| 2489 |
Protocol classes are defined like this:: |
| 2490 |
|
| 2491 |
class Proto(Protocol): |
| 2492 |
def meth(self) -> int: |
| 2493 |
... |
| 2494 |
|
| 2495 |
Such classes are primarily used with static type checkers that recognize |
| 2496 |
structural subtyping (static duck-typing), for example:: |
| 2497 |
|
| 2498 |
class C: |
| 2499 |
def meth(self) -> int: |
| 2500 |
return 0 |
| 2501 |
|
| 2502 |
def func(x: Proto) -> int: |
| 2503 |
return x.meth() |
| 2504 |
|
| 2505 |
func(C()) # Passes static type check |
| 2506 |
|
| 2507 |
See :pep:`544` for more details. Protocol classes decorated with |
| 2508 |
:func:`runtime_checkable` (described later) act as simple-minded runtime |
| 2509 |
protocols that check only the presence of given attributes, ignoring their |
| 2510 |
type signatures. Protocol classes without this decorator cannot be used |
| 2511 |
as the second argument to :func:`isinstance` or :func:`issubclass`. |
| 2512 |
|
| 2513 |
Protocol classes can be generic, for example:: |
| 2514 |
|
| 2515 |
class GenProto[T](Protocol): |
| 2516 |
def meth(self) -> T: |
| 2517 |
... |
| 2518 |
|
| 2519 |
In code that needs to be compatible with Python 3.11 or older, generic |
| 2520 |
Protocols can be written as follows:: |
| 2521 |
|
| 2522 |
T = TypeVar("T") |
| 2523 |
|
| 2524 |
class GenProto(Protocol[T]): |
| 2525 |
def meth(self) -> T: |
| 2526 |
... |
| 2527 |
|
| 2528 |
.. versionadded:: 3.8 |
| 2529 |
|
| 2530 |
.. decorator:: runtime_checkable |
| 2531 |
|
| 2532 |
Mark a protocol class as a runtime protocol. |
| 2533 |
|
| 2534 |
Such a protocol can be used with :func:`isinstance` and :func:`issubclass`. |
| 2535 |
This allows a simple-minded structural check, very similar to "one-trick ponies" |
| 2536 |
in :mod:`collections.abc` such as :class:`~collections.abc.Iterable`. For example:: |
| 2537 |
|
| 2538 |
@runtime_checkable |
| 2539 |
class Closable(Protocol): |
| 2540 |
def close(self): ... |
| 2541 |
|
| 2542 |
assert isinstance(open('/some/file'), Closable) |
| 2543 |
|
| 2544 |
@runtime_checkable |
| 2545 |
class Named(Protocol): |
| 2546 |
name: str |
| 2547 |
|
| 2548 |
import threading |
| 2549 |
assert isinstance(threading.Thread(name='Bob'), Named) |
| 2550 |
|
| 2551 |
This decorator raises :exc:`TypeError` when applied to a non-protocol class. |
| 2552 |
|
| 2553 |
.. note:: |
| 2554 |
|
| 2555 |
:func:`!runtime_checkable` will check only the presence of the required |
| 2556 |
methods or attributes, not their type signatures or types. |
| 2557 |
For example, :class:`ssl.SSLObject` |
| 2558 |
is a class, therefore it passes an :func:`issubclass` |
| 2559 |
check against :ref:`Callable <annotating-callables>`. However, the |
| 2560 |
``ssl.SSLObject.__init__`` method exists only to raise a |
| 2561 |
:exc:`TypeError` with a more informative message, therefore making |
| 2562 |
it impossible to call (instantiate) :class:`ssl.SSLObject`. |
| 2563 |
|
| 2564 |
.. note:: |
| 2565 |
|
| 2566 |
An :func:`isinstance` check against a runtime-checkable protocol can be |
| 2567 |
surprisingly slow compared to an ``isinstance()`` check against |
| 2568 |
a non-protocol class. Consider using alternative idioms such as |
| 2569 |
:func:`hasattr` calls for structural checks in performance-sensitive |
| 2570 |
code. |
| 2571 |
|
| 2572 |
.. versionadded:: 3.8 |
| 2573 |
|
| 2574 |
.. versionchanged:: 3.12 |
| 2575 |
The internal implementation of :func:`isinstance` checks against |
| 2576 |
runtime-checkable protocols now uses :func:`inspect.getattr_static` |
| 2577 |
to look up attributes (previously, :func:`hasattr` was used). |
| 2578 |
As a result, some objects which used to be considered instances |
| 2579 |
of a runtime-checkable protocol may no longer be considered instances |
| 2580 |
of that protocol on Python 3.12+, and vice versa. |
| 2581 |
Most users are unlikely to be affected by this change. |
| 2582 |
|
| 2583 |
.. versionchanged:: 3.12 |
| 2584 |
The members of a runtime-checkable protocol are now considered "frozen" |
| 2585 |
at runtime as soon as the class has been created. Monkey-patching |
| 2586 |
attributes onto a runtime-checkable protocol will still work, but will |
| 2587 |
have no impact on :func:`isinstance` checks comparing objects to the |
| 2588 |
protocol. See :ref:`What's new in Python 3.12 <whatsnew-typing-py312>` |
| 2589 |
for more details. |
| 2590 |
|
| 2591 |
|
| 2592 |
.. class:: TypedDict(dict) |
| 2593 |
|
| 2594 |
Special construct to add type hints to a dictionary. |
| 2595 |
At runtime ":class:`!TypedDict` instances" are simply :class:`dicts <dict>`. |
| 2596 |
|
| 2597 |
``TypedDict`` declares a dictionary type that expects all of its |
| 2598 |
instances to have a certain set of keys, where each key is |
| 2599 |
associated with a value of a consistent type. This expectation |
| 2600 |
is not checked at runtime but is only enforced by type checkers. |
| 2601 |
Usage:: |
| 2602 |
|
| 2603 |
class Point2D(TypedDict): |
| 2604 |
x: int |
| 2605 |
y: int |
| 2606 |
label: str |
| 2607 |
|
| 2608 |
a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK |
| 2609 |
b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check |
| 2610 |
|
| 2611 |
assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first') |
| 2612 |
|
| 2613 |
An alternative way to create a ``TypedDict`` is by using |
| 2614 |
function-call syntax. The second argument must be a literal :class:`dict`:: |
| 2615 |
|
| 2616 |
Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) |
| 2617 |
|
| 2618 |
This functional syntax allows defining keys which are not valid |
| 2619 |
:ref:`identifiers <identifiers>`, for example because they are |
| 2620 |
keywords or contain hyphens, or when key names must not be |
| 2621 |
:ref:`mangled <private-name-mangling>` like regular private names:: |
| 2622 |
|
| 2623 |
# raises SyntaxError |
| 2624 |
class Point2D(TypedDict): |
| 2625 |
in: int # 'in' is a keyword |
| 2626 |
x-y: int # name with hyphens |
| 2627 |
|
| 2628 |
class Definition(TypedDict): |
| 2629 |
__schema: str # mangled to `_Definition__schema` |
| 2630 |
|
| 2631 |
# OK, functional syntax |
| 2632 |
Point2D = TypedDict('Point2D', {'in': int, 'x-y': int}) |
| 2633 |
Definition = TypedDict('Definition', {'__schema': str}) # not mangled |
| 2634 |
|
| 2635 |
By default, all keys must be present in a ``TypedDict``. It is possible to |
| 2636 |
mark individual keys as non-required using :data:`NotRequired`:: |
| 2637 |
|
| 2638 |
class Point2D(TypedDict): |
| 2639 |
x: int |
| 2640 |
y: int |
| 2641 |
label: NotRequired[str] |
| 2642 |
|
| 2643 |
# Alternative syntax |
| 2644 |
Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': NotRequired[str]}) |
| 2645 |
|
| 2646 |
This means that a ``Point2D`` ``TypedDict`` can have the ``label`` |
| 2647 |
key omitted. |
| 2648 |
|
| 2649 |
It is also possible to mark all keys as non-required by default |
| 2650 |
by specifying a totality of ``False``:: |
| 2651 |
|
| 2652 |
class Point2D(TypedDict, total=False): |
| 2653 |
x: int |
| 2654 |
y: int |
| 2655 |
|
| 2656 |
# Alternative syntax |
| 2657 |
Point2D = TypedDict('Point2D', {'x': int, 'y': int}, total=False) |
| 2658 |
|
| 2659 |
This means that a ``Point2D`` ``TypedDict`` can have any of the keys |
| 2660 |
omitted. A type checker is only expected to support a literal ``False`` or |
| 2661 |
``True`` as the value of the ``total`` argument. ``True`` is the default, |
| 2662 |
and makes all items defined in the class body required. |
| 2663 |
|
| 2664 |
Individual keys of a ``total=False`` ``TypedDict`` can be marked as |
| 2665 |
required using :data:`Required`:: |
| 2666 |
|
| 2667 |
class Point2D(TypedDict, total=False): |
| 2668 |
x: Required[int] |
| 2669 |
y: Required[int] |
| 2670 |
label: str |
| 2671 |
|
| 2672 |
# Alternative syntax |
| 2673 |
Point2D = TypedDict('Point2D', { |
| 2674 |
'x': Required[int], |
| 2675 |
'y': Required[int], |
| 2676 |
'label': str |
| 2677 |
}, total=False) |
| 2678 |
|
| 2679 |
It is possible for a ``TypedDict`` type to inherit from one or more other ``TypedDict`` types |
| 2680 |
using the class-based syntax. |
| 2681 |
Usage:: |
| 2682 |
|
| 2683 |
class Point3D(Point2D): |
| 2684 |
z: int |
| 2685 |
|
| 2686 |
``Point3D`` has three items: ``x``, ``y`` and ``z``. It is equivalent to this |
| 2687 |
definition:: |
| 2688 |
|
| 2689 |
class Point3D(TypedDict): |
| 2690 |
x: int |
| 2691 |
y: int |
| 2692 |
z: int |
| 2693 |
|
| 2694 |
A ``TypedDict`` cannot inherit from a non-\ ``TypedDict`` class, |
| 2695 |
except for :class:`Generic`. For example:: |
| 2696 |
|
| 2697 |
class X(TypedDict): |
| 2698 |
x: int |
| 2699 |
|
| 2700 |
class Y(TypedDict): |
| 2701 |
y: int |
| 2702 |
|
| 2703 |
class Z(object): pass # A non-TypedDict class |
| 2704 |
|
| 2705 |
class XY(X, Y): pass # OK |
| 2706 |
|
| 2707 |
class XZ(X, Z): pass # raises TypeError |
| 2708 |
|
| 2709 |
A ``TypedDict`` can be generic:: |
| 2710 |
|
| 2711 |
class Group[T](TypedDict): |
| 2712 |
key: T |
| 2713 |
group: list[T] |
| 2714 |
|
| 2715 |
To create a generic ``TypedDict`` that is compatible with Python 3.11 |
| 2716 |
or lower, inherit from :class:`Generic` explicitly: |
| 2717 |
|
| 2718 |
.. testcode:: |
| 2719 |
|
| 2720 |
T = TypeVar("T") |
| 2721 |
|
| 2722 |
class Group(TypedDict, Generic[T]): |
| 2723 |
key: T |
| 2724 |
group: list[T] |
| 2725 |
|
| 2726 |
A ``TypedDict`` can be introspected via :func:`annotationlib.get_annotations` |
| 2727 |
(see :ref:`annotations-howto` for more information on annotations best practices) |
| 2728 |
and the following attributes: |
| 2729 |
|
| 2730 |
.. attribute:: __total__ |
| 2731 |
|
| 2732 |
``Point2D.__total__`` gives the value of the ``total`` argument. |
| 2733 |
Example: |
| 2734 |
|
| 2735 |
.. doctest:: |
| 2736 |
|
| 2737 |
>>> from typing import TypedDict |
| 2738 |
>>> class Point2D(TypedDict): pass |
| 2739 |
>>> Point2D.__total__ |
| 2740 |
True |
| 2741 |
>>> class Point2D(TypedDict, total=False): pass |
| 2742 |
>>> Point2D.__total__ |
| 2743 |
False |
| 2744 |
>>> class Point3D(Point2D): pass |
| 2745 |
>>> Point3D.__total__ |
| 2746 |
True |
| 2747 |
|
| 2748 |
This attribute reflects *only* the value of the ``total`` argument |
| 2749 |
to the current ``TypedDict`` class, not whether the class is semantically |
| 2750 |
total. For example, a ``TypedDict`` with ``__total__`` set to ``True`` may |
| 2751 |
have keys marked with :data:`NotRequired`, or it may inherit from another |
| 2752 |
``TypedDict`` with ``total=False``. Therefore, it is generally better to use |
| 2753 |
:attr:`__required_keys__` and :attr:`__optional_keys__` for introspection. |
| 2754 |
|
| 2755 |
.. attribute:: __required_keys__ |
| 2756 |
|
| 2757 |
.. versionadded:: 3.9 |
| 2758 |
|
| 2759 |
.. attribute:: __optional_keys__ |
| 2760 |
|
| 2761 |
``Point2D.__required_keys__`` and ``Point2D.__optional_keys__`` return |
| 2762 |
:class:`frozenset` objects containing required and non-required keys, respectively. |
| 2763 |
|
| 2764 |
Keys marked with :data:`Required` will always appear in ``__required_keys__`` |
| 2765 |
and keys marked with :data:`NotRequired` will always appear in ``__optional_keys__``. |
| 2766 |
|
| 2767 |
For backwards compatibility with Python 3.10 and below, |
| 2768 |
it is also possible to use inheritance to declare both required and |
| 2769 |
non-required keys in the same ``TypedDict``. This is done by declaring a |
| 2770 |
``TypedDict`` with one value for the ``total`` argument and then |
| 2771 |
inheriting from it in another ``TypedDict`` with a different value for |
| 2772 |
``total``: |
| 2773 |
|
| 2774 |
.. doctest:: |
| 2775 |
|
| 2776 |
>>> class Point2D(TypedDict, total=False): |
| 2777 |
... x: int |
| 2778 |
... y: int |
| 2779 |
... |
| 2780 |
>>> class Point3D(Point2D): |
| 2781 |
... z: int |
| 2782 |
... |
| 2783 |
>>> Point3D.__required_keys__ == frozenset({'z'}) |
| 2784 |
True |
| 2785 |
>>> Point3D.__optional_keys__ == frozenset({'x', 'y'}) |
| 2786 |
True |
| 2787 |
|
| 2788 |
.. versionadded:: 3.9 |
| 2789 |
|
| 2790 |
.. note:: |
| 2791 |
|
| 2792 |
If ``from __future__ import annotations`` is used or if annotations |
| 2793 |
are given as strings, annotations are not evaluated when the |
| 2794 |
``TypedDict`` is defined. Therefore, the runtime introspection that |
| 2795 |
``__required_keys__`` and ``__optional_keys__`` rely on may not work |
| 2796 |
properly, and the values of the attributes may be incorrect. |
| 2797 |
|
| 2798 |
Support for :data:`ReadOnly` is reflected in the following attributes: |
| 2799 |
|
| 2800 |
.. attribute:: __readonly_keys__ |
| 2801 |
|
| 2802 |
A :class:`frozenset` containing the names of all read-only keys. Keys |
| 2803 |
are read-only if they carry the :data:`ReadOnly` qualifier. |
| 2804 |
|
| 2805 |
.. versionadded:: 3.13 |
| 2806 |
|
| 2807 |
.. attribute:: __mutable_keys__ |
| 2808 |
|
| 2809 |
A :class:`frozenset` containing the names of all mutable keys. Keys |
| 2810 |
are mutable if they do not carry the :data:`ReadOnly` qualifier. |
| 2811 |
|
| 2812 |
.. versionadded:: 3.13 |
| 2813 |
|
| 2814 |
See the `TypedDict <https://typing.python.org/en/latest/spec/typeddict.html#typeddict>`_ section in the typing documentation for more examples and detailed rules. |
| 2815 |
|
| 2816 |
.. versionadded:: 3.8 |
| 2817 |
|
| 2818 |
.. versionchanged:: 3.9 |
| 2819 |
``TypedDict`` is now a function rather than a class. |
| 2820 |
It can still be used as a class base, as described above. |
| 2821 |
|
| 2822 |
.. versionchanged:: 3.11 |
| 2823 |
Added support for marking individual keys as :data:`Required` or :data:`NotRequired`. |
| 2824 |
See :pep:`655`. |
| 2825 |
|
| 2826 |
.. versionchanged:: 3.11 |
| 2827 |
Added support for generic ``TypedDict``\ s. |
| 2828 |
|
| 2829 |
.. versionchanged:: 3.13 |
| 2830 |
Removed support for the keyword-argument method of creating ``TypedDict``\ s. |
| 2831 |
|
| 2832 |
.. versionchanged:: 3.13 |
| 2833 |
Support for the :data:`ReadOnly` qualifier was added. |
| 2834 |
|
| 2835 |
.. deprecated-removed:: 3.13 3.15 |
| 2836 |
When using the functional syntax to create a TypedDict class, failing to |
| 2837 |
pass a value to the 'fields' parameter (``TD = TypedDict("TD")``) is |
| 2838 |
deprecated. Passing ``None`` to the 'fields' parameter |
| 2839 |
(``TD = TypedDict("TD", None)``) is also deprecated. Both will be |
| 2840 |
disallowed in Python 3.15. To create a TypedDict class with 0 fields, |
| 2841 |
use ``class TD(TypedDict): pass`` or ``TD = TypedDict("TD", {})``. |
| 2842 |
|
| 2843 |
Protocols |
| 2844 |
--------- |
| 2845 |
|
| 2846 |
The following protocols are provided by the :mod:`!typing` module. All are decorated |
| 2847 |
with :deco:`runtime_checkable`. |
| 2848 |
|
| 2849 |
.. class:: SupportsAbs |
| 2850 |
|
| 2851 |
A protocol with one abstract method ``__abs__`` that is covariant |
| 2852 |
in its return type. |
| 2853 |
|
| 2854 |
.. class:: SupportsBytes |
| 2855 |
|
| 2856 |
A protocol with one abstract method ``__bytes__``. |
| 2857 |
|
| 2858 |
.. class:: SupportsComplex |
| 2859 |
|
| 2860 |
A protocol with one abstract method ``__complex__``. |
| 2861 |
|
| 2862 |
.. class:: SupportsFloat |
| 2863 |
|
| 2864 |
A protocol with one abstract method ``__float__``. |
| 2865 |
|
| 2866 |
.. class:: SupportsIndex |
| 2867 |
|
| 2868 |
A protocol with one abstract method ``__index__``. |
| 2869 |
|
| 2870 |
.. versionadded:: 3.8 |
| 2871 |
|
| 2872 |
.. class:: SupportsInt |
| 2873 |
|
| 2874 |
A protocol with one abstract method ``__int__``. |
| 2875 |
|
| 2876 |
.. class:: SupportsRound |
| 2877 |
|
| 2878 |
A protocol with one abstract method ``__round__`` |
| 2879 |
that is covariant in its return type. |
| 2880 |
|
| 2881 |
.. _typing-io: |
| 2882 |
|
| 2883 |
ABCs and Protocols for working with I/O |
| 2884 |
--------------------------------------- |
| 2885 |
|
| 2886 |
.. class:: IO[AnyStr] |
| 2887 |
TextIO |
| 2888 |
BinaryIO |
| 2889 |
|
| 2890 |
Generic class ``IO[AnyStr]`` and its subclasses ``TextIO(IO[str])`` |
| 2891 |
and ``BinaryIO(IO[bytes])`` |
| 2892 |
represent the types of I/O streams such as returned by |
| 2893 |
:func:`open`. Please note that these classes are not protocols, and |
| 2894 |
their interface is fairly broad. |
| 2895 |
|
| 2896 |
The protocols :class:`io.Reader` and :class:`io.Writer` offer a simpler |
| 2897 |
alternative for argument types, when only the ``read()`` or ``write()`` |
| 2898 |
methods are accessed, respectively:: |
| 2899 |
|
| 2900 |
def read_and_write(reader: Reader[str], writer: Writer[bytes]): |
| 2901 |
data = reader.read() |
| 2902 |
writer.write(data.encode()) |
| 2903 |
|
| 2904 |
Also consider using :class:`collections.abc.Iterable` for iterating over |
| 2905 |
the lines of an input stream:: |
| 2906 |
|
| 2907 |
def read_config(stream: Iterable[str]): |
| 2908 |
for line in stream: |
| 2909 |
... |
| 2910 |
|
| 2911 |
Functions and decorators |
| 2912 |
------------------------ |
| 2913 |
|
| 2914 |
.. function:: cast(typ, val) |
| 2915 |
|
| 2916 |
Cast a value to a type. |
| 2917 |
|
| 2918 |
This returns the value unchanged. To the type checker this |
| 2919 |
signals that the return value has the designated type, but at |
| 2920 |
runtime we intentionally don't check anything (we want this |
| 2921 |
to be as fast as possible). |
| 2922 |
|
| 2923 |
.. function:: assert_type(val, typ, /) |
| 2924 |
|
| 2925 |
Ask a static type checker to confirm that *val* has an inferred type of *typ*. |
| 2926 |
|
| 2927 |
At runtime this does nothing: it returns the first argument unchanged with no |
| 2928 |
checks or side effects, no matter the actual type of the argument. |
| 2929 |
|
| 2930 |
When a static type checker encounters a call to ``assert_type()``, it |
| 2931 |
emits an error if the value is not of the specified type:: |
| 2932 |
|
| 2933 |
def greet(name: str) -> None: |
| 2934 |
assert_type(name, str) # OK, inferred type of `name` is `str` |
| 2935 |
assert_type(name, int) # type checker error |
| 2936 |
|
| 2937 |
This function is useful for ensuring the type checker's understanding of a |
| 2938 |
script is in line with the developer's intentions:: |
| 2939 |
|
| 2940 |
def complex_function(arg: object): |
| 2941 |
# Do some complex type-narrowing logic, |
| 2942 |
# after which we hope the inferred type will be `int` |
| 2943 |
... |
| 2944 |
# Test whether the type checker correctly understands our function |
| 2945 |
assert_type(arg, int) |
| 2946 |
|
| 2947 |
.. versionadded:: 3.11 |
| 2948 |
|
| 2949 |
.. function:: assert_never(arg, /) |
| 2950 |
|
| 2951 |
Ask a static type checker to confirm that a line of code is unreachable. |
| 2952 |
|
| 2953 |
Example:: |
| 2954 |
|
| 2955 |
def int_or_str(arg: int | str) -> None: |
| 2956 |
match arg: |
| 2957 |
case int(): |
| 2958 |
print("It's an int") |
| 2959 |
case str(): |
| 2960 |
print("It's a str") |
| 2961 |
case _ as unreachable: |
| 2962 |
assert_never(unreachable) |
| 2963 |
|
| 2964 |
Here, the annotations allow the type checker to infer that the |
| 2965 |
last case can never execute, because ``arg`` is either |
| 2966 |
an :class:`int` or a :class:`str`, and both options are covered by |
| 2967 |
earlier cases. |
| 2968 |
|
| 2969 |
If a type checker finds that a call to ``assert_never()`` is |
| 2970 |
reachable, it will emit an error. For example, if the type annotation |
| 2971 |
for ``arg`` was instead ``int | str | float``, the type checker would |
| 2972 |
emit an error pointing out that ``unreachable`` is of type :class:`float`. |
| 2973 |
For a call to ``assert_never`` to pass type checking, the inferred type of |
| 2974 |
the argument passed in must be the bottom type, :data:`Never`, and nothing |
| 2975 |
else. |
| 2976 |
|
| 2977 |
At runtime, this throws an exception when called. |
| 2978 |
|
| 2979 |
.. seealso:: |
| 2980 |
`Unreachable Code and Exhaustiveness Checking |
| 2981 |
<https://typing.python.org/en/latest/guides/unreachable.html>`__ has more |
| 2982 |
information about exhaustiveness checking with static typing. |
| 2983 |
|
| 2984 |
.. versionadded:: 3.11 |
| 2985 |
|
| 2986 |
.. function:: reveal_type(obj, /) |
| 2987 |
|
| 2988 |
Ask a static type checker to reveal the inferred type of an expression. |
| 2989 |
|
| 2990 |
When a static type checker encounters a call to this function, |
| 2991 |
it emits a diagnostic with the inferred type of the argument. For example:: |
| 2992 |
|
| 2993 |
x: int = 1 |
| 2994 |
reveal_type(x) # Revealed type is "builtins.int" |
| 2995 |
|
| 2996 |
This can be useful when you want to debug how your type checker |
| 2997 |
handles a particular piece of code. |
| 2998 |
|
| 2999 |
At runtime, this function prints the runtime type of its argument to |
| 3000 |
:data:`sys.stderr` and returns the argument unchanged (allowing the call to |
| 3001 |
be used within an expression):: |
| 3002 |
|
| 3003 |
x = reveal_type(1) # prints "Runtime type is int" |
| 3004 |
print(x) # prints "1" |
| 3005 |
|
| 3006 |
Note that the runtime type may be different from (more or less specific |
| 3007 |
than) the type statically inferred by a type checker. |
| 3008 |
|
| 3009 |
Most type checkers support ``reveal_type()`` anywhere, even if the |
| 3010 |
name is not imported from ``typing``. Importing the name from |
| 3011 |
``typing``, however, allows your code to run without runtime errors and |
| 3012 |
communicates intent more clearly. |
| 3013 |
|
| 3014 |
.. versionadded:: 3.11 |
| 3015 |
|
| 3016 |
.. decorator:: dataclass_transform(*, eq_default=True, order_default=False, \ |
| 3017 |
kw_only_default=False, frozen_default=False, \ |
| 3018 |
field_specifiers=(), **kwargs) |
| 3019 |
|
| 3020 |
Decorator to mark an object as providing |
| 3021 |
:func:`dataclass <dataclasses.dataclass>`-like behavior. |
| 3022 |
|
| 3023 |
``dataclass_transform`` may be used to |
| 3024 |
decorate a class, metaclass, or a function that is itself a decorator. |
| 3025 |
The presence of ``@dataclass_transform()`` tells a static type checker that the |
| 3026 |
decorated object performs runtime "magic" that |
| 3027 |
transforms a class in a similar way to |
| 3028 |
:deco:`dataclasses.dataclass`. |
| 3029 |
|
| 3030 |
Example usage with a decorator function: |
| 3031 |
|
| 3032 |
.. testcode:: |
| 3033 |
|
| 3034 |
@dataclass_transform() |
| 3035 |
def create_model[T](cls: type[T]) -> type[T]: |
| 3036 |
... |
| 3037 |
return cls |
| 3038 |
|
| 3039 |
@create_model |
| 3040 |
class CustomerModel: |
| 3041 |
id: int |
| 3042 |
name: str |
| 3043 |
|
| 3044 |
On a base class:: |
| 3045 |
|
| 3046 |
@dataclass_transform() |
| 3047 |
class ModelBase: ... |
| 3048 |
|
| 3049 |
class CustomerModel(ModelBase): |
| 3050 |
id: int |
| 3051 |
name: str |
| 3052 |
|
| 3053 |
On a metaclass:: |
| 3054 |
|
| 3055 |
@dataclass_transform() |
| 3056 |
class ModelMeta(type): ... |
| 3057 |
|
| 3058 |
class ModelBase(metaclass=ModelMeta): ... |
| 3059 |
|
| 3060 |
class CustomerModel(ModelBase): |
| 3061 |
id: int |
| 3062 |
name: str |
| 3063 |
|
| 3064 |
The ``CustomerModel`` classes defined above will |
| 3065 |
be treated by type checkers similarly to classes created with |
| 3066 |
:deco:`dataclasses.dataclass`. |
| 3067 |
For example, type checkers will assume these classes have |
| 3068 |
``__init__`` methods that accept ``id`` and ``name``. |
| 3069 |
|
| 3070 |
The decorated class, metaclass, or function may accept the following bool |
| 3071 |
arguments which type checkers will assume have the same effect as they |
| 3072 |
would have on the |
| 3073 |
:deco:`dataclasses.dataclass` decorator: ``init``, |
| 3074 |
``eq``, ``order``, ``unsafe_hash``, ``frozen``, ``match_args``, |
| 3075 |
``kw_only``, and ``slots``. It must be possible for the value of these |
| 3076 |
arguments (``True`` or ``False``) to be statically evaluated. |
| 3077 |
|
| 3078 |
The arguments to the ``dataclass_transform`` decorator can be used to |
| 3079 |
customize the default behaviors of the decorated class, metaclass, or |
| 3080 |
function: |
| 3081 |
|
| 3082 |
:param bool eq_default: |
| 3083 |
Indicates whether the ``eq`` parameter is assumed to be |
| 3084 |
``True`` or ``False`` if it is omitted by the caller. |
| 3085 |
Defaults to ``True``. |
| 3086 |
|
| 3087 |
:param bool order_default: |
| 3088 |
Indicates whether the ``order`` parameter is |
| 3089 |
assumed to be ``True`` or ``False`` if it is omitted by the caller. |
| 3090 |
Defaults to ``False``. |
| 3091 |
|
| 3092 |
:param bool kw_only_default: |
| 3093 |
Indicates whether the ``kw_only`` parameter is |
| 3094 |
assumed to be ``True`` or ``False`` if it is omitted by the caller. |
| 3095 |
Defaults to ``False``. |
| 3096 |
|
| 3097 |
:param bool frozen_default: |
| 3098 |
Indicates whether the ``frozen`` parameter is |
| 3099 |
assumed to be ``True`` or ``False`` if it is omitted by the caller. |
| 3100 |
Defaults to ``False``. |
| 3101 |
|
| 3102 |
.. versionadded:: 3.12 |
| 3103 |
|
| 3104 |
:param field_specifiers: |
| 3105 |
Specifies a static list of supported classes |
| 3106 |
or functions that describe fields, similar to :func:`dataclasses.field`. |
| 3107 |
Defaults to ``()``. |
| 3108 |
:type field_specifiers: tuple[Callable[..., Any], ...] |
| 3109 |
|
| 3110 |
:param Any \**kwargs: |
| 3111 |
Arbitrary other keyword arguments are accepted in order to allow for |
| 3112 |
possible future extensions. |
| 3113 |
|
| 3114 |
Type checkers recognize the following optional parameters on field |
| 3115 |
specifiers: |
| 3116 |
|
| 3117 |
.. list-table:: **Recognised parameters for field specifiers** |
| 3118 |
:header-rows: 1 |
| 3119 |
:widths: 20 80 |
| 3120 |
|
| 3121 |
* - Parameter name |
| 3122 |
- Description |
| 3123 |
* - ``init`` |
| 3124 |
- Indicates whether the field should be included in the |
| 3125 |
synthesized ``__init__`` method. If unspecified, ``init`` defaults to |
| 3126 |
``True``. |
| 3127 |
* - ``default`` |
| 3128 |
- Provides the default value for the field. |
| 3129 |
* - ``default_factory`` |
| 3130 |
- Provides a runtime callback that returns the |
| 3131 |
default value for the field. If neither ``default`` nor |
| 3132 |
``default_factory`` are specified, the field is assumed to have no |
| 3133 |
default value and must be provided a value when the class is |
| 3134 |
instantiated. |
| 3135 |
* - ``factory`` |
| 3136 |
- An alias for the ``default_factory`` parameter on field specifiers. |
| 3137 |
* - ``kw_only`` |
| 3138 |
- Indicates whether the field should be marked as |
| 3139 |
keyword-only. If ``True``, the field will be keyword-only. If |
| 3140 |
``False``, it will not be keyword-only. If unspecified, the value of |
| 3141 |
the ``kw_only`` parameter on the object decorated with |
| 3142 |
``dataclass_transform`` will be used, or if that is unspecified, the |
| 3143 |
value of ``kw_only_default`` on ``dataclass_transform`` will be used. |
| 3144 |
* - ``alias`` |
| 3145 |
- Provides an alternative name for the field. This alternative |
| 3146 |
name is used in the synthesized ``__init__`` method. |
| 3147 |
|
| 3148 |
At runtime, this decorator records its arguments in the |
| 3149 |
``__dataclass_transform__`` attribute on the decorated object. |
| 3150 |
It has no other runtime effect. |
| 3151 |
|
| 3152 |
See :pep:`681` for more details. |
| 3153 |
|
| 3154 |
.. versionadded:: 3.11 |
| 3155 |
|
| 3156 |
.. _overload: |
| 3157 |
|
| 3158 |
.. decorator:: overload |
| 3159 |
|
| 3160 |
Decorator for creating overloaded functions and methods. |
| 3161 |
|
| 3162 |
The ``@overload`` decorator allows describing functions and methods |
| 3163 |
that support multiple different combinations of argument types. A series |
| 3164 |
of ``@overload``-decorated definitions must be followed by exactly one |
| 3165 |
non-``@overload``-decorated definition (for the same function/method). |
| 3166 |
|
| 3167 |
``@overload``-decorated definitions are for the benefit of the |
| 3168 |
type checker only, since they will be overwritten by the |
| 3169 |
non-``@overload``-decorated definition. The non-``@overload``-decorated |
| 3170 |
definition, meanwhile, will be used at |
| 3171 |
runtime but should be ignored by a type checker. At runtime, calling |
| 3172 |
an ``@overload``-decorated function directly will raise |
| 3173 |
:exc:`NotImplementedError`. |
| 3174 |
|
| 3175 |
An example of overload that gives a more |
| 3176 |
precise type than can be expressed using a union or a type variable: |
| 3177 |
|
| 3178 |
.. testcode:: |
| 3179 |
|
| 3180 |
@overload |
| 3181 |
def process(response: None) -> None: |
| 3182 |
... |
| 3183 |
@overload |
| 3184 |
def process(response: int) -> tuple[int, str]: |
| 3185 |
... |
| 3186 |
@overload |
| 3187 |
def process(response: bytes) -> str: |
| 3188 |
... |
| 3189 |
def process(response): |
| 3190 |
... # actual implementation goes here |
| 3191 |
|
| 3192 |
See :pep:`484` for more details and comparison with other typing semantics. |
| 3193 |
|
| 3194 |
.. versionchanged:: 3.11 |
| 3195 |
Overloaded functions can now be introspected at runtime using |
| 3196 |
:func:`get_overloads`. |
| 3197 |
|
| 3198 |
|
| 3199 |
.. function:: get_overloads(func) |
| 3200 |
|
| 3201 |
Return a sequence of :deco:`overload`-decorated definitions for |
| 3202 |
*func*. |
| 3203 |
|
| 3204 |
*func* is the function object for the implementation of the |
| 3205 |
overloaded function. For example, given the definition of ``process`` in |
| 3206 |
the documentation for :deco:`overload`, |
| 3207 |
``get_overloads(process)`` will return a sequence of three function objects |
| 3208 |
for the three defined overloads. If called on a function with no overloads, |
| 3209 |
``get_overloads()`` returns an empty sequence. |
| 3210 |
|
| 3211 |
``get_overloads()`` can be used for introspecting an overloaded function at |
| 3212 |
runtime. |
| 3213 |
|
| 3214 |
.. versionadded:: 3.11 |
| 3215 |
|
| 3216 |
|
| 3217 |
.. function:: clear_overloads() |
| 3218 |
|
| 3219 |
Clear all registered overloads in the internal registry. |
| 3220 |
|
| 3221 |
This can be used to reclaim the memory used by the registry. |
| 3222 |
|
| 3223 |
.. versionadded:: 3.11 |
| 3224 |
|
| 3225 |
|
| 3226 |
.. decorator:: final |
| 3227 |
|
| 3228 |
Decorator to indicate final methods and final classes. |
| 3229 |
|
| 3230 |
Decorating a method with ``@final`` indicates to a type checker that the |
| 3231 |
method cannot be overridden in a subclass. Decorating a class with ``@final`` |
| 3232 |
indicates that it cannot be subclassed. |
| 3233 |
|
| 3234 |
For example:: |
| 3235 |
|
| 3236 |
class Base: |
| 3237 |
@final |
| 3238 |
def done(self) -> None: |
| 3239 |
... |
| 3240 |
class Sub(Base): |
| 3241 |
def done(self) -> None: # Error reported by type checker |
| 3242 |
... |
| 3243 |
|
| 3244 |
@final |
| 3245 |
class Leaf: |
| 3246 |
... |
| 3247 |
class Other(Leaf): # Error reported by type checker |
| 3248 |
... |
| 3249 |
|
| 3250 |
There is no runtime checking of these properties. See :pep:`591` for |
| 3251 |
more details. |
| 3252 |
|
| 3253 |
.. versionadded:: 3.8 |
| 3254 |
|
| 3255 |
.. versionchanged:: 3.11 |
| 3256 |
The decorator will now attempt to set a ``__final__`` attribute to ``True`` |
| 3257 |
on the decorated object. Thus, a check like |
| 3258 |
``if getattr(obj, "__final__", False)`` can be used at runtime |
| 3259 |
to determine whether an object ``obj`` has been marked as final. |
| 3260 |
If the decorated object does not support setting attributes, |
| 3261 |
the decorator returns the object unchanged without raising an exception. |
| 3262 |
|
| 3263 |
|
| 3264 |
.. decorator:: no_type_check |
| 3265 |
|
| 3266 |
Decorator to indicate that annotations are not type hints. |
| 3267 |
|
| 3268 |
This works as a class or function :term:`decorator`. With a class, it |
| 3269 |
applies recursively to all methods and classes defined in that class |
| 3270 |
(but not to methods defined in its superclasses or subclasses). Type |
| 3271 |
checkers will ignore all annotations in a function or class with this |
| 3272 |
decorator. |
| 3273 |
|
| 3274 |
``@no_type_check`` mutates the decorated object in place. |
| 3275 |
|
| 3276 |
.. decorator:: no_type_check_decorator |
| 3277 |
|
| 3278 |
Decorator to give another decorator the :func:`no_type_check` effect. |
| 3279 |
|
| 3280 |
This wraps the decorator with something that wraps the decorated |
| 3281 |
function in :func:`no_type_check`. |
| 3282 |
|
| 3283 |
.. deprecated-removed:: 3.13 3.15 |
| 3284 |
No type checker ever added support for ``@no_type_check_decorator``. It |
| 3285 |
is therefore deprecated, and will be removed in Python 3.15. |
| 3286 |
|
| 3287 |
.. decorator:: override |
| 3288 |
|
| 3289 |
Decorator to indicate that a method in a subclass is intended to override a |
| 3290 |
method or attribute in a superclass. |
| 3291 |
|
| 3292 |
Type checkers should emit an error if a method decorated with ``@override`` |
| 3293 |
does not, in fact, override anything. |
| 3294 |
This helps prevent bugs that may occur when a base class is changed without |
| 3295 |
an equivalent change to a child class. |
| 3296 |
|
| 3297 |
For example: |
| 3298 |
|
| 3299 |
.. testcode:: |
| 3300 |
|
| 3301 |
class Base: |
| 3302 |
def log_status(self) -> None: |
| 3303 |
... |
| 3304 |
|
| 3305 |
class Sub(Base): |
| 3306 |
@override |
| 3307 |
def log_status(self) -> None: # Okay: overrides Base.log_status |
| 3308 |
... |
| 3309 |
|
| 3310 |
@override |
| 3311 |
def done(self) -> None: # Error reported by type checker |
| 3312 |
... |
| 3313 |
|
| 3314 |
There is no runtime checking of this property. |
| 3315 |
|
| 3316 |
The decorator will attempt to set an ``__override__`` attribute to ``True`` on |
| 3317 |
the decorated object. Thus, a check like |
| 3318 |
``if getattr(obj, "__override__", False)`` can be used at runtime to determine |
| 3319 |
whether an object ``obj`` has been marked as an override. If the decorated object |
| 3320 |
does not support setting attributes, the decorator returns the object unchanged |
| 3321 |
without raising an exception. |
| 3322 |
|
| 3323 |
See :pep:`698` for more details. |
| 3324 |
|
| 3325 |
.. versionadded:: 3.12 |
| 3326 |
|
| 3327 |
|
| 3328 |
.. decorator:: type_check_only |
| 3329 |
|
| 3330 |
Decorator to mark a class or function as unavailable at runtime. |
| 3331 |
|
| 3332 |
This decorator is itself not available at runtime. It is mainly |
| 3333 |
intended to mark classes that are defined in type stub files if |
| 3334 |
an implementation returns an instance of a private class:: |
| 3335 |
|
| 3336 |
@type_check_only |
| 3337 |
class Response: # private or not available at runtime |
| 3338 |
code: int |
| 3339 |
def get_header(self, name: str) -> str: ... |
| 3340 |
|
| 3341 |
def fetch_response() -> Response: ... |
| 3342 |
|
| 3343 |
Note that returning instances of private classes is not recommended. |
| 3344 |
It is usually preferable to make such classes public. |
| 3345 |
|
| 3346 |
Introspection helpers |
| 3347 |
--------------------- |
| 3348 |
|
| 3349 |
.. function:: get_type_hints(obj, globalns=None, localns=None, include_extras=False, *, format=Format.VALUE) |
| 3350 |
|
| 3351 |
Return a dictionary containing type hints for a function, method, module, |
| 3352 |
class object, or other callable object. |
| 3353 |
|
| 3354 |
This is often the same as :func:`annotationlib.get_annotations`, but this |
| 3355 |
function makes the following changes to the annotations dictionary: |
| 3356 |
|
| 3357 |
* Forward references encoded as string literals or :class:`ForwardRef` |
| 3358 |
objects are handled by evaluating them in *globalns*, *localns*, and |
| 3359 |
(where applicable) *obj*'s :ref:`type parameter <type-params>` namespace. |
| 3360 |
If *globalns* or *localns* is not given, appropriate namespace |
| 3361 |
dictionaries are inferred from *obj*. |
| 3362 |
* ``None`` is replaced with :class:`types.NoneType`. |
| 3363 |
* If :deco:`no_type_check` has been applied to *obj*, an |
| 3364 |
empty dictionary is returned. |
| 3365 |
* If *obj* is a class ``C``, the function returns a dictionary that merges |
| 3366 |
annotations from ``C``'s base classes with those on ``C`` directly. This |
| 3367 |
is done by traversing :attr:`C.__mro__ <type.__mro__>` and iteratively |
| 3368 |
combining |
| 3369 |
:term:`annotations <variable annotation>` of each base class. Annotations |
| 3370 |
on classes appearing earlier in the :term:`method resolution order` always |
| 3371 |
take precedence over annotations on classes appearing later in the method |
| 3372 |
resolution order. |
| 3373 |
* The function recursively replaces all occurrences of |
| 3374 |
``Annotated[T, ...]``, ``Required[T]``, ``NotRequired[T]``, and ``ReadOnly[T]`` |
| 3375 |
with ``T``, unless *include_extras* is set to ``True`` (see |
| 3376 |
:class:`Annotated` for more information). |
| 3377 |
|
| 3378 |
.. caution:: |
| 3379 |
|
| 3380 |
This function may execute arbitrary code contained in annotations. |
| 3381 |
See :ref:`annotationlib-security` for more information. |
| 3382 |
|
| 3383 |
.. note:: |
| 3384 |
|
| 3385 |
If :attr:`Format.VALUE <annotationlib.Format.VALUE>` is used and any |
| 3386 |
forward references in the annotations of *obj* are not resolvable, a |
| 3387 |
:exc:`NameError` exception is raised. For example, this can happen |
| 3388 |
with names imported under :data:`if TYPE_CHECKING <TYPE_CHECKING>`. |
| 3389 |
More generally, any kind of exception can be raised if an annotation |
| 3390 |
contains invalid Python code. |
| 3391 |
|
| 3392 |
.. note:: |
| 3393 |
|
| 3394 |
Calling :func:`get_type_hints` on an instance is not supported. |
| 3395 |
To retrieve annotations for an instance, call |
| 3396 |
:func:`get_type_hints` on the instance's class instead |
| 3397 |
(for example, ``get_type_hints(type(obj))``). |
| 3398 |
|
| 3399 |
.. versionchanged:: 3.9 |
| 3400 |
Added ``include_extras`` parameter as part of :pep:`593`. |
| 3401 |
See the documentation on :data:`Annotated` for more information. |
| 3402 |
|
| 3403 |
.. versionchanged:: 3.11 |
| 3404 |
Previously, ``Optional[t]`` was added for function and method annotations |
| 3405 |
if a default value equal to ``None`` was set. |
| 3406 |
Now the annotation is returned unchanged. |
| 3407 |
|
| 3408 |
.. versionchanged:: 3.14 |
| 3409 |
Added the ``format`` parameter. See the documentation on |
| 3410 |
:func:`annotationlib.get_annotations` for more information. |
| 3411 |
|
| 3412 |
.. versionchanged:: 3.14 |
| 3413 |
Calling :func:`get_type_hints` on instances is no longer supported. |
| 3414 |
Some instances were accepted in earlier versions as an undocumented |
| 3415 |
implementation detail. |
| 3416 |
|
| 3417 |
.. function:: get_origin(tp) |
| 3418 |
|
| 3419 |
Get the unsubscripted version of a type: for a typing object of the form |
| 3420 |
``X[Y, Z, ...]`` return ``X``. |
| 3421 |
|
| 3422 |
If ``X`` is a typing-module alias for a builtin or |
| 3423 |
:mod:`collections` class, it will be normalized to the original class. |
| 3424 |
If ``X`` is an instance of :class:`ParamSpecArgs` or :class:`ParamSpecKwargs`, |
| 3425 |
return the underlying :class:`ParamSpec`. |
| 3426 |
Return ``None`` for unsupported objects. |
| 3427 |
|
| 3428 |
Examples: |
| 3429 |
|
| 3430 |
.. testcode:: |
| 3431 |
|
| 3432 |
assert get_origin(str) is None |
| 3433 |
assert get_origin(Dict[str, int]) is dict |
| 3434 |
assert get_origin(Union[int, str]) is Union |
| 3435 |
assert get_origin(Annotated[str, "metadata"]) is Annotated |
| 3436 |
P = ParamSpec('P') |
| 3437 |
assert get_origin(P.args) is P |
| 3438 |
assert get_origin(P.kwargs) is P |
| 3439 |
|
| 3440 |
.. versionadded:: 3.8 |
| 3441 |
|
| 3442 |
.. function:: get_args(tp) |
| 3443 |
|
| 3444 |
Get type arguments with all substitutions performed: for a typing object |
| 3445 |
of the form ``X[Y, Z, ...]`` return ``(Y, Z, ...)``. |
| 3446 |
|
| 3447 |
If ``X`` is a union or :class:`Literal` contained in another |
| 3448 |
generic type, the order of ``(Y, Z, ...)`` may be different from the order |
| 3449 |
of the original arguments ``[Y, Z, ...]`` due to type caching. |
| 3450 |
Return ``()`` for unsupported objects. |
| 3451 |
|
| 3452 |
Examples: |
| 3453 |
|
| 3454 |
.. testcode:: |
| 3455 |
|
| 3456 |
assert get_args(int) == () |
| 3457 |
assert get_args(Dict[int, str]) == (int, str) |
| 3458 |
assert get_args(Union[int, str]) == (int, str) |
| 3459 |
|
| 3460 |
.. versionadded:: 3.8 |
| 3461 |
|
| 3462 |
.. function:: get_protocol_members(tp) |
| 3463 |
|
| 3464 |
Return the set of members defined in a :class:`Protocol`. |
| 3465 |
|
| 3466 |
.. doctest:: |
| 3467 |
|
| 3468 |
>>> from typing import Protocol, get_protocol_members |
| 3469 |
>>> class P(Protocol): |
| 3470 |
... def a(self) -> str: ... |
| 3471 |
... b: int |
| 3472 |
>>> get_protocol_members(P) == frozenset({'a', 'b'}) |
| 3473 |
True |
| 3474 |
|
| 3475 |
Raise :exc:`TypeError` for arguments that are not Protocols. |
| 3476 |
|
| 3477 |
.. versionadded:: 3.13 |
| 3478 |
|
| 3479 |
.. function:: is_protocol(tp) |
| 3480 |
|
| 3481 |
Determine if a type is a :class:`Protocol`. |
| 3482 |
|
| 3483 |
For example: |
| 3484 |
|
| 3485 |
.. testcode:: |
| 3486 |
|
| 3487 |
class P(Protocol): |
| 3488 |
def a(self) -> str: ... |
| 3489 |
b: int |
| 3490 |
|
| 3491 |
assert is_protocol(P) |
| 3492 |
assert not is_protocol(int) |
| 3493 |
|
| 3494 |
This function only returns true for ``Protocol`` classes, not for |
| 3495 |
:ref:`generic aliases <types-genericalias>` of them: |
| 3496 |
|
| 3497 |
.. testcode:: |
| 3498 |
|
| 3499 |
class GenericP[T](Protocol): |
| 3500 |
def a(self) -> T: ... |
| 3501 |
b: int |
| 3502 |
|
| 3503 |
assert not is_protocol(GenericP[int]) |
| 3504 |
|
| 3505 |
.. versionadded:: 3.13 |
| 3506 |
|
| 3507 |
.. function:: is_typeddict(tp) |
| 3508 |
|
| 3509 |
Check if a type is a :class:`TypedDict`. |
| 3510 |
|
| 3511 |
For example: |
| 3512 |
|
| 3513 |
.. testcode:: |
| 3514 |
|
| 3515 |
class Film(TypedDict): |
| 3516 |
title: str |
| 3517 |
year: int |
| 3518 |
|
| 3519 |
assert is_typeddict(Film) |
| 3520 |
assert not is_typeddict(list | str) |
| 3521 |
|
| 3522 |
# TypedDict is a factory for creating typed dicts, |
| 3523 |
# not a typed dict itself |
| 3524 |
assert not is_typeddict(TypedDict) |
| 3525 |
|
| 3526 |
This function only returns true for ``TypedDict`` classes, not for |
| 3527 |
:ref:`generic aliases <types-genericalias>` of them: |
| 3528 |
|
| 3529 |
.. testcode:: |
| 3530 |
|
| 3531 |
class GenericFilm[T](TypedDict): |
| 3532 |
title: str |
| 3533 |
year: T |
| 3534 |
|
| 3535 |
assert not is_typeddict(GenericFilm[int]) |
| 3536 |
|
| 3537 |
.. versionadded:: 3.10 |
| 3538 |
|
| 3539 |
.. class:: ForwardRef |
| 3540 |
|
| 3541 |
Class used for internal typing representation of string forward references. |
| 3542 |
|
| 3543 |
For example, ``List["SomeClass"]`` is implicitly transformed into |
| 3544 |
``List[ForwardRef("SomeClass")]``. :class:`!ForwardRef` should not be instantiated by |
| 3545 |
a user, but may be used by introspection tools. |
| 3546 |
|
| 3547 |
.. note:: |
| 3548 |
:pep:`585` generic types such as ``list["SomeClass"]`` will not be |
| 3549 |
implicitly transformed into ``list[ForwardRef("SomeClass")]`` and thus |
| 3550 |
will not automatically resolve to ``list[SomeClass]``. |
| 3551 |
|
| 3552 |
.. versionadded:: 3.7.4 |
| 3553 |
|
| 3554 |
.. versionchanged:: 3.14 |
| 3555 |
This is now an alias for :class:`annotationlib.ForwardRef`. Several undocumented |
| 3556 |
behaviors of this class have been changed; for example, after a ``ForwardRef`` has |
| 3557 |
been evaluated, the evaluated value is no longer cached. |
| 3558 |
|
| 3559 |
.. function:: evaluate_forward_ref(forward_ref, *, owner=None, globals=None, locals=None, type_params=None, format=annotationlib.Format.VALUE) |
| 3560 |
|
| 3561 |
Evaluate an :class:`annotationlib.ForwardRef` as a :term:`type hint`. |
| 3562 |
|
| 3563 |
This is similar to calling :meth:`annotationlib.ForwardRef.evaluate`, |
| 3564 |
but unlike that method, :func:`!evaluate_forward_ref` also |
| 3565 |
recursively evaluates forward references nested within the type hint. |
| 3566 |
|
| 3567 |
See the documentation for :meth:`annotationlib.ForwardRef.evaluate` for |
| 3568 |
the meaning of the *owner*, *globals*, *locals*, *type_params*, and *format* parameters. |
| 3569 |
|
| 3570 |
.. caution:: |
| 3571 |
|
| 3572 |
This function may execute arbitrary code contained in annotations. |
| 3573 |
See :ref:`annotationlib-security` for more information. |
| 3574 |
|
| 3575 |
.. versionadded:: 3.14 |
| 3576 |
|
| 3577 |
.. data:: NoDefault |
| 3578 |
|
| 3579 |
A sentinel object used to indicate that a type parameter has no default |
| 3580 |
value. For example: |
| 3581 |
|
| 3582 |
.. doctest:: |
| 3583 |
|
| 3584 |
>>> T = TypeVar("T") |
| 3585 |
>>> T.__default__ is typing.NoDefault |
| 3586 |
True |
| 3587 |
>>> S = TypeVar("S", default=None) |
| 3588 |
>>> S.__default__ is None |
| 3589 |
True |
| 3590 |
|
| 3591 |
.. versionadded:: 3.13 |
| 3592 |
|
| 3593 |
Constant |
| 3594 |
-------- |
| 3595 |
|
| 3596 |
.. data:: TYPE_CHECKING |
| 3597 |
|
| 3598 |
A special constant that is assumed to be ``True`` by static |
| 3599 |
type checkers. It's ``False`` at runtime. |
| 3600 |
|
| 3601 |
A module which is expensive to import, and which only contain types |
| 3602 |
used for typing annotations, can be safely imported inside an |
| 3603 |
``if TYPE_CHECKING:`` block. This prevents the module from actually |
| 3604 |
being imported at runtime; annotations aren't eagerly evaluated |
| 3605 |
(see :pep:`649`) so using undefined symbols in annotations is |
| 3606 |
harmless--as long as you don't later examine them. |
| 3607 |
Your static type analysis tool will set ``TYPE_CHECKING`` to |
| 3608 |
``True`` during static type analysis, which means the module will |
| 3609 |
be imported and the types will be checked properly during such analysis. |
| 3610 |
|
| 3611 |
Usage:: |
| 3612 |
|
| 3613 |
if TYPE_CHECKING: |
| 3614 |
import expensive_mod |
| 3615 |
|
| 3616 |
def fun(arg: expensive_mod.SomeType) -> None: |
| 3617 |
local_var: expensive_mod.AnotherType = other_fun() |
| 3618 |
|
| 3619 |
If you occasionally need to examine type annotations at runtime |
| 3620 |
which may contain undefined symbols, use |
| 3621 |
:meth:`annotationlib.get_annotations` with a ``format`` parameter |
| 3622 |
of :attr:`annotationlib.Format.STRING` or |
| 3623 |
:attr:`annotationlib.Format.FORWARDREF` to safely retrieve the |
| 3624 |
annotations without raising :exc:`NameError`. |
| 3625 |
|
| 3626 |
.. versionadded:: 3.5.2 |
| 3627 |
|
| 3628 |
.. _generic-concrete-collections: |
| 3629 |
.. _deprecated-aliases: |
| 3630 |
|
| 3631 |
Deprecated aliases |
| 3632 |
------------------ |
| 3633 |
|
| 3634 |
This module defines several deprecated aliases to pre-existing |
| 3635 |
standard library classes. These were originally included in the :mod:`!typing` |
| 3636 |
module in order to support parameterizing these generic classes using ``[]``. |
| 3637 |
However, the aliases became redundant in Python 3.9 when the |
| 3638 |
corresponding pre-existing classes were enhanced to support ``[]`` (see |
| 3639 |
:pep:`585`). |
| 3640 |
|
| 3641 |
The redundant types are deprecated as of Python 3.9. However, while the aliases |
| 3642 |
may be removed at some point, removal of these aliases is not currently |
| 3643 |
planned. As such, no deprecation warnings are currently issued by the |
| 3644 |
interpreter for these aliases. |
| 3645 |
|
| 3646 |
If at some point it is decided to remove these deprecated aliases, a |
| 3647 |
deprecation warning will be issued by the interpreter for at least two releases |
| 3648 |
prior to removal. The aliases are guaranteed to remain in the :mod:`!typing` module |
| 3649 |
without deprecation warnings until at least Python 3.14. |
| 3650 |
|
| 3651 |
Type checkers are encouraged to flag uses of the deprecated types if the |
| 3652 |
program they are checking targets a minimum Python version of 3.9 or newer. |
| 3653 |
|
| 3654 |
.. _corresponding-to-built-in-types: |
| 3655 |
|
| 3656 |
Aliases to built-in types |
| 3657 |
""""""""""""""""""""""""" |
| 3658 |
|
| 3659 |
.. class:: Dict(dict, MutableMapping[KT, VT]) |
| 3660 |
|
| 3661 |
Deprecated alias to :class:`dict`. |
| 3662 |
|
| 3663 |
Note that to annotate arguments, it is preferred |
| 3664 |
to use an abstract collection type such as :class:`~collections.abc.Mapping` |
| 3665 |
rather than to use :class:`dict` or :class:`!typing.Dict`. |
| 3666 |
|
| 3667 |
.. deprecated:: 3.9 |
| 3668 |
:class:`builtins.dict <dict>` now supports subscripting (``[]``). |
| 3669 |
See :pep:`585` and :ref:`types-genericalias`. |
| 3670 |
|
| 3671 |
.. class:: List(list, MutableSequence[T]) |
| 3672 |
|
| 3673 |
Deprecated alias to :class:`list`. |
| 3674 |
|
| 3675 |
Note that to annotate arguments, it is preferred |
| 3676 |
to use an abstract collection type such as |
| 3677 |
:class:`~collections.abc.Sequence` or :class:`~collections.abc.Iterable` |
| 3678 |
rather than to use :class:`list` or :class:`!typing.List`. |
| 3679 |
|
| 3680 |
.. deprecated:: 3.9 |
| 3681 |
:class:`builtins.list <list>` now supports subscripting (``[]``). |
| 3682 |
See :pep:`585` and :ref:`types-genericalias`. |
| 3683 |
|
| 3684 |
.. class:: Set(set, MutableSet[T]) |
| 3685 |
|
| 3686 |
Deprecated alias to :class:`builtins.set <set>`. |
| 3687 |
|
| 3688 |
Note that to annotate arguments, it is preferred |
| 3689 |
to use an abstract collection type such as :class:`collections.abc.Set` |
| 3690 |
rather than to use :class:`set` or :class:`typing.Set`. |
| 3691 |
|
| 3692 |
.. deprecated:: 3.9 |
| 3693 |
:class:`builtins.set <set>` now supports subscripting (``[]``). |
| 3694 |
See :pep:`585` and :ref:`types-genericalias`. |
| 3695 |
|
| 3696 |
.. class:: FrozenSet(frozenset, AbstractSet[T_co]) |
| 3697 |
|
| 3698 |
Deprecated alias to :class:`builtins.frozenset <frozenset>`. |
| 3699 |
|
| 3700 |
.. deprecated:: 3.9 |
| 3701 |
:class:`builtins.frozenset <frozenset>` |
| 3702 |
now supports subscripting (``[]``). |
| 3703 |
See :pep:`585` and :ref:`types-genericalias`. |
| 3704 |
|
| 3705 |
.. data:: Tuple |
| 3706 |
|
| 3707 |
Deprecated alias for :class:`tuple`. |
| 3708 |
|
| 3709 |
:class:`tuple` and ``Tuple`` are special-cased in the type system; see |
| 3710 |
:ref:`annotating-tuples` for more details. |
| 3711 |
|
| 3712 |
.. deprecated:: 3.9 |
| 3713 |
:class:`builtins.tuple <tuple>` now supports subscripting (``[]``). |
| 3714 |
See :pep:`585` and :ref:`types-genericalias`. |
| 3715 |
|
| 3716 |
.. class:: Type(Generic[CT_co]) |
| 3717 |
|
| 3718 |
Deprecated alias to :class:`type`. |
| 3719 |
|
| 3720 |
See :ref:`type-of-class-objects` for details on using :class:`type` or |
| 3721 |
``typing.Type`` in type annotations. |
| 3722 |
|
| 3723 |
.. versionadded:: 3.5.2 |
| 3724 |
|
| 3725 |
.. deprecated:: 3.9 |
| 3726 |
:class:`builtins.type <type>` now supports subscripting (``[]``). |
| 3727 |
See :pep:`585` and :ref:`types-genericalias`. |
| 3728 |
|
| 3729 |
.. _corresponding-to-types-in-collections: |
| 3730 |
|
| 3731 |
Aliases to types in :mod:`collections` |
| 3732 |
"""""""""""""""""""""""""""""""""""""" |
| 3733 |
|
| 3734 |
.. class:: DefaultDict(collections.defaultdict, MutableMapping[KT, VT]) |
| 3735 |
|
| 3736 |
Deprecated alias to :class:`collections.defaultdict`. |
| 3737 |
|
| 3738 |
.. versionadded:: 3.5.2 |
| 3739 |
|
| 3740 |
.. deprecated:: 3.9 |
| 3741 |
:class:`collections.defaultdict` now supports subscripting (``[]``). |
| 3742 |
See :pep:`585` and :ref:`types-genericalias`. |
| 3743 |
|
| 3744 |
.. class:: OrderedDict(collections.OrderedDict, MutableMapping[KT, VT]) |
| 3745 |
|
| 3746 |
Deprecated alias to :class:`collections.OrderedDict`. |
| 3747 |
|
| 3748 |
.. versionadded:: 3.7.2 |
| 3749 |
|
| 3750 |
.. deprecated:: 3.9 |
| 3751 |
:class:`collections.OrderedDict` now supports subscripting (``[]``). |
| 3752 |
See :pep:`585` and :ref:`types-genericalias`. |
| 3753 |
|
| 3754 |
.. class:: ChainMap(collections.ChainMap, MutableMapping[KT, VT]) |
| 3755 |
|
| 3756 |
Deprecated alias to :class:`collections.ChainMap`. |
| 3757 |
|
| 3758 |
.. versionadded:: 3.6.1 |
| 3759 |
|
| 3760 |
.. deprecated:: 3.9 |
| 3761 |
:class:`collections.ChainMap` now supports subscripting (``[]``). |
| 3762 |
See :pep:`585` and :ref:`types-genericalias`. |
| 3763 |
|
| 3764 |
.. class:: Counter(collections.Counter, Dict[T, int]) |
| 3765 |
|
| 3766 |
Deprecated alias to :class:`collections.Counter`. |
| 3767 |
|
| 3768 |
.. versionadded:: 3.6.1 |
| 3769 |
|
| 3770 |
.. deprecated:: 3.9 |
| 3771 |
:class:`collections.Counter` now supports subscripting (``[]``). |
| 3772 |
See :pep:`585` and :ref:`types-genericalias`. |
| 3773 |
|
| 3774 |
.. class:: Deque(deque, MutableSequence[T]) |
| 3775 |
|
| 3776 |
Deprecated alias to :class:`collections.deque`. |
| 3777 |
|
| 3778 |
.. versionadded:: 3.6.1 |
| 3779 |
|
| 3780 |
.. deprecated:: 3.9 |
| 3781 |
:class:`collections.deque` now supports subscripting (``[]``). |
| 3782 |
See :pep:`585` and :ref:`types-genericalias`. |
| 3783 |
|
| 3784 |
.. _other-concrete-types: |
| 3785 |
|
| 3786 |
Aliases to other concrete types |
| 3787 |
""""""""""""""""""""""""""""""" |
| 3788 |
|
| 3789 |
.. class:: Pattern |
| 3790 |
Match |
| 3791 |
|
| 3792 |
Deprecated aliases corresponding to the return types from |
| 3793 |
:func:`re.compile` and :func:`re.match`. |
| 3794 |
|
| 3795 |
These types (and the corresponding functions) are generic over |
| 3796 |
:data:`AnyStr`. ``Pattern`` can be specialised as ``Pattern[str]`` or |
| 3797 |
``Pattern[bytes]``; ``Match`` can be specialised as ``Match[str]`` or |
| 3798 |
``Match[bytes]``. |
| 3799 |
|
| 3800 |
.. deprecated:: 3.9 |
| 3801 |
Classes ``Pattern`` and ``Match`` from :mod:`re` now support ``[]``. |
| 3802 |
See :pep:`585` and :ref:`types-genericalias`. |
| 3803 |
|
| 3804 |
.. class:: Text |
| 3805 |
|
| 3806 |
Deprecated alias for :class:`str`. |
| 3807 |
|
| 3808 |
``Text`` is provided to supply a forward |
| 3809 |
compatible path for Python 2 code: in Python 2, ``Text`` is an alias for |
| 3810 |
``unicode``. |
| 3811 |
|
| 3812 |
Use ``Text`` to indicate that a value must contain a unicode string in |
| 3813 |
a manner that is compatible with both Python 2 and Python 3:: |
| 3814 |
|
| 3815 |
def add_unicode_checkmark(text: Text) -> Text: |
| 3816 |
return text + u' \u2713' |
| 3817 |
|
| 3818 |
.. versionadded:: 3.5.2 |
| 3819 |
|
| 3820 |
.. deprecated:: 3.11 |
| 3821 |
Python 2 is no longer supported, and most type checkers also no longer |
| 3822 |
support type checking Python 2 code. Removal of the alias is not |
| 3823 |
currently planned, but users are encouraged to use |
| 3824 |
:class:`str` instead of ``Text``. |
| 3825 |
|
| 3826 |
.. _abstract-base-classes: |
| 3827 |
.. _corresponding-to-collections-in-collections-abc: |
| 3828 |
|
| 3829 |
Aliases to container ABCs in :mod:`collections.abc` |
| 3830 |
""""""""""""""""""""""""""""""""""""""""""""""""""" |
| 3831 |
|
| 3832 |
.. class:: AbstractSet(Collection[T_co]) |
| 3833 |
|
| 3834 |
Deprecated alias to :class:`collections.abc.Set`. |
| 3835 |
|
| 3836 |
.. deprecated:: 3.9 |
| 3837 |
:class:`collections.abc.Set` now supports subscripting (``[]``). |
| 3838 |
See :pep:`585` and :ref:`types-genericalias`. |
| 3839 |
|
| 3840 |
.. class:: ByteString(Sequence[int]) |
| 3841 |
|
| 3842 |
Deprecated alias to :class:`collections.abc.ByteString`. |
| 3843 |
|
| 3844 |
Use ``isinstance(obj, collections.abc.Buffer)`` to test if ``obj`` |
| 3845 |
implements the :ref:`buffer protocol <bufferobjects>` at runtime. For use in |
| 3846 |
type annotations, either use :class:`~collections.abc.Buffer` or a union |
| 3847 |
that explicitly specifies the types your code supports (e.g., |
| 3848 |
``bytes | bytearray | memoryview``). |
| 3849 |
|
| 3850 |
:class:`!ByteString` was originally intended to be an abstract class that |
| 3851 |
would serve as a supertype of both :class:`bytes` and :class:`bytearray`. |
| 3852 |
However, since the ABC never had any methods, knowing that an object was an |
| 3853 |
instance of :class:`!ByteString` never actually told you anything useful |
| 3854 |
about the object. Other common buffer types such as :class:`memoryview` were |
| 3855 |
also never understood as subtypes of :class:`!ByteString` (either at runtime |
| 3856 |
or by static type checkers). |
| 3857 |
|
| 3858 |
See :pep:`PEP 688 <688#current-options>` for more details. |
| 3859 |
|
| 3860 |
.. deprecated-removed:: 3.9 3.17 |
| 3861 |
|
| 3862 |
.. class:: Collection(Sized, Iterable[T_co], Container[T_co]) |
| 3863 |
|
| 3864 |
Deprecated alias to :class:`collections.abc.Collection`. |
| 3865 |
|
| 3866 |
.. versionadded:: 3.6 |
| 3867 |
|
| 3868 |
.. deprecated:: 3.9 |
| 3869 |
:class:`collections.abc.Collection` now supports subscripting (``[]``). |
| 3870 |
See :pep:`585` and :ref:`types-genericalias`. |
| 3871 |
|
| 3872 |
.. class:: Container(Generic[T_co]) |
| 3873 |
|
| 3874 |
Deprecated alias to :class:`collections.abc.Container`. |
| 3875 |
|
| 3876 |
.. deprecated:: 3.9 |
| 3877 |
:class:`collections.abc.Container` now supports subscripting (``[]``). |
| 3878 |
See :pep:`585` and :ref:`types-genericalias`. |
| 3879 |
|
| 3880 |
.. class:: ItemsView(MappingView, AbstractSet[tuple[KT_co, VT_co]]) |
| 3881 |
|
| 3882 |
Deprecated alias to :class:`collections.abc.ItemsView`. |
| 3883 |
|
| 3884 |
.. deprecated:: 3.9 |
| 3885 |
:class:`collections.abc.ItemsView` now supports subscripting (``[]``). |
| 3886 |
See :pep:`585` and :ref:`types-genericalias`. |
| 3887 |
|
| 3888 |
.. class:: KeysView(MappingView, AbstractSet[KT_co]) |
| 3889 |
|
| 3890 |
Deprecated alias to :class:`collections.abc.KeysView`. |
| 3891 |
|
| 3892 |
.. deprecated:: 3.9 |
| 3893 |
:class:`collections.abc.KeysView` now supports subscripting (``[]``). |
| 3894 |
See :pep:`585` and :ref:`types-genericalias`. |
| 3895 |
|
| 3896 |
.. class:: Mapping(Collection[KT], Generic[KT, VT_co]) |
| 3897 |
|
| 3898 |
Deprecated alias to :class:`collections.abc.Mapping`. |
| 3899 |
|
| 3900 |
.. deprecated:: 3.9 |
| 3901 |
:class:`collections.abc.Mapping` now supports subscripting (``[]``). |
| 3902 |
See :pep:`585` and :ref:`types-genericalias`. |
| 3903 |
|
| 3904 |
.. class:: MappingView(Sized) |
| 3905 |
|
| 3906 |
Deprecated alias to :class:`collections.abc.MappingView`. |
| 3907 |
|
| 3908 |
.. deprecated:: 3.9 |
| 3909 |
:class:`collections.abc.MappingView` now supports subscripting (``[]``). |
| 3910 |
See :pep:`585` and :ref:`types-genericalias`. |
| 3911 |
|
| 3912 |
.. class:: MutableMapping(Mapping[KT, VT]) |
| 3913 |
|
| 3914 |
Deprecated alias to :class:`collections.abc.MutableMapping`. |
| 3915 |
|
| 3916 |
.. deprecated:: 3.9 |
| 3917 |
:class:`collections.abc.MutableMapping` |
| 3918 |
now supports subscripting (``[]``). |
| 3919 |
See :pep:`585` and :ref:`types-genericalias`. |
| 3920 |
|
| 3921 |
.. class:: MutableSequence(Sequence[T]) |
| 3922 |
|
| 3923 |
Deprecated alias to :class:`collections.abc.MutableSequence`. |
| 3924 |
|
| 3925 |
.. deprecated:: 3.9 |
| 3926 |
:class:`collections.abc.MutableSequence` |
| 3927 |
now supports subscripting (``[]``). |
| 3928 |
See :pep:`585` and :ref:`types-genericalias`. |
| 3929 |
|
| 3930 |
.. class:: MutableSet(AbstractSet[T]) |
| 3931 |
|
| 3932 |
Deprecated alias to :class:`collections.abc.MutableSet`. |
| 3933 |
|
| 3934 |
.. deprecated:: 3.9 |
| 3935 |
:class:`collections.abc.MutableSet` now supports subscripting (``[]``). |
| 3936 |
See :pep:`585` and :ref:`types-genericalias`. |
| 3937 |
|
| 3938 |
.. class:: Sequence(Reversible[T_co], Collection[T_co]) |
| 3939 |
|
| 3940 |
Deprecated alias to :class:`collections.abc.Sequence`. |
| 3941 |
|
| 3942 |
.. deprecated:: 3.9 |
| 3943 |
:class:`collections.abc.Sequence` now supports subscripting (``[]``). |
| 3944 |
See :pep:`585` and :ref:`types-genericalias`. |
| 3945 |
|
| 3946 |
.. class:: ValuesView(MappingView, Collection[_VT_co]) |
| 3947 |
|
| 3948 |
Deprecated alias to :class:`collections.abc.ValuesView`. |
| 3949 |
|
| 3950 |
.. deprecated:: 3.9 |
| 3951 |
:class:`collections.abc.ValuesView` now supports subscripting (``[]``). |
| 3952 |
See :pep:`585` and :ref:`types-genericalias`. |
| 3953 |
|
| 3954 |
.. _asynchronous-programming: |
| 3955 |
|
| 3956 |
Aliases to asynchronous ABCs in :mod:`collections.abc` |
| 3957 |
"""""""""""""""""""""""""""""""""""""""""""""""""""""" |
| 3958 |
|
| 3959 |
.. class:: Coroutine(Awaitable[ReturnType], Generic[YieldType, SendType, ReturnType]) |
| 3960 |
|
| 3961 |
Deprecated alias to :class:`collections.abc.Coroutine`. |
| 3962 |
|
| 3963 |
See :ref:`annotating-generators-and-coroutines` |
| 3964 |
for details on using :class:`collections.abc.Coroutine` |
| 3965 |
and ``typing.Coroutine`` in type annotations. |
| 3966 |
|
| 3967 |
.. versionadded:: 3.5.3 |
| 3968 |
|
| 3969 |
.. deprecated:: 3.9 |
| 3970 |
:class:`collections.abc.Coroutine` now supports subscripting (``[]``). |
| 3971 |
See :pep:`585` and :ref:`types-genericalias`. |
| 3972 |
|
| 3973 |
.. class:: AsyncGenerator(AsyncIterator[YieldType], Generic[YieldType, SendType]) |
| 3974 |
|
| 3975 |
Deprecated alias to :class:`collections.abc.AsyncGenerator`. |
| 3976 |
|
| 3977 |
See :ref:`annotating-generators-and-coroutines` |
| 3978 |
for details on using :class:`collections.abc.AsyncGenerator` |
| 3979 |
and ``typing.AsyncGenerator`` in type annotations. |
| 3980 |
|
| 3981 |
.. versionadded:: 3.6.1 |
| 3982 |
|
| 3983 |
.. deprecated:: 3.9 |
| 3984 |
:class:`collections.abc.AsyncGenerator` |
| 3985 |
now supports subscripting (``[]``). |
| 3986 |
See :pep:`585` and :ref:`types-genericalias`. |
| 3987 |
|
| 3988 |
.. versionchanged:: 3.13 |
| 3989 |
The ``SendType`` parameter now has a default. |
| 3990 |
|
| 3991 |
.. class:: AsyncIterable(Generic[T_co]) |
| 3992 |
|
| 3993 |
Deprecated alias to :class:`collections.abc.AsyncIterable`. |
| 3994 |
|
| 3995 |
.. versionadded:: 3.5.2 |
| 3996 |
|
| 3997 |
.. deprecated:: 3.9 |
| 3998 |
:class:`collections.abc.AsyncIterable` now supports subscripting (``[]``). |
| 3999 |
See :pep:`585` and :ref:`types-genericalias`. |
| 4000 |
|
| 4001 |
.. class:: AsyncIterator(AsyncIterable[T_co]) |
| 4002 |
|
| 4003 |
Deprecated alias to :class:`collections.abc.AsyncIterator`. |
| 4004 |
|
| 4005 |
.. versionadded:: 3.5.2 |
| 4006 |
|
| 4007 |
.. deprecated:: 3.9 |
| 4008 |
:class:`collections.abc.AsyncIterator` now supports subscripting (``[]``). |
| 4009 |
See :pep:`585` and :ref:`types-genericalias`. |
| 4010 |
|
| 4011 |
.. class:: Awaitable(Generic[T_co]) |
| 4012 |
|
| 4013 |
Deprecated alias to :class:`collections.abc.Awaitable`. |
| 4014 |
|
| 4015 |
.. versionadded:: 3.5.2 |
| 4016 |
|
| 4017 |
.. deprecated:: 3.9 |
| 4018 |
:class:`collections.abc.Awaitable` now supports subscripting (``[]``). |
| 4019 |
See :pep:`585` and :ref:`types-genericalias`. |
| 4020 |
|
| 4021 |
.. _corresponding-to-other-types-in-collections-abc: |
| 4022 |
|
| 4023 |
Aliases to other ABCs in :mod:`collections.abc` |
| 4024 |
""""""""""""""""""""""""""""""""""""""""""""""" |
| 4025 |
|
| 4026 |
.. class:: Iterable(Generic[T_co]) |
| 4027 |
|
| 4028 |
Deprecated alias to :class:`collections.abc.Iterable`. |
| 4029 |
|
| 4030 |
.. deprecated:: 3.9 |
| 4031 |
:class:`collections.abc.Iterable` now supports subscripting (``[]``). |
| 4032 |
See :pep:`585` and :ref:`types-genericalias`. |
| 4033 |
|
| 4034 |
.. class:: Iterator(Iterable[T_co]) |
| 4035 |
|
| 4036 |
Deprecated alias to :class:`collections.abc.Iterator`. |
| 4037 |
|
| 4038 |
.. deprecated:: 3.9 |
| 4039 |
:class:`collections.abc.Iterator` now supports subscripting (``[]``). |
| 4040 |
See :pep:`585` and :ref:`types-genericalias`. |
| 4041 |
|
| 4042 |
.. data:: Callable |
| 4043 |
|
| 4044 |
Deprecated alias to :class:`collections.abc.Callable`. |
| 4045 |
|
| 4046 |
See :ref:`annotating-callables` for details on how to use |
| 4047 |
:class:`collections.abc.Callable` and ``typing.Callable`` in type annotations. |
| 4048 |
|
| 4049 |
.. deprecated:: 3.9 |
| 4050 |
:class:`collections.abc.Callable` now supports subscripting (``[]``). |
| 4051 |
See :pep:`585` and :ref:`types-genericalias`. |
| 4052 |
|
| 4053 |
.. versionchanged:: 3.10 |
| 4054 |
``Callable`` now supports :class:`ParamSpec` and :data:`Concatenate`. |
| 4055 |
See :pep:`612` for more details. |
| 4056 |
|
| 4057 |
.. class:: Generator(Iterator[YieldType], Generic[YieldType, SendType, ReturnType]) |
| 4058 |
|
| 4059 |
Deprecated alias to :class:`collections.abc.Generator`. |
| 4060 |
|
| 4061 |
See :ref:`annotating-generators-and-coroutines` |
| 4062 |
for details on using :class:`collections.abc.Generator` |
| 4063 |
and ``typing.Generator`` in type annotations. |
| 4064 |
|
| 4065 |
.. deprecated:: 3.9 |
| 4066 |
:class:`collections.abc.Generator` now supports subscripting (``[]``). |
| 4067 |
See :pep:`585` and :ref:`types-genericalias`. |
| 4068 |
|
| 4069 |
.. versionchanged:: 3.13 |
| 4070 |
Default values for the send and return types were added. |
| 4071 |
|
| 4072 |
.. class:: Hashable |
| 4073 |
|
| 4074 |
Deprecated alias to :class:`collections.abc.Hashable`. |
| 4075 |
|
| 4076 |
.. deprecated:: 3.12 |
| 4077 |
Use :class:`collections.abc.Hashable` directly instead. |
| 4078 |
|
| 4079 |
.. class:: Reversible(Iterable[T_co]) |
| 4080 |
|
| 4081 |
Deprecated alias to :class:`collections.abc.Reversible`. |
| 4082 |
|
| 4083 |
.. deprecated:: 3.9 |
| 4084 |
:class:`collections.abc.Reversible` now supports subscripting (``[]``). |
| 4085 |
See :pep:`585` and :ref:`types-genericalias`. |
| 4086 |
|
| 4087 |
.. class:: Sized |
| 4088 |
|
| 4089 |
Deprecated alias to :class:`collections.abc.Sized`. |
| 4090 |
|
| 4091 |
.. deprecated:: 3.12 |
| 4092 |
Use :class:`collections.abc.Sized` directly instead. |
| 4093 |
|
| 4094 |
.. _context-manager-types: |
| 4095 |
|
| 4096 |
Aliases to :mod:`contextlib` ABCs |
| 4097 |
""""""""""""""""""""""""""""""""" |
| 4098 |
|
| 4099 |
.. class:: ContextManager(Generic[T_co, ExitT_co]) |
| 4100 |
|
| 4101 |
Deprecated alias to :class:`contextlib.AbstractContextManager`. |
| 4102 |
|
| 4103 |
The first type parameter, ``T_co``, represents the type returned by |
| 4104 |
the :meth:`~object.__enter__` method. The optional second type parameter, ``ExitT_co``, |
| 4105 |
which defaults to ``bool | None``, represents the type returned by the |
| 4106 |
:meth:`~object.__exit__` method. |
| 4107 |
|
| 4108 |
.. versionadded:: 3.5.4 |
| 4109 |
|
| 4110 |
.. deprecated:: 3.9 |
| 4111 |
:class:`contextlib.AbstractContextManager` |
| 4112 |
now supports subscripting (``[]``). |
| 4113 |
See :pep:`585` and :ref:`types-genericalias`. |
| 4114 |
|
| 4115 |
.. versionchanged:: 3.13 |
| 4116 |
Added the optional second type parameter, ``ExitT_co``. |
| 4117 |
|
| 4118 |
.. class:: AsyncContextManager(Generic[T_co, AExitT_co]) |
| 4119 |
|
| 4120 |
Deprecated alias to :class:`contextlib.AbstractAsyncContextManager`. |
| 4121 |
|
| 4122 |
The first type parameter, ``T_co``, represents the type returned by |
| 4123 |
the :meth:`~object.__aenter__` method. The optional second type parameter, ``AExitT_co``, |
| 4124 |
which defaults to ``bool | None``, represents the type returned by the |
| 4125 |
:meth:`~object.__aexit__` method. |
| 4126 |
|
| 4127 |
.. versionadded:: 3.6.2 |
| 4128 |
|
| 4129 |
.. deprecated:: 3.9 |
| 4130 |
:class:`contextlib.AbstractAsyncContextManager` |
| 4131 |
now supports subscripting (``[]``). |
| 4132 |
See :pep:`585` and :ref:`types-genericalias`. |
| 4133 |
|
| 4134 |
.. versionchanged:: 3.13 |
| 4135 |
Added the optional second type parameter, ``AExitT_co``. |
| 4136 |
|
| 4137 |
Deprecation Timeline of Major Features |
| 4138 |
====================================== |
| 4139 |
|
| 4140 |
Certain features in ``typing`` are deprecated and may be removed in a future |
| 4141 |
version of Python. The following table summarizes major deprecations for your |
| 4142 |
convenience. This is subject to change, and not all deprecations are listed. |
| 4143 |
|
| 4144 |
.. list-table:: |
| 4145 |
:header-rows: 1 |
| 4146 |
|
| 4147 |
* - Feature |
| 4148 |
- Deprecated in |
| 4149 |
- Projected removal |
| 4150 |
- PEP/issue |
| 4151 |
* - ``typing`` versions of standard collections |
| 4152 |
- 3.9 |
| 4153 |
- Undecided (see :ref:`deprecated-aliases` for more information) |
| 4154 |
- :pep:`585` |
| 4155 |
* - :class:`typing.ByteString` |
| 4156 |
- 3.9 |
| 4157 |
- 3.17 |
| 4158 |
- :gh:`91896` |
| 4159 |
* - :data:`typing.Text` |
| 4160 |
- 3.11 |
| 4161 |
- Undecided |
| 4162 |
- :gh:`92332` |
| 4163 |
* - :class:`typing.Hashable` and :class:`typing.Sized` |
| 4164 |
- 3.12 |
| 4165 |
- Undecided |
| 4166 |
- :gh:`94309` |
| 4167 |
* - :data:`typing.TypeAlias` |
| 4168 |
- 3.12 |
| 4169 |
- Undecided |
| 4170 |
- :pep:`695` |
| 4171 |
* - :func:`@typing.no_type_check_decorator <no_type_check_decorator>` |
| 4172 |
- 3.13 |
| 4173 |
- 3.15 |
| 4174 |
- :gh:`106309` |
| 4175 |
* - :data:`typing.AnyStr` |
| 4176 |
- 3.13 |
| 4177 |
- 3.18 |
| 4178 |
- :gh:`105578` |