Debian Codegraph @

Doc/library/typing.rst

raw
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 being compatible with :data:`Any` and :data:`Any` as being
723 compatible with 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 compatible with 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` allows to solve 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 compatible with :data:`Any`.
855 * :data:`Any` is compatible with 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 .. data:: 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 .. data:: Optional
1136
1137 ``Optional[X]`` is equivalent to ``X | None`` (or ``Union[X, None]``).
1138
1139 Note that this is not the same concept as an optional argument,
1140 which is one that has a default. An optional argument with a
1141 default does not require the ``Optional`` qualifier on its type
1142 annotation just because it is optional. For example::
1143
1144 def foo(arg: int = 0) -> None:
1145 ...
1146
1147 On the other hand, if an explicit value of ``None`` is allowed, the
1148 use of ``Optional`` is appropriate, whether the argument is optional
1149 or not. For example::
1150
1151 def foo(arg: Optional[int] = None) -> None:
1152 ...
1153
1154 .. versionchanged:: 3.10
1155 Optional can now be written as ``X | None``. See
1156 :ref:`union type expressions<types-union>`.
1157
1158 .. data:: Concatenate
1159
1160 Special form for annotating higher-order functions.
1161
1162 .. index:: single: ...; ellipsis literal
1163
1164 ``Concatenate`` can be used in conjunction with :ref:`Callable <annotating-callables>` and
1165 :class:`ParamSpec` to annotate a higher-order callable which adds, removes,
1166 or transforms parameters of another
1167 callable. Usage is in the form
1168 ``Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable]``. ``Concatenate``
1169 is currently only valid when used as the first argument to a :ref:`Callable <annotating-callables>`.
1170 The last parameter to ``Concatenate`` must be a :class:`ParamSpec` or
1171 ellipsis (``...``).
1172
1173 For example, to annotate a decorator ``with_lock`` which provides a
1174 :class:`threading.Lock` to the decorated function, ``Concatenate`` can be
1175 used to indicate that ``with_lock`` expects a callable which takes in a
1176 ``Lock`` as the first argument, and returns a callable with a different type
1177 signature. In this case, the :class:`ParamSpec` indicates that the returned
1178 callable's parameter types are dependent on the parameter types of the
1179 callable being passed in::
1180
1181 from collections.abc import Callable
1182 from threading import Lock
1183 from typing import Concatenate
1184
1185 # Use this lock to ensure that only one thread is executing a function
1186 # at any time.
1187 my_lock = Lock()
1188
1189 def with_lock[**P, R](f: Callable[Concatenate[Lock, P], R]) -> Callable[P, R]:
1190 '''A type-safe decorator which provides a lock.'''
1191 def inner(*args: P.args, **kwargs: P.kwargs) -> R:
1192 # Provide the lock as the first argument.
1193 return f(my_lock, *args, **kwargs)
1194 return inner
1195
1196 @with_lock
1197 def sum_threadsafe(lock: Lock, numbers: list[float]) -> float:
1198 '''Add a list of numbers together in a thread-safe manner.'''
1199 with lock:
1200 return sum(numbers)
1201
1202 # We don't need to pass in the lock ourselves thanks to the decorator.
1203 sum_threadsafe([1.1, 2.2, 3.3])
1204
1205 .. versionadded:: 3.10
1206
1207 .. seealso::
1208
1209 * :pep:`612` -- Parameter Specification Variables (the PEP which introduced
1210 ``ParamSpec`` and ``Concatenate``)
1211 * :class:`ParamSpec`
1212 * :ref:`annotating-callables`
1213
1214 .. data:: Literal
1215
1216 Special typing form to define "literal types".
1217
1218 ``Literal`` can be used to indicate to type checkers that the
1219 annotated object has a value equivalent to one of the
1220 provided literals.
1221
1222 For example::
1223
1224 def validate_simple(data: Any) -> Literal[True]: # always returns True
1225 ...
1226
1227 type Mode = Literal['r', 'rb', 'w', 'wb']
1228 def open_helper(file: str, mode: Mode) -> str:
1229 ...
1230
1231 open_helper('/some/path', 'r') # Passes type check
1232 open_helper('/other/path', 'typo') # Error in type checker
1233
1234 ``Literal[...]`` cannot be subclassed. At runtime, an arbitrary value
1235 is allowed as type argument to ``Literal[...]``, but type checkers may
1236 impose restrictions. See :pep:`586` for more details about literal types.
1237
1238 Additional details:
1239
1240 * The arguments must be literal values and there must be at least one.
1241
1242 * Nested ``Literal`` types are flattened, e.g.::
1243
1244 assert Literal[Literal[1, 2], 3] == Literal[1, 2, 3]
1245
1246 However, this does not apply to ``Literal`` types referenced through a type
1247 alias, to avoid forcing evaluation of the underlying :class:`TypeAliasType`::
1248
1249 type A = Literal[1, 2]
1250 assert Literal[A, 3] != Literal[1, 2, 3]
1251
1252 * Redundant arguments are skipped, e.g.::
1253
1254 assert Literal[1, 2, 1] == Literal[1, 2]
1255
1256 * When comparing literals, the argument order is ignored, e.g.::
1257
1258 assert Literal[1, 2] == Literal[2, 1]
1259
1260 * You cannot subclass or instantiate a ``Literal``.
1261
1262 * You cannot write ``Literal[X][Y]``.
1263
1264 .. versionadded:: 3.8
1265
1266 .. versionchanged:: 3.9.1
1267 ``Literal`` now de-duplicates parameters. Equality comparisons of
1268 ``Literal`` objects are no longer order dependent. ``Literal`` objects
1269 will now raise a :exc:`TypeError` exception during equality comparisons
1270 if one of their parameters are not :term:`hashable`.
1271
1272 .. data:: ClassVar
1273
1274 Special type construct to mark class variables.
1275
1276 As introduced in :pep:`526`, a variable annotation wrapped in ClassVar
1277 indicates that a given attribute is intended to be used as a class variable
1278 and should not be set on instances of that class. Usage::
1279
1280 class Starship:
1281 stats: ClassVar[dict[str, int]] = {} # class variable
1282 damage: int = 10 # instance variable
1283
1284 :data:`ClassVar` accepts only types and cannot be further subscribed.
1285
1286 :data:`ClassVar` is not a class itself, and should not
1287 be used with :func:`isinstance` or :func:`issubclass`.
1288 :data:`ClassVar` does not change Python runtime behavior, but
1289 it can be used by third-party type checkers. For example, a type checker
1290 might flag the following code as an error::
1291
1292 enterprise_d = Starship(3000)
1293 enterprise_d.stats = {} # Error, setting class variable on instance
1294 Starship.stats = {} # This is OK
1295
1296 .. versionadded:: 3.5.3
1297
1298 .. versionchanged:: 3.13
1299
1300 :data:`ClassVar` can now be nested in :data:`Final` and vice versa.
1301
1302 .. data:: Final
1303
1304 Special typing construct to indicate final names to type checkers.
1305
1306 Final names cannot be reassigned in any scope. Final names declared in class
1307 scopes cannot be overridden in subclasses.
1308
1309 For example::
1310
1311 MAX_SIZE: Final = 9000
1312 MAX_SIZE += 1 # Error reported by type checker
1313
1314 class Connection:
1315 TIMEOUT: Final[int] = 10
1316
1317 class FastConnector(Connection):
1318 TIMEOUT = 1 # Error reported by type checker
1319
1320 There is no runtime checking of these properties. See :pep:`591` for
1321 more details.
1322
1323 .. versionadded:: 3.8
1324
1325 .. versionchanged:: 3.13
1326
1327 :data:`Final` can now be nested in :data:`ClassVar` and vice versa.
1328
1329 .. data:: Required
1330
1331 Special typing construct to mark a :class:`TypedDict` key as required.
1332
1333 This is mainly useful for ``total=False`` TypedDicts. See :class:`TypedDict`
1334 and :pep:`655` for more details.
1335
1336 .. versionadded:: 3.11
1337
1338 .. data:: NotRequired
1339
1340 Special typing construct to mark a :class:`TypedDict` key as potentially
1341 missing.
1342
1343 See :class:`TypedDict` and :pep:`655` for more details.
1344
1345 .. versionadded:: 3.11
1346
1347 .. data:: ReadOnly
1348
1349 A special typing construct to mark an item of a :class:`TypedDict` as read-only.
1350
1351 For example::
1352
1353 class Movie(TypedDict):
1354 title: ReadOnly[str]
1355 year: int
1356
1357 def mutate_movie(m: Movie) -> None:
1358 m["year"] = 1999 # allowed
1359 m["title"] = "The Matrix" # typechecker error
1360
1361 There is no runtime checking for this property.
1362
1363 See :class:`TypedDict` and :pep:`705` for more details.
1364
1365 .. versionadded:: 3.13
1366
1367 .. data:: Annotated
1368
1369 Special typing form to add context-specific metadata to an annotation.
1370
1371 Add metadata ``x`` to a given type ``T`` by using the annotation
1372 ``Annotated[T, x]``. Metadata added using ``Annotated`` can be used by
1373 static analysis tools or at runtime. At runtime, the metadata is stored
1374 in a :attr:`!__metadata__` attribute.
1375
1376 If a library or tool encounters an annotation ``Annotated[T, x]`` and has
1377 no special logic for the metadata, it should ignore the metadata and simply
1378 treat the annotation as ``T``. As such, ``Annotated`` can be useful for code
1379 that wants to use annotations for purposes outside Python's static typing
1380 system.
1381
1382 Using ``Annotated[T, x]`` as an annotation still allows for static
1383 typechecking of ``T``, as type checkers will simply ignore the metadata ``x``.
1384 In this way, ``Annotated`` differs from the
1385 :deco:`no_type_check` decorator, which can also be used for
1386 adding annotations outside the scope of the typing system, but
1387 completely disables typechecking for a function or class.
1388
1389 The responsibility of how to interpret the metadata
1390 lies with the tool or library encountering an
1391 ``Annotated`` annotation. A tool or library encountering an ``Annotated`` type
1392 can scan through the metadata elements to determine if they are of interest
1393 (e.g., using :func:`isinstance`).
1394
1395 .. describe:: Annotated[<type>, <metadata>]
1396
1397 Here is an example of how you might use ``Annotated`` to add metadata to
1398 type annotations if you were doing range analysis:
1399
1400 .. testcode::
1401
1402 @dataclass
1403 class ValueRange:
1404 lo: int
1405 hi: int
1406
1407 T1 = Annotated[int, ValueRange(-10, 5)]
1408 T2 = Annotated[T1, ValueRange(-20, 3)]
1409
1410 The first argument to ``Annotated`` must be a valid type. Multiple metadata
1411 elements can be supplied as ``Annotated`` supports variadic arguments. The
1412 order of the metadata elements is preserved and matters for equality checks::
1413
1414 @dataclass
1415 class ctype:
1416 kind: str
1417
1418 a1 = Annotated[int, ValueRange(3, 10), ctype("char")]
1419 a2 = Annotated[int, ctype("char"), ValueRange(3, 10)]
1420
1421 assert a1 != a2 # Order matters
1422
1423 It is up to the tool consuming the annotations to decide whether the
1424 client is allowed to add multiple metadata elements to one annotation and how to
1425 merge those annotations.
1426
1427 Nested ``Annotated`` types are flattened. The order of the metadata elements
1428 starts with the innermost annotation::
1429
1430 assert Annotated[Annotated[int, ValueRange(3, 10)], ctype("char")] == Annotated[
1431 int, ValueRange(3, 10), ctype("char")
1432 ]
1433
1434 However, this does not apply to ``Annotated`` types referenced through a type
1435 alias, to avoid forcing evaluation of the underlying :class:`TypeAliasType`::
1436
1437 type From3To10[T] = Annotated[T, ValueRange(3, 10)]
1438 assert Annotated[From3To10[int], ctype("char")] != Annotated[
1439 int, ValueRange(3, 10), ctype("char")
1440 ]
1441
1442 Duplicated metadata elements are not removed::
1443
1444 assert Annotated[int, ValueRange(3, 10)] != Annotated[
1445 int, ValueRange(3, 10), ValueRange(3, 10)
1446 ]
1447
1448 ``Annotated`` can be used with nested and generic aliases:
1449
1450 .. testcode::
1451
1452 @dataclass
1453 class MaxLen:
1454 value: int
1455
1456 type Vec[T] = Annotated[list[tuple[T, T]], MaxLen(10)]
1457
1458 # When used in a type annotation, a type checker will treat "V" the same as
1459 # ``Annotated[list[tuple[int, int]], MaxLen(10)]``:
1460 type V = Vec[int]
1461
1462 ``Annotated`` cannot be used with an unpacked :class:`TypeVarTuple`::
1463
1464 type Variadic[*Ts] = Annotated[*Ts, Ann1] = Annotated[T1, T2, T3, ..., Ann1] # NOT valid
1465
1466 where ``T1``, ``T2``, ... are :class:`TypeVars <TypeVar>`. This is invalid as
1467 only one type should be passed to Annotated.
1468
1469 By default, :func:`get_type_hints` strips the metadata from annotations.
1470 Pass ``include_extras=True`` to have the metadata preserved:
1471
1472 .. doctest::
1473
1474 >>> from typing import Annotated, get_type_hints
1475 >>> def func(x: Annotated[int, "metadata"]) -> None: pass
1476 ...
1477 >>> get_type_hints(func)
1478 {'x': <class 'int'>, 'return': <class 'NoneType'>}
1479 >>> get_type_hints(func, include_extras=True)
1480 {'x': typing.Annotated[int, 'metadata'], 'return': <class 'NoneType'>}
1481
1482 At runtime, the metadata associated with an ``Annotated`` type can be
1483 retrieved via the :attr:`!__metadata__` attribute:
1484
1485 .. doctest::
1486
1487 >>> from typing import Annotated
1488 >>> X = Annotated[int, "very", "important", "metadata"]
1489 >>> X
1490 typing.Annotated[int, 'very', 'important', 'metadata']
1491 >>> X.__metadata__
1492 ('very', 'important', 'metadata')
1493
1494 If you want to retrieve the original type wrapped by ``Annotated``, use the
1495 :attr:`!__origin__` attribute:
1496
1497 .. doctest::
1498
1499 >>> from typing import Annotated, get_origin
1500 >>> Password = Annotated[str, "secret"]
1501 >>> Password.__origin__
1502 <class 'str'>
1503
1504 Note that using :func:`get_origin` will return ``Annotated`` itself:
1505
1506 .. doctest::
1507
1508 >>> get_origin(Password)
1509 typing.Annotated
1510
1511 .. seealso::
1512
1513 :pep:`593` - Flexible function and variable annotations
1514 The PEP introducing ``Annotated`` to the standard library.
1515
1516 .. versionadded:: 3.9
1517
1518
1519 .. data:: TypeIs
1520
1521 Special typing construct for marking user-defined type predicate functions.
1522
1523 ``TypeIs`` can be used to annotate the return type of a user-defined
1524 type predicate function. ``TypeIs`` only accepts a single type argument.
1525 At runtime, functions marked this way should return a boolean and take at
1526 least one positional argument.
1527
1528 ``TypeIs`` aims to benefit *type narrowing* -- a technique used by static
1529 type checkers to determine a more precise type of an expression within a
1530 program's code flow. Usually type narrowing is done by analyzing
1531 conditional code flow and applying the narrowing to a block of code. The
1532 conditional expression here is sometimes referred to as a "type predicate"::
1533
1534 def is_str(val: str | float):
1535 # "isinstance" type predicate
1536 if isinstance(val, str):
1537 # Type of ``val`` is narrowed to ``str``
1538 ...
1539 else:
1540 # Else, type of ``val`` is narrowed to ``float``.
1541 ...
1542
1543 Sometimes it would be convenient to use a user-defined boolean function
1544 as a type predicate. Such a function should use ``TypeIs[...]`` or
1545 :data:`TypeGuard` as its return type to alert static type checkers to
1546 this intention. ``TypeIs`` usually has more intuitive behavior than
1547 ``TypeGuard``, but it cannot be used when the input and output types
1548 are incompatible (e.g., ``list[object]`` to ``list[int]``) or when the
1549 function does not return ``True`` for all instances of the narrowed type.
1550
1551 Using ``-> TypeIs[NarrowedType]`` tells the static type checker that for a given
1552 function:
1553
1554 1. The return value is a boolean.
1555 2. If the return value is ``True``, the type of its argument
1556 is the intersection of the argument's original type and ``NarrowedType``.
1557 3. If the return value is ``False``, the type of its argument
1558 is narrowed to exclude ``NarrowedType``.
1559
1560 For example::
1561
1562 from typing import assert_type, final, TypeIs
1563
1564 class Parent: pass
1565 class Child(Parent): pass
1566 @final
1567 class Unrelated: pass
1568
1569 def is_parent(val: object) -> TypeIs[Parent]:
1570 return isinstance(val, Parent)
1571
1572 def run(arg: Child | Unrelated):
1573 if is_parent(arg):
1574 # Type of ``arg`` is narrowed to the intersection
1575 # of ``Parent`` and ``Child``, which is equivalent to
1576 # ``Child``.
1577 assert_type(arg, Child)
1578 else:
1579 # Type of ``arg`` is narrowed to exclude ``Parent``,
1580 # so only ``Unrelated`` is left.
1581 assert_type(arg, Unrelated)
1582
1583 The type inside ``TypeIs`` must be consistent with the type of the
1584 function's argument; if it is not, static type checkers will raise
1585 an error. An incorrectly written ``TypeIs`` function can lead to
1586 unsound behavior in the type system; it is the user's responsibility
1587 to write such functions in a type-safe manner.
1588
1589 If a ``TypeIs`` function is a class or instance method, then the type in
1590 ``TypeIs`` maps to the type of the second parameter (after ``cls`` or
1591 ``self``).
1592
1593 In short, the form ``def foo(arg: TypeA) -> TypeIs[TypeB]: ...``,
1594 means that if ``foo(arg)`` returns ``True``, then ``arg`` is an instance
1595 of ``TypeB``, and if it returns ``False``, it is not an instance of ``TypeB``.
1596
1597 ``TypeIs`` also works with type variables. For more information, see
1598 :pep:`742` (Narrowing types with ``TypeIs``).
1599
1600 .. versionadded:: 3.13
1601
1602
1603 .. data:: TypeGuard
1604
1605 Special typing construct for marking user-defined type predicate functions.
1606
1607 Type predicate functions are user-defined functions that return whether their
1608 argument is an instance of a particular type.
1609 ``TypeGuard`` works similarly to :data:`TypeIs`, but has subtly different
1610 effects on type checking behavior (see below).
1611
1612 Using ``-> TypeGuard`` tells the static type checker that for a given
1613 function:
1614
1615 1. The return value is a boolean.
1616 2. If the return value is ``True``, the type of its argument
1617 is the type inside ``TypeGuard``.
1618
1619 ``TypeGuard`` also works with type variables. See :pep:`647` for more details.
1620
1621 For example::
1622
1623 def is_str_list(val: list[object]) -> TypeGuard[list[str]]:
1624 '''Determines whether all objects in the list are strings'''
1625 return all(isinstance(x, str) for x in val)
1626
1627 def func1(val: list[object]):
1628 if is_str_list(val):
1629 # Type of ``val`` is narrowed to ``list[str]``.
1630 print(" ".join(val))
1631 else:
1632 # Type of ``val`` remains as ``list[object]``.
1633 print("Not a list of strings!")
1634
1635 ``TypeIs`` and ``TypeGuard`` differ in the following ways:
1636
1637 * ``TypeIs`` requires the narrowed type to be a subtype of the input type, while
1638 ``TypeGuard`` does not. The main reason is to allow for things like
1639 narrowing ``list[object]`` to ``list[str]`` even though the latter
1640 is not a subtype of the former, since ``list`` is invariant.
1641 * When a ``TypeGuard`` function returns ``True``, type checkers narrow the type of the
1642 variable to exactly the ``TypeGuard`` type. When a ``TypeIs`` function returns ``True``,
1643 type checkers can infer a more precise type combining the previously known type of the
1644 variable with the ``TypeIs`` type. (Technically, this is known as an intersection type.)
1645 * When a ``TypeGuard`` function returns ``False``, type checkers cannot narrow the type of
1646 the variable at all. When a ``TypeIs`` function returns ``False``, type checkers can narrow
1647 the type of the variable to exclude the ``TypeIs`` type.
1648
1649 .. versionadded:: 3.10
1650
1651
1652 .. data:: Unpack
1653
1654 Typing operator to conceptually mark an object as having been unpacked.
1655
1656 For example, using the unpack operator ``*`` on a
1657 :ref:`type variable tuple <typevartuple>` is equivalent to using ``Unpack``
1658 to mark the type variable tuple as having been unpacked::
1659
1660 Ts = TypeVarTuple('Ts')
1661 tup: tuple[*Ts]
1662 # Effectively does:
1663 tup: tuple[Unpack[Ts]]
1664
1665 In fact, ``Unpack`` can be used interchangeably with ``*`` in the context
1666 of :class:`typing.TypeVarTuple <TypeVarTuple>` and
1667 :class:`builtins.tuple <tuple>` types. You might see ``Unpack`` being used
1668 explicitly in older versions of Python, where ``*`` couldn't be used in
1669 certain places::
1670
1671 # In older versions of Python, TypeVarTuple and Unpack
1672 # are located in the `typing_extensions` backports package.
1673 from typing_extensions import TypeVarTuple, Unpack
1674
1675 Ts = TypeVarTuple('Ts')
1676 tup: tuple[*Ts] # Syntax error on Python <= 3.10!
1677 tup: tuple[Unpack[Ts]] # Semantically equivalent, and backwards-compatible
1678
1679 ``Unpack`` can also be used along with :class:`typing.TypedDict` for typing
1680 ``**kwargs`` in a function signature::
1681
1682 from typing import TypedDict, Unpack
1683
1684 class Movie(TypedDict):
1685 name: str
1686 year: int
1687
1688 # This function expects two keyword arguments - `name` of type `str`
1689 # and `year` of type `int`.
1690 def foo(**kwargs: Unpack[Movie]): ...
1691
1692 See :pep:`692` for more details on using ``Unpack`` for ``**kwargs`` typing.
1693
1694 .. versionadded:: 3.11
1695
1696 Building generic types and type aliases
1697 """""""""""""""""""""""""""""""""""""""
1698
1699 The following classes should not be used directly as annotations.
1700 Their intended purpose is to be building blocks
1701 for creating generic types and type aliases.
1702
1703 These objects can be created through special syntax
1704 (:ref:`type parameter lists <type-params>` and the :keyword:`type` statement).
1705 For compatibility with Python 3.11 and earlier, they can also be created
1706 without the dedicated syntax, as documented below.
1707
1708 .. class:: Generic
1709
1710 Abstract base class for generic types.
1711
1712 A generic type is typically declared by adding a list of type parameters
1713 after the class name::
1714
1715 class Mapping[KT, VT]:
1716 def __getitem__(self, key: KT) -> VT:
1717 ...
1718 # Etc.
1719
1720 Such a class implicitly inherits from ``Generic``.
1721 The runtime semantics of this syntax are discussed in the
1722 :ref:`Language Reference <generic-classes>`.
1723
1724 This class can then be used as follows::
1725
1726 def lookup_name[X, Y](mapping: Mapping[X, Y], key: X, default: Y) -> Y:
1727 try:
1728 return mapping[key]
1729 except KeyError:
1730 return default
1731
1732 Here the brackets after the function name indicate a
1733 :ref:`generic function <generic-functions>`.
1734
1735 For backwards compatibility, generic classes can also be
1736 declared by explicitly inheriting from
1737 ``Generic``. In this case, the type parameters must be declared
1738 separately::
1739
1740 KT = TypeVar('KT')
1741 VT = TypeVar('VT')
1742
1743 class Mapping(Generic[KT, VT]):
1744 def __getitem__(self, key: KT) -> VT:
1745 ...
1746 # Etc.
1747
1748 .. _typevar:
1749
1750 .. class:: TypeVar(name, *constraints, bound=None, covariant=False, contravariant=False, infer_variance=False, default=typing.NoDefault)
1751
1752 Type variable.
1753
1754 The preferred way to construct a type variable is via the dedicated syntax
1755 for :ref:`generic functions <generic-functions>`,
1756 :ref:`generic classes <generic-classes>`, and
1757 :ref:`generic type aliases <generic-type-aliases>`::
1758
1759 class Sequence[T]: # T is a TypeVar
1760 ...
1761
1762 This syntax can also be used to create bounded and constrained type
1763 variables::
1764
1765 class StrSequence[S: str]: # S is a TypeVar with a `str` upper bound;
1766 ... # we can say that S is "bounded by `str`"
1767
1768
1769 class StrOrBytesSequence[A: (str, bytes)]: # A is a TypeVar constrained to str or bytes
1770 ...
1771
1772 However, if desired, reusable type variables can also be constructed manually, like so::
1773
1774 T = TypeVar('T') # Can be anything
1775 S = TypeVar('S', bound=str) # Can be any subtype of str
1776 A = TypeVar('A', str, bytes) # Must be exactly str or bytes
1777
1778 Type variables exist primarily for the benefit of static type
1779 checkers. They serve as the parameters for generic types as well
1780 as for generic function and type alias definitions.
1781 See :class:`Generic` for more
1782 information on generic types. Generic functions work as follows::
1783
1784 def repeat[T](x: T, n: int) -> Sequence[T]:
1785 """Return a list containing n references to x."""
1786 return [x]*n
1787
1788
1789 def print_capitalized[S: str](x: S) -> S:
1790 """Print x capitalized, and return x."""
1791 print(x.capitalize())
1792 return x
1793
1794
1795 def concatenate[A: (str, bytes)](x: A, y: A) -> A:
1796 """Add two strings or bytes objects together."""
1797 return x + y
1798
1799 Note that type variables can be *bounded*, *constrained*, or neither, but
1800 cannot be both bounded *and* constrained.
1801
1802 The variance of type variables is inferred by type checkers when they are created
1803 through the :ref:`type parameter syntax <type-params>` or when
1804 ``infer_variance=True`` is passed.
1805 Manually created type variables may be explicitly marked covariant or contravariant by passing
1806 ``covariant=True`` or ``contravariant=True``.
1807 By default, manually created type variables are invariant.
1808 See :pep:`484` and :pep:`695` for more details.
1809
1810 Bounded type variables and constrained type variables have different
1811 semantics in several important ways. Using a *bounded* type variable means
1812 that the ``TypeVar`` will be solved using the most specific type possible::
1813
1814 x = print_capitalized('a string')
1815 reveal_type(x) # revealed type is str
1816
1817 class StringSubclass(str):
1818 pass
1819
1820 y = print_capitalized(StringSubclass('another string'))
1821 reveal_type(y) # revealed type is StringSubclass
1822
1823 z = print_capitalized(45) # error: int is not a subtype of str
1824
1825 The upper bound of a type variable can be a concrete type, abstract type
1826 (ABC or Protocol), or even a union of types::
1827
1828 # Can be anything with an __abs__ method
1829 def print_abs[T: SupportsAbs](arg: T) -> None:
1830 print("Absolute value:", abs(arg))
1831
1832 U = TypeVar('U', bound=str|bytes) # Can be any subtype of the union str|bytes
1833 V = TypeVar('V', bound=SupportsAbs) # Can be anything with an __abs__ method
1834
1835 .. _typing-constrained-typevar:
1836
1837 Using a *constrained* type variable, however, means that the ``TypeVar``
1838 can only ever be solved as being exactly one of the constraints given::
1839
1840 a = concatenate('one', 'two')
1841 reveal_type(a) # revealed type is str
1842
1843 b = concatenate(StringSubclass('one'), StringSubclass('two'))
1844 reveal_type(b) # revealed type is str, despite StringSubclass being passed in
1845
1846 c = concatenate('one', b'two') # error: type variable 'A' can be either str or bytes in a function call, but not both
1847
1848 At runtime, ``isinstance(x, T)`` will raise :exc:`TypeError`.
1849
1850 .. attribute:: __name__
1851
1852 The name of the type variable.
1853
1854 .. attribute:: __covariant__
1855
1856 Whether the type var has been explicitly marked as covariant.
1857
1858 .. attribute:: __contravariant__
1859
1860 Whether the type var has been explicitly marked as contravariant.
1861
1862 .. attribute:: __infer_variance__
1863
1864 Whether the type variable's variance should be inferred by type checkers.
1865
1866 .. versionadded:: 3.12
1867
1868 .. attribute:: __bound__
1869
1870 The upper bound of the type variable, if any.
1871
1872 .. versionchanged:: 3.12
1873
1874 For type variables created through :ref:`type parameter syntax <type-params>`,
1875 the bound is evaluated only when the attribute is accessed, not when
1876 the type variable is created (see :ref:`lazy-evaluation`).
1877
1878 .. attribute:: __constraints__
1879
1880 A tuple containing the constraints of the type variable, if any.
1881
1882 .. versionchanged:: 3.12
1883
1884 For type variables created through :ref:`type parameter syntax <type-params>`,
1885 the constraints are evaluated only when the attribute is accessed, not when
1886 the type variable is created (see :ref:`lazy-evaluation`).
1887
1888 .. attribute:: __default__
1889
1890 The default value of the type variable, or :data:`typing.NoDefault` if it
1891 has no default.
1892
1893 .. versionadded:: 3.13
1894
1895 .. method:: has_default()
1896
1897 Return whether or not the type variable has a default value. This is equivalent
1898 to checking whether :attr:`__default__` is not the :data:`typing.NoDefault`
1899 singleton, except that it does not force evaluation of the
1900 :ref:`lazily evaluated <lazy-evaluation>` default value.
1901
1902 .. versionadded:: 3.13
1903
1904 .. versionchanged:: 3.12
1905
1906 Type variables can now be declared using the
1907 :ref:`type parameter <type-params>` syntax introduced by :pep:`695`.
1908 The ``infer_variance`` parameter was added.
1909
1910 .. versionchanged:: 3.13
1911
1912 Support for default values was added.
1913
1914 .. _typevartuple:
1915
1916 .. class:: TypeVarTuple(name, *, default=typing.NoDefault)
1917
1918 Type variable tuple. A specialized form of :ref:`type variable <typevar>`
1919 that enables *variadic* generics.
1920
1921 Type variable tuples can be declared in :ref:`type parameter lists <type-params>`
1922 using a single asterisk (``*``) before the name::
1923
1924 def move_first_element_to_last[T, *Ts](tup: tuple[T, *Ts]) -> tuple[*Ts, T]:
1925 return (*tup[1:], tup[0])
1926
1927 Or by explicitly invoking the ``TypeVarTuple`` constructor::
1928
1929 T = TypeVar("T")
1930 Ts = TypeVarTuple("Ts")
1931
1932 def move_first_element_to_last(tup: tuple[T, *Ts]) -> tuple[*Ts, T]:
1933 return (*tup[1:], tup[0])
1934
1935 A normal type variable enables parameterization with a single type. A type
1936 variable tuple, in contrast, allows parameterization with an
1937 *arbitrary* number of types by acting like an *arbitrary* number of type
1938 variables wrapped in a tuple. For example::
1939
1940 # T is bound to int, Ts is bound to ()
1941 # Return value is (1,), which has type tuple[int]
1942 move_first_element_to_last(tup=(1,))
1943
1944 # T is bound to int, Ts is bound to (str,)
1945 # Return value is ('spam', 1), which has type tuple[str, int]
1946 move_first_element_to_last(tup=(1, 'spam'))
1947
1948 # T is bound to int, Ts is bound to (str, float)
1949 # Return value is ('spam', 3.0, 1), which has type tuple[str, float, int]
1950 move_first_element_to_last(tup=(1, 'spam', 3.0))
1951
1952 # This fails to type check (and fails at runtime)
1953 # because tuple[()] is not compatible with tuple[T, *Ts]
1954 # (at least one element is required)
1955 move_first_element_to_last(tup=())
1956
1957 Note the use of the unpacking operator ``*`` in ``tuple[T, *Ts]``.
1958 Conceptually, you can think of ``Ts`` as a tuple of type variables
1959 ``(T1, T2, ...)``. ``tuple[T, *Ts]`` would then become
1960 ``tuple[T, *(T1, T2, ...)]``, which is equivalent to
1961 ``tuple[T, T1, T2, ...]``. (Note that in older versions of Python, you might
1962 see this written using :data:`Unpack <Unpack>` instead, as
1963 ``Unpack[Ts]``.)
1964
1965 Type variable tuples must *always* be unpacked. This helps distinguish type
1966 variable tuples from normal type variables::
1967
1968 x: Ts # Not valid
1969 x: tuple[Ts] # Not valid
1970 x: tuple[*Ts] # The correct way to do it
1971
1972 Type variable tuples can be used in the same contexts as normal type
1973 variables. For example, in class definitions, arguments, and return types::
1974
1975 class Array[*Shape]:
1976 def __getitem__(self, key: tuple[*Shape]) -> float: ...
1977 def __abs__(self) -> "Array[*Shape]": ...
1978 def get_shape(self) -> tuple[*Shape]: ...
1979
1980 Type variable tuples can be happily combined with normal type variables:
1981
1982 .. testcode::
1983
1984 class Array[DType, *Shape]: # This is fine
1985 pass
1986
1987 class Array2[*Shape, DType]: # This would also be fine
1988 pass
1989
1990 class Height: ...
1991 class Width: ...
1992
1993 float_array_1d: Array[float, Height] = Array() # Totally fine
1994 int_array_2d: Array[int, Height, Width] = Array() # Yup, fine too
1995
1996 However, note that at most one type variable tuple may appear in a single
1997 list of type arguments or type parameters::
1998
1999 x: tuple[*Ts, *Ts] # Not valid
2000 class Array[*Shape, *Shape]: # Not valid
2001 pass
2002
2003 Finally, an unpacked type variable tuple can be used as the type annotation
2004 of ``*args``::
2005
2006 def call_soon[*Ts](
2007 callback: Callable[[*Ts], None],
2008 *args: *Ts
2009 ) -> None:
2010 ...
2011 callback(*args)
2012
2013 In contrast to non-unpacked annotations of ``*args`` - e.g. ``*args: int``,
2014 which would specify that *all* arguments are ``int`` - ``*args: *Ts``
2015 enables reference to the types of the *individual* arguments in ``*args``.
2016 Here, this allows us to ensure the types of the ``*args`` passed
2017 to ``call_soon`` match the types of the (positional) arguments of
2018 ``callback``.
2019
2020 See :pep:`646` for more details on type variable tuples.
2021
2022 .. attribute:: __name__
2023
2024 The name of the type variable tuple.
2025
2026 .. attribute:: __default__
2027
2028 The default value of the type variable tuple, or :data:`typing.NoDefault` if it
2029 has no default.
2030
2031 .. versionadded:: 3.13
2032
2033 .. method:: has_default()
2034
2035 Return whether or not the type variable tuple has a default value. This is equivalent
2036 to checking whether :attr:`__default__` is not the :data:`typing.NoDefault`
2037 singleton, except that it does not force evaluation of the
2038 :ref:`lazily evaluated <lazy-evaluation>` default value.
2039
2040 .. versionadded:: 3.13
2041
2042 .. versionadded:: 3.11
2043
2044 .. versionchanged:: 3.12
2045
2046 Type variable tuples can now be declared using the
2047 :ref:`type parameter <type-params>` syntax introduced by :pep:`695`.
2048
2049 .. versionchanged:: 3.13
2050
2051 Support for default values was added.
2052
2053 .. class:: ParamSpec(name, *, bound=None, covariant=False, contravariant=False, default=typing.NoDefault)
2054
2055 Parameter specification variable. A specialized version of
2056 :ref:`type variables <typevar>`.
2057
2058 In :ref:`type parameter lists <type-params>`, parameter specifications
2059 can be declared with two asterisks (``**``)::
2060
2061 type IntFunc[**P] = Callable[P, int]
2062
2063 For compatibility with Python 3.11 and earlier, ``ParamSpec`` objects
2064 can also be created as follows::
2065
2066 P = ParamSpec('P')
2067
2068 Parameter specification variables exist primarily for the benefit of static
2069 type checkers. They are used to forward the parameter types of one
2070 callable to another callable -- a pattern commonly found in higher order
2071 functions and decorators. They are only valid when used in ``Concatenate``,
2072 or as the first argument to ``Callable``, or as parameters for user-defined
2073 Generics. See :class:`Generic` for more information on generic types.
2074
2075 For example, to add basic logging to a function, one can create a decorator
2076 ``add_logging`` to log function calls. The parameter specification variable
2077 tells the type checker that the callable passed into the decorator and the
2078 new callable returned by it have inter-dependent type parameters::
2079
2080 from collections.abc import Callable
2081 import logging
2082
2083 def add_logging[T, **P](f: Callable[P, T]) -> Callable[P, T]:
2084 '''A type-safe decorator to add logging to a function.'''
2085 def inner(*args: P.args, **kwargs: P.kwargs) -> T:
2086 logging.info(f'{f.__name__} was called')
2087 return f(*args, **kwargs)
2088 return inner
2089
2090 @add_logging
2091 def add_two(x: float, y: float) -> float:
2092 '''Add two numbers together.'''
2093 return x + y
2094
2095 Without ``ParamSpec``, the simplest way to annotate this previously was to
2096 use a :class:`TypeVar` with upper bound ``Callable[..., Any]``. However this
2097 causes two problems:
2098
2099 1. The type checker can't type check the ``inner`` function because
2100 ``*args`` and ``**kwargs`` have to be typed :data:`Any`.
2101 2. :func:`~cast` may be required in the body of the ``add_logging``
2102 decorator when returning the ``inner`` function, or the static type
2103 checker must be told to ignore the ``return inner``.
2104
2105 .. attribute:: args
2106 .. attribute:: kwargs
2107
2108 Since ``ParamSpec`` captures both positional and keyword parameters,
2109 ``P.args`` and ``P.kwargs`` can be used to split a ``ParamSpec`` into its
2110 components. ``P.args`` represents the tuple of positional parameters in a
2111 given call and should only be used to annotate ``*args``. ``P.kwargs``
2112 represents the mapping of keyword parameters to their values in a given call,
2113 and should be only be used to annotate ``**kwargs``. Both
2114 attributes require the annotated parameter to be in scope. At runtime,
2115 ``P.args`` and ``P.kwargs`` are instances respectively of
2116 :class:`ParamSpecArgs` and :class:`ParamSpecKwargs`.
2117
2118 .. attribute:: __name__
2119
2120 The name of the parameter specification.
2121
2122 .. attribute:: __default__
2123
2124 The default value of the parameter specification, or :data:`typing.NoDefault` if it
2125 has no default.
2126
2127 .. versionadded:: 3.13
2128
2129 .. method:: has_default()
2130
2131 Return whether or not the parameter specification has a default value. This is equivalent
2132 to checking whether :attr:`__default__` is not the :data:`typing.NoDefault`
2133 singleton, except that it does not force evaluation of the
2134 :ref:`lazily evaluated <lazy-evaluation>` default value.
2135
2136 .. versionadded:: 3.13
2137
2138 Parameter specification variables created with ``covariant=True`` or
2139 ``contravariant=True`` can be used to declare covariant or contravariant
2140 generic types. The ``bound`` argument is also accepted, similar to
2141 :class:`TypeVar`. However the actual semantics of these keywords are yet to
2142 be decided.
2143
2144 .. versionadded:: 3.10
2145
2146 .. versionchanged:: 3.12
2147
2148 Parameter specifications can now be declared using the
2149 :ref:`type parameter <type-params>` syntax introduced by :pep:`695`.
2150
2151 .. versionchanged:: 3.13
2152
2153 Support for default values was added.
2154
2155 .. note::
2156 Only parameter specification variables defined in global scope can
2157 be pickled.
2158
2159 .. seealso::
2160 * :pep:`612` -- Parameter Specification Variables (the PEP which introduced
2161 ``ParamSpec`` and ``Concatenate``)
2162 * :data:`Concatenate`
2163 * :ref:`annotating-callables`
2164
2165 .. data:: ParamSpecArgs
2166 ParamSpecKwargs
2167
2168 Arguments and keyword arguments attributes of a :class:`ParamSpec`. The
2169 ``P.args`` attribute of a ``ParamSpec`` is an instance of ``ParamSpecArgs``,
2170 and ``P.kwargs`` is an instance of ``ParamSpecKwargs``. They are intended
2171 for runtime introspection and have no special meaning to static type checkers.
2172
2173 Calling :func:`get_origin` on either of these objects will return the
2174 original ``ParamSpec``:
2175
2176 .. doctest::
2177
2178 >>> from typing import ParamSpec, get_origin
2179 >>> P = ParamSpec("P")
2180 >>> get_origin(P.args) is P
2181 True
2182 >>> get_origin(P.kwargs) is P
2183 True
2184
2185 .. versionadded:: 3.10
2186
2187
2188 .. class:: TypeAliasType(name, value, *, type_params=())
2189
2190 The type of type aliases created through the :keyword:`type` statement.
2191
2192 Example:
2193
2194 .. doctest::
2195
2196 >>> type Alias = int
2197 >>> type(Alias)
2198 <class 'typing.TypeAliasType'>
2199
2200 .. versionadded:: 3.12
2201
2202 .. attribute:: __name__
2203
2204 The name of the type alias:
2205
2206 .. doctest::
2207
2208 >>> type Alias = int
2209 >>> Alias.__name__
2210 'Alias'
2211
2212 .. attribute:: __module__
2213
2214 The name of the module in which the type alias was defined::
2215
2216 >>> type Alias = int
2217 >>> Alias.__module__
2218 '__main__'
2219
2220 .. attribute:: __type_params__
2221
2222 The type parameters of the type alias, or an empty tuple if the alias is
2223 not generic:
2224
2225 .. doctest::
2226
2227 >>> type ListOrSet[T] = list[T] | set[T]
2228 >>> ListOrSet.__type_params__
2229 (T,)
2230 >>> type NotGeneric = int
2231 >>> NotGeneric.__type_params__
2232 ()
2233
2234 .. attribute:: __value__
2235
2236 The type alias's value. This is :ref:`lazily evaluated <lazy-evaluation>`,
2237 so names used in the definition of the alias are not resolved until the
2238 ``__value__`` attribute is accessed:
2239
2240 .. doctest::
2241
2242 >>> type Mutually = Recursive
2243 >>> type Recursive = Mutually
2244 >>> Mutually
2245 Mutually
2246 >>> Recursive
2247 Recursive
2248 >>> Mutually.__value__
2249 Recursive
2250 >>> Recursive.__value__
2251 Mutually
2252
2253 Other special directives
2254 """"""""""""""""""""""""
2255
2256 These functions and classes should not be used directly as annotations.
2257 Their intended purpose is to be building blocks for creating and declaring
2258 types.
2259
2260 .. class:: NamedTuple
2261
2262 Typed version of :func:`collections.namedtuple`.
2263
2264 Usage::
2265
2266 class Employee(NamedTuple):
2267 name: str
2268 id: int
2269
2270 This is equivalent to::
2271
2272 Employee = collections.namedtuple('Employee', ['name', 'id'])
2273
2274 To give a field a default value, you can assign to it in the class body::
2275
2276 class Employee(NamedTuple):
2277 name: str
2278 id: int = 3
2279
2280 employee = Employee('Guido')
2281 assert employee.id == 3
2282
2283 Fields with a default value must come after any fields without a default.
2284
2285 The resulting class has an extra attribute ``__annotations__`` giving a
2286 dict that maps the field names to the field types. (The field names are in
2287 the ``_fields`` attribute and the default values are in the
2288 ``_field_defaults`` attribute, both of which are part of the :func:`~collections.namedtuple`
2289 API.)
2290
2291 ``NamedTuple`` subclasses can also have docstrings and methods::
2292
2293 class Employee(NamedTuple):
2294 """Represents an employee."""
2295 name: str
2296 id: int = 3
2297
2298 def __repr__(self) -> str:
2299 return f'<Employee {self.name}, id={self.id}>'
2300
2301 ``NamedTuple`` subclasses can be generic::
2302
2303 class Group[T](NamedTuple):
2304 key: T
2305 group: list[T]
2306
2307 Backward-compatible usage::
2308
2309 # For creating a generic NamedTuple on Python 3.11
2310 T = TypeVar("T")
2311
2312 class Group(NamedTuple, Generic[T]):
2313 key: T
2314 group: list[T]
2315
2316 # A functional syntax is also supported
2317 Employee = NamedTuple('Employee', [('name', str), ('id', int)])
2318
2319 .. versionchanged:: 3.6
2320 Added support for :pep:`526` variable annotation syntax.
2321
2322 .. versionchanged:: 3.6.1
2323 Added support for default values, methods, and docstrings.
2324
2325 .. versionchanged:: 3.8
2326 The ``_field_types`` and ``__annotations__`` attributes are
2327 now regular dictionaries instead of instances of ``OrderedDict``.
2328
2329 .. versionchanged:: 3.9
2330 Removed the ``_field_types`` attribute in favor of the more
2331 standard ``__annotations__`` attribute which has the same information.
2332
2333 .. versionchanged:: 3.9
2334 ``NamedTuple`` is now a function rather than a class.
2335 It can still be used as a class base, as described above.
2336
2337 .. versionchanged:: 3.11
2338 Added support for generic namedtuples.
2339
2340 .. deprecated-removed:: 3.13 3.15
2341 The undocumented keyword argument syntax for creating NamedTuple classes
2342 (``NT = NamedTuple("NT", x=int)``) is deprecated, and will be disallowed
2343 in 3.15. Use the class-based syntax or the functional syntax instead.
2344
2345 .. deprecated-removed:: 3.13 3.15
2346 When using the functional syntax to create a NamedTuple class, failing to
2347 pass a value to the 'fields' parameter (``NT = NamedTuple("NT")``) is
2348 deprecated. Passing ``None`` to the 'fields' parameter
2349 (``NT = NamedTuple("NT", None)``) is also deprecated. Both will be
2350 disallowed in Python 3.15. To create a NamedTuple class with 0 fields,
2351 use ``class NT(NamedTuple): pass`` or ``NT = NamedTuple("NT", [])``.
2352
2353 .. class:: NewType(name, tp)
2354
2355 Helper class to create low-overhead :ref:`distinct types <distinct>`.
2356
2357 A ``NewType`` is considered a distinct type by a typechecker. At runtime,
2358 however, calling a ``NewType`` returns its argument unchanged.
2359
2360 Usage::
2361
2362 UserId = NewType('UserId', int) # Declare the NewType "UserId"
2363 first_user = UserId(1) # "UserId" returns the argument unchanged at runtime
2364
2365 .. attribute:: __module__
2366
2367 The name of the module in which the new type is defined.
2368
2369 .. attribute:: __name__
2370
2371 The name of the new type.
2372
2373 .. attribute:: __supertype__
2374
2375 The type that the new type is based on.
2376
2377 .. versionadded:: 3.5.2
2378
2379 .. versionchanged:: 3.10
2380 ``NewType`` is now a class rather than a function.
2381
2382 .. class:: Protocol(Generic)
2383
2384 Base class for protocol classes.
2385
2386 Protocol classes are defined like this::
2387
2388 class Proto(Protocol):
2389 def meth(self) -> int:
2390 ...
2391
2392 Such classes are primarily used with static type checkers that recognize
2393 structural subtyping (static duck-typing), for example::
2394
2395 class C:
2396 def meth(self) -> int:
2397 return 0
2398
2399 def func(x: Proto) -> int:
2400 return x.meth()
2401
2402 func(C()) # Passes static type check
2403
2404 See :pep:`544` for more details. Protocol classes decorated with
2405 :func:`runtime_checkable` (described later) act as simple-minded runtime
2406 protocols that check only the presence of given attributes, ignoring their
2407 type signatures. Protocol classes without this decorator cannot be used
2408 as the second argument to :func:`isinstance` or :func:`issubclass`.
2409
2410 Protocol classes can be generic, for example::
2411
2412 class GenProto[T](Protocol):
2413 def meth(self) -> T:
2414 ...
2415
2416 In code that needs to be compatible with Python 3.11 or older, generic
2417 Protocols can be written as follows::
2418
2419 T = TypeVar("T")
2420
2421 class GenProto(Protocol[T]):
2422 def meth(self) -> T:
2423 ...
2424
2425 .. versionadded:: 3.8
2426
2427 .. decorator:: runtime_checkable
2428
2429 Mark a protocol class as a runtime protocol.
2430
2431 Such a protocol can be used with :func:`isinstance` and :func:`issubclass`.
2432 This allows a simple-minded structural check, very similar to "one trick ponies"
2433 in :mod:`collections.abc` such as :class:`~collections.abc.Iterable`. For example::
2434
2435 @runtime_checkable
2436 class Closable(Protocol):
2437 def close(self): ...
2438
2439 assert isinstance(open('/some/file'), Closable)
2440
2441 @runtime_checkable
2442 class Named(Protocol):
2443 name: str
2444
2445 import threading
2446 assert isinstance(threading.Thread(name='Bob'), Named)
2447
2448 This decorator raises :exc:`TypeError` when applied to a non-protocol class.
2449
2450 .. note::
2451
2452 :func:`!runtime_checkable` will check only the presence of the required
2453 methods or attributes, not their type signatures or types.
2454 For example, :class:`ssl.SSLObject`
2455 is a class, therefore it passes an :func:`issubclass`
2456 check against :ref:`Callable <annotating-callables>`. However, the
2457 ``ssl.SSLObject.__init__`` method exists only to raise a
2458 :exc:`TypeError` with a more informative message, therefore making
2459 it impossible to call (instantiate) :class:`ssl.SSLObject`.
2460
2461 .. note::
2462
2463 An :func:`isinstance` check against a runtime-checkable protocol can be
2464 surprisingly slow compared to an ``isinstance()`` check against
2465 a non-protocol class. Consider using alternative idioms such as
2466 :func:`hasattr` calls for structural checks in performance-sensitive
2467 code.
2468
2469 .. versionadded:: 3.8
2470
2471 .. versionchanged:: 3.12
2472 The internal implementation of :func:`isinstance` checks against
2473 runtime-checkable protocols now uses :func:`inspect.getattr_static`
2474 to look up attributes (previously, :func:`hasattr` was used).
2475 As a result, some objects which used to be considered instances
2476 of a runtime-checkable protocol may no longer be considered instances
2477 of that protocol on Python 3.12+, and vice versa.
2478 Most users are unlikely to be affected by this change.
2479
2480 .. versionchanged:: 3.12
2481 The members of a runtime-checkable protocol are now considered "frozen"
2482 at runtime as soon as the class has been created. Monkey-patching
2483 attributes onto a runtime-checkable protocol will still work, but will
2484 have no impact on :func:`isinstance` checks comparing objects to the
2485 protocol. See :ref:`What's new in Python 3.12 <whatsnew-typing-py312>`
2486 for more details.
2487
2488
2489 .. class:: TypedDict(dict)
2490
2491 Special construct to add type hints to a dictionary.
2492 At runtime ":class:`!TypedDict` instances" are simply :class:`dicts <dict>`.
2493
2494 ``TypedDict`` declares a dictionary type that expects all of its
2495 instances to have a certain set of keys, where each key is
2496 associated with a value of a consistent type. This expectation
2497 is not checked at runtime but is only enforced by type checkers.
2498 Usage::
2499
2500 class Point2D(TypedDict):
2501 x: int
2502 y: int
2503 label: str
2504
2505 a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
2506 b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
2507
2508 assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
2509
2510 An alternative way to create a ``TypedDict`` is by using
2511 function-call syntax. The second argument must be a literal :class:`dict`::
2512
2513 Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
2514
2515 This functional syntax allows defining keys which are not valid
2516 :ref:`identifiers <identifiers>`, for example because they are
2517 keywords or contain hyphens, or when key names must not be
2518 :ref:`mangled <private-name-mangling>` like regular private names::
2519
2520 # raises SyntaxError
2521 class Point2D(TypedDict):
2522 in: int # 'in' is a keyword
2523 x-y: int # name with hyphens
2524
2525 class Definition(TypedDict):
2526 __schema: str # mangled to `_Definition__schema`
2527
2528 # OK, functional syntax
2529 Point2D = TypedDict('Point2D', {'in': int, 'x-y': int})
2530 Definition = TypedDict('Definition', {'__schema': str}) # not mangled
2531
2532 By default, all keys must be present in a ``TypedDict``. It is possible to
2533 mark individual keys as non-required using :data:`NotRequired`::
2534
2535 class Point2D(TypedDict):
2536 x: int
2537 y: int
2538 label: NotRequired[str]
2539
2540 # Alternative syntax
2541 Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': NotRequired[str]})
2542
2543 This means that a ``Point2D`` ``TypedDict`` can have the ``label``
2544 key omitted.
2545
2546 It is also possible to mark all keys as non-required by default
2547 by specifying a totality of ``False``::
2548
2549 class Point2D(TypedDict, total=False):
2550 x: int
2551 y: int
2552
2553 # Alternative syntax
2554 Point2D = TypedDict('Point2D', {'x': int, 'y': int}, total=False)
2555
2556 This means that a ``Point2D`` ``TypedDict`` can have any of the keys
2557 omitted. A type checker is only expected to support a literal ``False`` or
2558 ``True`` as the value of the ``total`` argument. ``True`` is the default,
2559 and makes all items defined in the class body required.
2560
2561 Individual keys of a ``total=False`` ``TypedDict`` can be marked as
2562 required using :data:`Required`::
2563
2564 class Point2D(TypedDict, total=False):
2565 x: Required[int]
2566 y: Required[int]
2567 label: str
2568
2569 # Alternative syntax
2570 Point2D = TypedDict('Point2D', {
2571 'x': Required[int],
2572 'y': Required[int],
2573 'label': str
2574 }, total=False)
2575
2576 It is possible for a ``TypedDict`` type to inherit from one or more other ``TypedDict`` types
2577 using the class-based syntax.
2578 Usage::
2579
2580 class Point3D(Point2D):
2581 z: int
2582
2583 ``Point3D`` has three items: ``x``, ``y`` and ``z``. It is equivalent to this
2584 definition::
2585
2586 class Point3D(TypedDict):
2587 x: int
2588 y: int
2589 z: int
2590
2591 A ``TypedDict`` cannot inherit from a non-\ ``TypedDict`` class,
2592 except for :class:`Generic`. For example::
2593
2594 class X(TypedDict):
2595 x: int
2596
2597 class Y(TypedDict):
2598 y: int
2599
2600 class Z(object): pass # A non-TypedDict class
2601
2602 class XY(X, Y): pass # OK
2603
2604 class XZ(X, Z): pass # raises TypeError
2605
2606 A ``TypedDict`` can be generic::
2607
2608 class Group[T](TypedDict):
2609 key: T
2610 group: list[T]
2611
2612 To create a generic ``TypedDict`` that is compatible with Python 3.11
2613 or lower, inherit from :class:`Generic` explicitly:
2614
2615 .. testcode::
2616
2617 T = TypeVar("T")
2618
2619 class Group(TypedDict, Generic[T]):
2620 key: T
2621 group: list[T]
2622
2623 A ``TypedDict`` can be introspected via annotations dicts
2624 (see :ref:`annotations-howto` for more information on annotations best practices),
2625 :attr:`__total__`, :attr:`__required_keys__`, and :attr:`__optional_keys__`.
2626
2627 .. attribute:: __total__
2628
2629 ``Point2D.__total__`` gives the value of the ``total`` argument.
2630 Example:
2631
2632 .. doctest::
2633
2634 >>> from typing import TypedDict
2635 >>> class Point2D(TypedDict): pass
2636 >>> Point2D.__total__
2637 True
2638 >>> class Point2D(TypedDict, total=False): pass
2639 >>> Point2D.__total__
2640 False
2641 >>> class Point3D(Point2D): pass
2642 >>> Point3D.__total__
2643 True
2644
2645 This attribute reflects *only* the value of the ``total`` argument
2646 to the current ``TypedDict`` class, not whether the class is semantically
2647 total. For example, a ``TypedDict`` with ``__total__`` set to ``True`` may
2648 have keys marked with :data:`NotRequired`, or it may inherit from another
2649 ``TypedDict`` with ``total=False``. Therefore, it is generally better to use
2650 :attr:`__required_keys__` and :attr:`__optional_keys__` for introspection.
2651
2652 .. attribute:: __required_keys__
2653
2654 .. versionadded:: 3.9
2655
2656 .. attribute:: __optional_keys__
2657
2658 ``Point2D.__required_keys__`` and ``Point2D.__optional_keys__`` return
2659 :class:`frozenset` objects containing required and non-required keys, respectively.
2660
2661 Keys marked with :data:`Required` will always appear in ``__required_keys__``
2662 and keys marked with :data:`NotRequired` will always appear in ``__optional_keys__``.
2663
2664 For backwards compatibility with Python 3.10 and below,
2665 it is also possible to use inheritance to declare both required and
2666 non-required keys in the same ``TypedDict`` . This is done by declaring a
2667 ``TypedDict`` with one value for the ``total`` argument and then
2668 inheriting from it in another ``TypedDict`` with a different value for
2669 ``total``:
2670
2671 .. doctest::
2672
2673 >>> class Point2D(TypedDict, total=False):
2674 ... x: int
2675 ... y: int
2676 ...
2677 >>> class Point3D(Point2D):
2678 ... z: int
2679 ...
2680 >>> Point3D.__required_keys__ == frozenset({'z'})
2681 True
2682 >>> Point3D.__optional_keys__ == frozenset({'x', 'y'})
2683 True
2684
2685 .. versionadded:: 3.9
2686
2687 .. note::
2688
2689 If ``from __future__ import annotations`` is used or if annotations
2690 are given as strings, annotations are not evaluated when the
2691 ``TypedDict`` is defined. Therefore, the runtime introspection that
2692 ``__required_keys__`` and ``__optional_keys__`` rely on may not work
2693 properly, and the values of the attributes may be incorrect.
2694
2695 Support for :data:`ReadOnly` is reflected in the following attributes:
2696
2697 .. attribute:: __readonly_keys__
2698
2699 A :class:`frozenset` containing the names of all read-only keys. Keys
2700 are read-only if they carry the :data:`ReadOnly` qualifier.
2701
2702 .. versionadded:: 3.13
2703
2704 .. attribute:: __mutable_keys__
2705
2706 A :class:`frozenset` containing the names of all mutable keys. Keys
2707 are mutable if they do not carry the :data:`ReadOnly` qualifier.
2708
2709 .. versionadded:: 3.13
2710
2711 See :pep:`589` for more examples and detailed rules of using ``TypedDict``.
2712
2713 .. versionadded:: 3.8
2714
2715 .. versionchanged:: 3.9
2716 ``TypedDict`` is now a function rather than a class.
2717 It can still be used as a class base, as described above.
2718
2719 .. versionchanged:: 3.11
2720 Added support for marking individual keys as :data:`Required` or :data:`NotRequired`.
2721 See :pep:`655`.
2722
2723 .. versionchanged:: 3.11
2724 Added support for generic ``TypedDict``\ s.
2725
2726 .. versionchanged:: 3.13
2727 Removed support for the keyword-argument method of creating ``TypedDict``\ s.
2728
2729 .. versionchanged:: 3.13
2730 Support for the :data:`ReadOnly` qualifier was added.
2731
2732 .. deprecated-removed:: 3.13 3.15
2733 When using the functional syntax to create a TypedDict class, failing to
2734 pass a value to the 'fields' parameter (``TD = TypedDict("TD")``) is
2735 deprecated. Passing ``None`` to the 'fields' parameter
2736 (``TD = TypedDict("TD", None)``) is also deprecated. Both will be
2737 disallowed in Python 3.15. To create a TypedDict class with 0 fields,
2738 use ``class TD(TypedDict): pass`` or ``TD = TypedDict("TD", {})``.
2739
2740 Protocols
2741 ---------
2742
2743 The following protocols are provided by the :mod:`!typing` module. All are decorated
2744 with :deco:`runtime_checkable`.
2745
2746 .. class:: SupportsAbs
2747
2748 An ABC with one abstract method ``__abs__`` that is covariant
2749 in its return type.
2750
2751 .. class:: SupportsBytes
2752
2753 An ABC with one abstract method ``__bytes__``.
2754
2755 .. class:: SupportsComplex
2756
2757 An ABC with one abstract method ``__complex__``.
2758
2759 .. class:: SupportsFloat
2760
2761 An ABC with one abstract method ``__float__``.
2762
2763 .. class:: SupportsIndex
2764
2765 An ABC with one abstract method ``__index__``.
2766
2767 .. versionadded:: 3.8
2768
2769 .. class:: SupportsInt
2770
2771 An ABC with one abstract method ``__int__``.
2772
2773 .. class:: SupportsRound
2774
2775 An ABC with one abstract method ``__round__``
2776 that is covariant in its return type.
2777
2778 ABCs for working with IO
2779 ------------------------
2780
2781 .. class:: IO
2782 TextIO
2783 BinaryIO
2784
2785 Generic type ``IO[AnyStr]`` and its subclasses ``TextIO(IO[str])``
2786 and ``BinaryIO(IO[bytes])``
2787 represent the types of I/O streams such as returned by
2788 :func:`open`.
2789
2790 Functions and decorators
2791 ------------------------
2792
2793 .. function:: cast(typ, val)
2794
2795 Cast a value to a type.
2796
2797 This returns the value unchanged. To the type checker this
2798 signals that the return value has the designated type, but at
2799 runtime we intentionally don't check anything (we want this
2800 to be as fast as possible).
2801
2802 .. function:: assert_type(val, typ, /)
2803
2804 Ask a static type checker to confirm that *val* has an inferred type of *typ*.
2805
2806 At runtime this does nothing: it returns the first argument unchanged with no
2807 checks or side effects, no matter the actual type of the argument.
2808
2809 When a static type checker encounters a call to ``assert_type()``, it
2810 emits an error if the value is not of the specified type::
2811
2812 def greet(name: str) -> None:
2813 assert_type(name, str) # OK, inferred type of `name` is `str`
2814 assert_type(name, int) # type checker error
2815
2816 This function is useful for ensuring the type checker's understanding of a
2817 script is in line with the developer's intentions::
2818
2819 def complex_function(arg: object):
2820 # Do some complex type-narrowing logic,
2821 # after which we hope the inferred type will be `int`
2822 ...
2823 # Test whether the type checker correctly understands our function
2824 assert_type(arg, int)
2825
2826 .. versionadded:: 3.11
2827
2828 .. function:: assert_never(arg, /)
2829
2830 Ask a static type checker to confirm that a line of code is unreachable.
2831
2832 Example::
2833
2834 def int_or_str(arg: int | str) -> None:
2835 match arg:
2836 case int():
2837 print("It's an int")
2838 case str():
2839 print("It's a str")
2840 case _ as unreachable:
2841 assert_never(unreachable)
2842
2843 Here, the annotations allow the type checker to infer that the
2844 last case can never execute, because ``arg`` is either
2845 an :class:`int` or a :class:`str`, and both options are covered by
2846 earlier cases.
2847
2848 If a type checker finds that a call to ``assert_never()`` is
2849 reachable, it will emit an error. For example, if the type annotation
2850 for ``arg`` was instead ``int | str | float``, the type checker would
2851 emit an error pointing out that ``unreachable`` is of type :class:`float`.
2852 For a call to ``assert_never`` to pass type checking, the inferred type of
2853 the argument passed in must be the bottom type, :data:`Never`, and nothing
2854 else.
2855
2856 At runtime, this throws an exception when called.
2857
2858 .. seealso::
2859 `Unreachable Code and Exhaustiveness Checking
2860 <https://typing.python.org/en/latest/guides/unreachable.html>`__ has more
2861 information about exhaustiveness checking with static typing.
2862
2863 .. versionadded:: 3.11
2864
2865 .. function:: reveal_type(obj, /)
2866
2867 Ask a static type checker to reveal the inferred type of an expression.
2868
2869 When a static type checker encounters a call to this function,
2870 it emits a diagnostic with the inferred type of the argument. For example::
2871
2872 x: int = 1
2873 reveal_type(x) # Revealed type is "builtins.int"
2874
2875 This can be useful when you want to debug how your type checker
2876 handles a particular piece of code.
2877
2878 At runtime, this function prints the runtime type of its argument to
2879 :data:`sys.stderr` and returns the argument unchanged (allowing the call to
2880 be used within an expression)::
2881
2882 x = reveal_type(1) # prints "Runtime type is int"
2883 print(x) # prints "1"
2884
2885 Note that the runtime type may be different from (more or less specific
2886 than) the type statically inferred by a type checker.
2887
2888 Most type checkers support ``reveal_type()`` anywhere, even if the
2889 name is not imported from ``typing``. Importing the name from
2890 ``typing``, however, allows your code to run without runtime errors and
2891 communicates intent more clearly.
2892
2893 .. versionadded:: 3.11
2894
2895 .. decorator:: dataclass_transform(*, eq_default=True, order_default=False, \
2896 kw_only_default=False, frozen_default=False, \
2897 field_specifiers=(), **kwargs)
2898
2899 Decorator to mark an object as providing
2900 :func:`dataclass <dataclasses.dataclass>`-like behavior.
2901
2902 ``dataclass_transform`` may be used to
2903 decorate a class, metaclass, or a function that is itself a decorator.
2904 The presence of ``@dataclass_transform()`` tells a static type checker that the
2905 decorated object performs runtime "magic" that
2906 transforms a class in a similar way to
2907 :deco:`dataclasses.dataclass`.
2908
2909 Example usage with a decorator function:
2910
2911 .. testcode::
2912
2913 @dataclass_transform()
2914 def create_model[T](cls: type[T]) -> type[T]:
2915 ...
2916 return cls
2917
2918 @create_model
2919 class CustomerModel:
2920 id: int
2921 name: str
2922
2923 On a base class::
2924
2925 @dataclass_transform()
2926 class ModelBase: ...
2927
2928 class CustomerModel(ModelBase):
2929 id: int
2930 name: str
2931
2932 On a metaclass::
2933
2934 @dataclass_transform()
2935 class ModelMeta(type): ...
2936
2937 class ModelBase(metaclass=ModelMeta): ...
2938
2939 class CustomerModel(ModelBase):
2940 id: int
2941 name: str
2942
2943 The ``CustomerModel`` classes defined above will
2944 be treated by type checkers similarly to classes created with
2945 :deco:`dataclasses.dataclass`.
2946 For example, type checkers will assume these classes have
2947 ``__init__`` methods that accept ``id`` and ``name``.
2948
2949 The decorated class, metaclass, or function may accept the following bool
2950 arguments which type checkers will assume have the same effect as they
2951 would have on the
2952 :deco:`dataclasses.dataclass` decorator: ``init``,
2953 ``eq``, ``order``, ``unsafe_hash``, ``frozen``, ``match_args``,
2954 ``kw_only``, and ``slots``. It must be possible for the value of these
2955 arguments (``True`` or ``False``) to be statically evaluated.
2956
2957 The arguments to the ``dataclass_transform`` decorator can be used to
2958 customize the default behaviors of the decorated class, metaclass, or
2959 function:
2960
2961 :param bool eq_default:
2962 Indicates whether the ``eq`` parameter is assumed to be
2963 ``True`` or ``False`` if it is omitted by the caller.
2964 Defaults to ``True``.
2965
2966 :param bool order_default:
2967 Indicates whether the ``order`` parameter is
2968 assumed to be ``True`` or ``False`` if it is omitted by the caller.
2969 Defaults to ``False``.
2970
2971 :param bool kw_only_default:
2972 Indicates whether the ``kw_only`` parameter is
2973 assumed to be ``True`` or ``False`` if it is omitted by the caller.
2974 Defaults to ``False``.
2975
2976 :param bool frozen_default:
2977 Indicates whether the ``frozen`` parameter is
2978 assumed to be ``True`` or ``False`` if it is omitted by the caller.
2979 Defaults to ``False``.
2980
2981 .. versionadded:: 3.12
2982
2983 :param field_specifiers:
2984 Specifies a static list of supported classes
2985 or functions that describe fields, similar to :func:`dataclasses.field`.
2986 Defaults to ``()``.
2987 :type field_specifiers: tuple[Callable[..., Any], ...]
2988
2989 :param Any \**kwargs:
2990 Arbitrary other keyword arguments are accepted in order to allow for
2991 possible future extensions.
2992
2993 Type checkers recognize the following optional parameters on field
2994 specifiers:
2995
2996 .. list-table:: **Recognised parameters for field specifiers**
2997 :header-rows: 1
2998 :widths: 20 80
2999
3000 * - Parameter name
3001 - Description
3002 * - ``init``
3003 - Indicates whether the field should be included in the
3004 synthesized ``__init__`` method. If unspecified, ``init`` defaults to
3005 ``True``.
3006 * - ``default``
3007 - Provides the default value for the field.
3008 * - ``default_factory``
3009 - Provides a runtime callback that returns the
3010 default value for the field. If neither ``default`` nor
3011 ``default_factory`` are specified, the field is assumed to have no
3012 default value and must be provided a value when the class is
3013 instantiated.
3014 * - ``factory``
3015 - An alias for the ``default_factory`` parameter on field specifiers.
3016 * - ``kw_only``
3017 - Indicates whether the field should be marked as
3018 keyword-only. If ``True``, the field will be keyword-only. If
3019 ``False``, it will not be keyword-only. If unspecified, the value of
3020 the ``kw_only`` parameter on the object decorated with
3021 ``dataclass_transform`` will be used, or if that is unspecified, the
3022 value of ``kw_only_default`` on ``dataclass_transform`` will be used.
3023 * - ``alias``
3024 - Provides an alternative name for the field. This alternative
3025 name is used in the synthesized ``__init__`` method.
3026
3027 At runtime, this decorator records its arguments in the
3028 ``__dataclass_transform__`` attribute on the decorated object.
3029 It has no other runtime effect.
3030
3031 See :pep:`681` for more details.
3032
3033 .. versionadded:: 3.11
3034
3035 .. _overload:
3036
3037 .. decorator:: overload
3038
3039 Decorator for creating overloaded functions and methods.
3040
3041 The ``@overload`` decorator allows describing functions and methods
3042 that support multiple different combinations of argument types. A series
3043 of ``@overload``-decorated definitions must be followed by exactly one
3044 non-``@overload``-decorated definition (for the same function/method).
3045
3046 ``@overload``-decorated definitions are for the benefit of the
3047 type checker only, since they will be overwritten by the
3048 non-``@overload``-decorated definition. The non-``@overload``-decorated
3049 definition, meanwhile, will be used at
3050 runtime but should be ignored by a type checker. At runtime, calling
3051 an ``@overload``-decorated function directly will raise
3052 :exc:`NotImplementedError`.
3053
3054 An example of overload that gives a more
3055 precise type than can be expressed using a union or a type variable:
3056
3057 .. testcode::
3058
3059 @overload
3060 def process(response: None) -> None:
3061 ...
3062 @overload
3063 def process(response: int) -> tuple[int, str]:
3064 ...
3065 @overload
3066 def process(response: bytes) -> str:
3067 ...
3068 def process(response):
3069 ... # actual implementation goes here
3070
3071 See :pep:`484` for more details and comparison with other typing semantics.
3072
3073 .. versionchanged:: 3.11
3074 Overloaded functions can now be introspected at runtime using
3075 :func:`get_overloads`.
3076
3077
3078 .. function:: get_overloads(func)
3079
3080 Return a sequence of :deco:`overload`-decorated definitions for
3081 *func*.
3082
3083 *func* is the function object for the implementation of the
3084 overloaded function. For example, given the definition of ``process`` in
3085 the documentation for :deco:`overload`,
3086 ``get_overloads(process)`` will return a sequence of three function objects
3087 for the three defined overloads. If called on a function with no overloads,
3088 ``get_overloads()`` returns an empty sequence.
3089
3090 ``get_overloads()`` can be used for introspecting an overloaded function at
3091 runtime.
3092
3093 .. versionadded:: 3.11
3094
3095
3096 .. function:: clear_overloads()
3097
3098 Clear all registered overloads in the internal registry.
3099
3100 This can be used to reclaim the memory used by the registry.
3101
3102 .. versionadded:: 3.11
3103
3104
3105 .. decorator:: final
3106
3107 Decorator to indicate final methods and final classes.
3108
3109 Decorating a method with ``@final`` indicates to a type checker that the
3110 method cannot be overridden in a subclass. Decorating a class with ``@final``
3111 indicates that it cannot be subclassed.
3112
3113 For example::
3114
3115 class Base:
3116 @final
3117 def done(self) -> None:
3118 ...
3119 class Sub(Base):
3120 def done(self) -> None: # Error reported by type checker
3121 ...
3122
3123 @final
3124 class Leaf:
3125 ...
3126 class Other(Leaf): # Error reported by type checker
3127 ...
3128
3129 There is no runtime checking of these properties. See :pep:`591` for
3130 more details.
3131
3132 .. versionadded:: 3.8
3133
3134 .. versionchanged:: 3.11
3135 The decorator will now attempt to set a ``__final__`` attribute to ``True``
3136 on the decorated object. Thus, a check like
3137 ``if getattr(obj, "__final__", False)`` can be used at runtime
3138 to determine whether an object ``obj`` has been marked as final.
3139 If the decorated object does not support setting attributes,
3140 the decorator returns the object unchanged without raising an exception.
3141
3142
3143 .. decorator:: no_type_check
3144
3145 Decorator to indicate that annotations are not type hints.
3146
3147 This works as a class or function :term:`decorator`. With a class, it
3148 applies recursively to all methods and classes defined in that class
3149 (but not to methods defined in its superclasses or subclasses). Type
3150 checkers will ignore all annotations in a function or class with this
3151 decorator.
3152
3153 ``@no_type_check`` mutates the decorated object in place.
3154
3155 .. decorator:: no_type_check_decorator
3156
3157 Decorator to give another decorator the :func:`no_type_check` effect.
3158
3159 This wraps the decorator with something that wraps the decorated
3160 function in :func:`no_type_check`.
3161
3162 .. deprecated-removed:: 3.13 3.15
3163 No type checker ever added support for ``@no_type_check_decorator``. It
3164 is therefore deprecated, and will be removed in Python 3.15.
3165
3166 .. decorator:: override
3167
3168 Decorator to indicate that a method in a subclass is intended to override a
3169 method or attribute in a superclass.
3170
3171 Type checkers should emit an error if a method decorated with ``@override``
3172 does not, in fact, override anything.
3173 This helps prevent bugs that may occur when a base class is changed without
3174 an equivalent change to a child class.
3175
3176 For example:
3177
3178 .. testcode::
3179
3180 class Base:
3181 def log_status(self) -> None:
3182 ...
3183
3184 class Sub(Base):
3185 @override
3186 def log_status(self) -> None: # Okay: overrides Base.log_status
3187 ...
3188
3189 @override
3190 def done(self) -> None: # Error reported by type checker
3191 ...
3192
3193 There is no runtime checking of this property.
3194
3195 The decorator will attempt to set an ``__override__`` attribute to ``True`` on
3196 the decorated object. Thus, a check like
3197 ``if getattr(obj, "__override__", False)`` can be used at runtime to determine
3198 whether an object ``obj`` has been marked as an override. If the decorated object
3199 does not support setting attributes, the decorator returns the object unchanged
3200 without raising an exception.
3201
3202 See :pep:`698` for more details.
3203
3204 .. versionadded:: 3.12
3205
3206
3207 .. decorator:: type_check_only
3208
3209 Decorator to mark a class or function as unavailable at runtime.
3210
3211 This decorator is itself not available at runtime. It is mainly
3212 intended to mark classes that are defined in type stub files if
3213 an implementation returns an instance of a private class::
3214
3215 @type_check_only
3216 class Response: # private or not available at runtime
3217 code: int
3218 def get_header(self, name: str) -> str: ...
3219
3220 def fetch_response() -> Response: ...
3221
3222 Note that returning instances of private classes is not recommended.
3223 It is usually preferable to make such classes public.
3224
3225 Introspection helpers
3226 ---------------------
3227
3228 .. function:: get_type_hints(obj, globalns=None, localns=None, include_extras=False)
3229
3230 Return a dictionary containing type hints for a function, method, module
3231 or class object.
3232
3233 This is often the same as ``obj.__annotations__``, but this function makes
3234 the following changes to the annotations dictionary:
3235
3236 * Forward references encoded as string literals or :class:`ForwardRef`
3237 objects are handled by evaluating them in *globalns*, *localns*, and
3238 (where applicable) *obj*'s :ref:`type parameter <type-params>` namespace.
3239 If *globalns* or *localns* is not given, appropriate namespace
3240 dictionaries are inferred from *obj*.
3241 * ``None`` is replaced with :class:`types.NoneType`.
3242 * If :deco:`no_type_check` has been applied to *obj*, an
3243 empty dictionary is returned.
3244 * If *obj* is a class ``C``, the function returns a dictionary that merges
3245 annotations from ``C``'s base classes with those on ``C`` directly. This
3246 is done by traversing :attr:`C.__mro__ <type.__mro__>` and iteratively
3247 combining
3248 ``__annotations__`` dictionaries. Annotations on classes appearing
3249 earlier in the :term:`method resolution order` always take precedence over
3250 annotations on classes appearing later in the method resolution order.
3251 * The function recursively replaces all occurrences of
3252 ``Annotated[T, ...]``, ``Required[T]``, ``NotRequired[T]``, and ``ReadOnly[T]``
3253 with ``T``, unless *include_extras* is set to ``True`` (see
3254 :class:`Annotated` for more information).
3255
3256 See also :func:`inspect.get_annotations`, a lower-level function that
3257 returns annotations more directly.
3258
3259 .. note::
3260
3261 If any forward references in the annotations of *obj* are not resolvable
3262 or are not valid Python code, this function will raise an exception
3263 such as :exc:`NameError`. For example, this can happen with imported
3264 :ref:`type aliases <type-aliases>` that include forward references,
3265 or with names imported under :data:`if TYPE_CHECKING <TYPE_CHECKING>`.
3266
3267 .. versionchanged:: 3.9
3268 Added ``include_extras`` parameter as part of :pep:`593`.
3269 See the documentation on :data:`Annotated` for more information.
3270
3271 .. versionchanged:: 3.11
3272 Previously, ``Optional[t]`` was added for function and method annotations
3273 if a default value equal to ``None`` was set.
3274 Now the annotation is returned unchanged.
3275
3276 .. function:: get_origin(tp)
3277
3278 Get the unsubscripted version of a type: for a typing object of the form
3279 ``X[Y, Z, ...]`` return ``X``.
3280
3281 If ``X`` is a typing-module alias for a builtin or
3282 :mod:`collections` class, it will be normalized to the original class.
3283 If ``X`` is an instance of :class:`ParamSpecArgs` or :class:`ParamSpecKwargs`,
3284 return the underlying :class:`ParamSpec`.
3285 Return ``None`` for unsupported objects.
3286
3287 Examples:
3288
3289 .. testcode::
3290
3291 assert get_origin(str) is None
3292 assert get_origin(Dict[str, int]) is dict
3293 assert get_origin(Union[int, str]) is Union
3294 assert get_origin(Annotated[str, "metadata"]) is Annotated
3295 P = ParamSpec('P')
3296 assert get_origin(P.args) is P
3297 assert get_origin(P.kwargs) is P
3298
3299 .. versionadded:: 3.8
3300
3301 .. function:: get_args(tp)
3302
3303 Get type arguments with all substitutions performed: for a typing object
3304 of the form ``X[Y, Z, ...]`` return ``(Y, Z, ...)``.
3305
3306 If ``X`` is a union or :class:`Literal` contained in another
3307 generic type, the order of ``(Y, Z, ...)`` may be different from the order
3308 of the original arguments ``[Y, Z, ...]`` due to type caching.
3309 Return ``()`` for unsupported objects.
3310
3311 Examples:
3312
3313 .. testcode::
3314
3315 assert get_args(int) == ()
3316 assert get_args(Dict[int, str]) == (int, str)
3317 assert get_args(Union[int, str]) == (int, str)
3318
3319 .. versionadded:: 3.8
3320
3321 .. function:: get_protocol_members(tp)
3322
3323 Return the set of members defined in a :class:`Protocol`.
3324
3325 .. doctest::
3326
3327 >>> from typing import Protocol, get_protocol_members
3328 >>> class P(Protocol):
3329 ... def a(self) -> str: ...
3330 ... b: int
3331 >>> get_protocol_members(P) == frozenset({'a', 'b'})
3332 True
3333
3334 Raise :exc:`TypeError` for arguments that are not Protocols.
3335
3336 .. versionadded:: 3.13
3337
3338 .. function:: is_protocol(tp)
3339
3340 Determine if a type is a :class:`Protocol`.
3341
3342 For example::
3343
3344 class P(Protocol):
3345 def a(self) -> str: ...
3346 b: int
3347
3348 is_protocol(P) # => True
3349 is_protocol(int) # => False
3350
3351 .. versionadded:: 3.13
3352
3353 .. function:: is_typeddict(tp)
3354
3355 Check if a type is a :class:`TypedDict`.
3356
3357 For example:
3358
3359 .. testcode::
3360
3361 class Film(TypedDict):
3362 title: str
3363 year: int
3364
3365 assert is_typeddict(Film)
3366 assert not is_typeddict(list | str)
3367
3368 # TypedDict is a factory for creating typed dicts,
3369 # not a typed dict itself
3370 assert not is_typeddict(TypedDict)
3371
3372 .. versionadded:: 3.10
3373
3374 .. class:: ForwardRef
3375
3376 Class used for internal typing representation of string forward references.
3377
3378 For example, ``List["SomeClass"]`` is implicitly transformed into
3379 ``List[ForwardRef("SomeClass")]``. ``ForwardRef`` should not be instantiated by
3380 a user, but may be used by introspection tools.
3381
3382 .. note::
3383 :pep:`585` generic types such as ``list["SomeClass"]`` will not be
3384 implicitly transformed into ``list[ForwardRef("SomeClass")]`` and thus
3385 will not automatically resolve to ``list[SomeClass]``.
3386
3387 .. versionadded:: 3.7.4
3388
3389 .. data:: NoDefault
3390
3391 A sentinel object used to indicate that a type parameter has no default
3392 value. For example:
3393
3394 .. doctest::
3395
3396 >>> T = TypeVar("T")
3397 >>> T.__default__ is typing.NoDefault
3398 True
3399 >>> S = TypeVar("S", default=None)
3400 >>> S.__default__ is None
3401 True
3402
3403 .. versionadded:: 3.13
3404
3405 Constant
3406 --------
3407
3408 .. data:: TYPE_CHECKING
3409
3410 A special constant that is assumed to be ``True`` by 3rd party static
3411 type checkers. It is ``False`` at runtime.
3412
3413 Usage::
3414
3415 if TYPE_CHECKING:
3416 import expensive_mod
3417
3418 def fun(arg: 'expensive_mod.SomeType') -> None:
3419 local_var: expensive_mod.AnotherType = other_fun()
3420
3421 The first type annotation must be enclosed in quotes, making it a
3422 "forward reference", to hide the ``expensive_mod`` reference from the
3423 interpreter runtime. Type annotations for local variables are not
3424 evaluated, so the second annotation does not need to be enclosed in quotes.
3425
3426 .. note::
3427
3428 If ``from __future__ import annotations`` is used,
3429 annotations are not evaluated at function definition time.
3430 Instead, they are stored as strings in ``__annotations__``.
3431 This makes it unnecessary to use quotes around the annotation
3432 (see :pep:`563`).
3433
3434 .. versionadded:: 3.5.2
3435
3436 .. _generic-concrete-collections:
3437 .. _deprecated-aliases:
3438
3439 Deprecated aliases
3440 ------------------
3441
3442 This module defines several deprecated aliases to pre-existing
3443 standard library classes. These were originally included in the :mod:`!typing`
3444 module in order to support parameterizing these generic classes using ``[]``.
3445 However, the aliases became redundant in Python 3.9 when the
3446 corresponding pre-existing classes were enhanced to support ``[]`` (see
3447 :pep:`585`).
3448
3449 The redundant types are deprecated as of Python 3.9. However, while the aliases
3450 may be removed at some point, removal of these aliases is not currently
3451 planned. As such, no deprecation warnings are currently issued by the
3452 interpreter for these aliases.
3453
3454 If at some point it is decided to remove these deprecated aliases, a
3455 deprecation warning will be issued by the interpreter for at least two releases
3456 prior to removal. The aliases are guaranteed to remain in the :mod:`!typing` module
3457 without deprecation warnings until at least Python 3.14.
3458
3459 Type checkers are encouraged to flag uses of the deprecated types if the
3460 program they are checking targets a minimum Python version of 3.9 or newer.
3461
3462 .. _corresponding-to-built-in-types:
3463
3464 Aliases to built-in types
3465 """""""""""""""""""""""""
3466
3467 .. class:: Dict(dict, MutableMapping[KT, VT])
3468
3469 Deprecated alias to :class:`dict`.
3470
3471 Note that to annotate arguments, it is preferred
3472 to use an abstract collection type such as :class:`~collections.abc.Mapping`
3473 rather than to use :class:`dict` or :class:`!typing.Dict`.
3474
3475 .. deprecated:: 3.9
3476 :class:`builtins.dict <dict>` now supports subscripting (``[]``).
3477 See :pep:`585` and :ref:`types-genericalias`.
3478
3479 .. class:: List(list, MutableSequence[T])
3480
3481 Deprecated alias to :class:`list`.
3482
3483 Note that to annotate arguments, it is preferred
3484 to use an abstract collection type such as
3485 :class:`~collections.abc.Sequence` or :class:`~collections.abc.Iterable`
3486 rather than to use :class:`list` or :class:`!typing.List`.
3487
3488 .. deprecated:: 3.9
3489 :class:`builtins.list <list>` now supports subscripting (``[]``).
3490 See :pep:`585` and :ref:`types-genericalias`.
3491
3492 .. class:: Set(set, MutableSet[T])
3493
3494 Deprecated alias to :class:`builtins.set <set>`.
3495
3496 Note that to annotate arguments, it is preferred
3497 to use an abstract collection type such as :class:`collections.abc.Set`
3498 rather than to use :class:`set` or :class:`typing.Set`.
3499
3500 .. deprecated:: 3.9
3501 :class:`builtins.set <set>` now supports subscripting (``[]``).
3502 See :pep:`585` and :ref:`types-genericalias`.
3503
3504 .. class:: FrozenSet(frozenset, AbstractSet[T_co])
3505
3506 Deprecated alias to :class:`builtins.frozenset <frozenset>`.
3507
3508 .. deprecated:: 3.9
3509 :class:`builtins.frozenset <frozenset>`
3510 now supports subscripting (``[]``).
3511 See :pep:`585` and :ref:`types-genericalias`.
3512
3513 .. data:: Tuple
3514
3515 Deprecated alias for :class:`tuple`.
3516
3517 :class:`tuple` and ``Tuple`` are special-cased in the type system; see
3518 :ref:`annotating-tuples` for more details.
3519
3520 .. deprecated:: 3.9
3521 :class:`builtins.tuple <tuple>` now supports subscripting (``[]``).
3522 See :pep:`585` and :ref:`types-genericalias`.
3523
3524 .. class:: Type(Generic[CT_co])
3525
3526 Deprecated alias to :class:`type`.
3527
3528 See :ref:`type-of-class-objects` for details on using :class:`type` or
3529 ``typing.Type`` in type annotations.
3530
3531 .. versionadded:: 3.5.2
3532
3533 .. deprecated:: 3.9
3534 :class:`builtins.type <type>` now supports subscripting (``[]``).
3535 See :pep:`585` and :ref:`types-genericalias`.
3536
3537 .. _corresponding-to-types-in-collections:
3538
3539 Aliases to types in :mod:`collections`
3540 """"""""""""""""""""""""""""""""""""""
3541
3542 .. class:: DefaultDict(collections.defaultdict, MutableMapping[KT, VT])
3543
3544 Deprecated alias to :class:`collections.defaultdict`.
3545
3546 .. versionadded:: 3.5.2
3547
3548 .. deprecated:: 3.9
3549 :class:`collections.defaultdict` now supports subscripting (``[]``).
3550 See :pep:`585` and :ref:`types-genericalias`.
3551
3552 .. class:: OrderedDict(collections.OrderedDict, MutableMapping[KT, VT])
3553
3554 Deprecated alias to :class:`collections.OrderedDict`.
3555
3556 .. versionadded:: 3.7.2
3557
3558 .. deprecated:: 3.9
3559 :class:`collections.OrderedDict` now supports subscripting (``[]``).
3560 See :pep:`585` and :ref:`types-genericalias`.
3561
3562 .. class:: ChainMap(collections.ChainMap, MutableMapping[KT, VT])
3563
3564 Deprecated alias to :class:`collections.ChainMap`.
3565
3566 .. versionadded:: 3.6.1
3567
3568 .. deprecated:: 3.9
3569 :class:`collections.ChainMap` now supports subscripting (``[]``).
3570 See :pep:`585` and :ref:`types-genericalias`.
3571
3572 .. class:: Counter(collections.Counter, Dict[T, int])
3573
3574 Deprecated alias to :class:`collections.Counter`.
3575
3576 .. versionadded:: 3.6.1
3577
3578 .. deprecated:: 3.9
3579 :class:`collections.Counter` now supports subscripting (``[]``).
3580 See :pep:`585` and :ref:`types-genericalias`.
3581
3582 .. class:: Deque(deque, MutableSequence[T])
3583
3584 Deprecated alias to :class:`collections.deque`.
3585
3586 .. versionadded:: 3.6.1
3587
3588 .. deprecated:: 3.9
3589 :class:`collections.deque` now supports subscripting (``[]``).
3590 See :pep:`585` and :ref:`types-genericalias`.
3591
3592 .. _other-concrete-types:
3593
3594 Aliases to other concrete types
3595 """""""""""""""""""""""""""""""
3596
3597 .. class:: Pattern
3598 Match
3599
3600 Deprecated aliases corresponding to the return types from
3601 :func:`re.compile` and :func:`re.match`.
3602
3603 These types (and the corresponding functions) are generic over
3604 :data:`AnyStr`. ``Pattern`` can be specialised as ``Pattern[str]`` or
3605 ``Pattern[bytes]``; ``Match`` can be specialised as ``Match[str]`` or
3606 ``Match[bytes]``.
3607
3608 .. deprecated:: 3.9
3609 Classes ``Pattern`` and ``Match`` from :mod:`re` now support ``[]``.
3610 See :pep:`585` and :ref:`types-genericalias`.
3611
3612 .. class:: Text
3613
3614 Deprecated alias for :class:`str`.
3615
3616 ``Text`` is provided to supply a forward
3617 compatible path for Python 2 code: in Python 2, ``Text`` is an alias for
3618 ``unicode``.
3619
3620 Use ``Text`` to indicate that a value must contain a unicode string in
3621 a manner that is compatible with both Python 2 and Python 3::
3622
3623 def add_unicode_checkmark(text: Text) -> Text:
3624 return text + u' \u2713'
3625
3626 .. versionadded:: 3.5.2
3627
3628 .. deprecated:: 3.11
3629 Python 2 is no longer supported, and most type checkers also no longer
3630 support type checking Python 2 code. Removal of the alias is not
3631 currently planned, but users are encouraged to use
3632 :class:`str` instead of ``Text``.
3633
3634 .. _abstract-base-classes:
3635 .. _corresponding-to-collections-in-collections-abc:
3636
3637 Aliases to container ABCs in :mod:`collections.abc`
3638 """""""""""""""""""""""""""""""""""""""""""""""""""
3639
3640 .. class:: AbstractSet(Collection[T_co])
3641
3642 Deprecated alias to :class:`collections.abc.Set`.
3643
3644 .. deprecated:: 3.9
3645 :class:`collections.abc.Set` now supports subscripting (``[]``).
3646 See :pep:`585` and :ref:`types-genericalias`.
3647
3648 .. class:: ByteString(Sequence[int])
3649
3650 Deprecated alias to :class:`collections.abc.ByteString`.
3651
3652 Use ``isinstance(obj, collections.abc.Buffer)`` to test if ``obj``
3653 implements the :ref:`buffer protocol <bufferobjects>` at runtime. For use in
3654 type annotations, either use :class:`~collections.abc.Buffer` or a union
3655 that explicitly specifies the types your code supports (e.g.,
3656 ``bytes | bytearray | memoryview``).
3657
3658 :class:`!ByteString` was originally intended to be an abstract class that
3659 would serve as a supertype of both :class:`bytes` and :class:`bytearray`.
3660 However, since the ABC never had any methods, knowing that an object was an
3661 instance of :class:`!ByteString` never actually told you anything useful
3662 about the object. Other common buffer types such as :class:`memoryview` were
3663 also never understood as subtypes of :class:`!ByteString` (either at runtime
3664 or by static type checkers).
3665
3666 See :pep:`PEP 688 <688#current-options>` for more details.
3667
3668 .. deprecated-removed:: 3.9 3.17
3669
3670 .. class:: Collection(Sized, Iterable[T_co], Container[T_co])
3671
3672 Deprecated alias to :class:`collections.abc.Collection`.
3673
3674 .. versionadded:: 3.6
3675
3676 .. deprecated:: 3.9
3677 :class:`collections.abc.Collection` now supports subscripting (``[]``).
3678 See :pep:`585` and :ref:`types-genericalias`.
3679
3680 .. class:: Container(Generic[T_co])
3681
3682 Deprecated alias to :class:`collections.abc.Container`.
3683
3684 .. deprecated:: 3.9
3685 :class:`collections.abc.Container` now supports subscripting (``[]``).
3686 See :pep:`585` and :ref:`types-genericalias`.
3687
3688 .. class:: ItemsView(MappingView, AbstractSet[tuple[KT_co, VT_co]])
3689
3690 Deprecated alias to :class:`collections.abc.ItemsView`.
3691
3692 .. deprecated:: 3.9
3693 :class:`collections.abc.ItemsView` now supports subscripting (``[]``).
3694 See :pep:`585` and :ref:`types-genericalias`.
3695
3696 .. class:: KeysView(MappingView, AbstractSet[KT_co])
3697
3698 Deprecated alias to :class:`collections.abc.KeysView`.
3699
3700 .. deprecated:: 3.9
3701 :class:`collections.abc.KeysView` now supports subscripting (``[]``).
3702 See :pep:`585` and :ref:`types-genericalias`.
3703
3704 .. class:: Mapping(Collection[KT], Generic[KT, VT_co])
3705
3706 Deprecated alias to :class:`collections.abc.Mapping`.
3707
3708 .. deprecated:: 3.9
3709 :class:`collections.abc.Mapping` now supports subscripting (``[]``).
3710 See :pep:`585` and :ref:`types-genericalias`.
3711
3712 .. class:: MappingView(Sized)
3713
3714 Deprecated alias to :class:`collections.abc.MappingView`.
3715
3716 .. deprecated:: 3.9
3717 :class:`collections.abc.MappingView` now supports subscripting (``[]``).
3718 See :pep:`585` and :ref:`types-genericalias`.
3719
3720 .. class:: MutableMapping(Mapping[KT, VT])
3721
3722 Deprecated alias to :class:`collections.abc.MutableMapping`.
3723
3724 .. deprecated:: 3.9
3725 :class:`collections.abc.MutableMapping`
3726 now supports subscripting (``[]``).
3727 See :pep:`585` and :ref:`types-genericalias`.
3728
3729 .. class:: MutableSequence(Sequence[T])
3730
3731 Deprecated alias to :class:`collections.abc.MutableSequence`.
3732
3733 .. deprecated:: 3.9
3734 :class:`collections.abc.MutableSequence`
3735 now supports subscripting (``[]``).
3736 See :pep:`585` and :ref:`types-genericalias`.
3737
3738 .. class:: MutableSet(AbstractSet[T])
3739
3740 Deprecated alias to :class:`collections.abc.MutableSet`.
3741
3742 .. deprecated:: 3.9
3743 :class:`collections.abc.MutableSet` now supports subscripting (``[]``).
3744 See :pep:`585` and :ref:`types-genericalias`.
3745
3746 .. class:: Sequence(Reversible[T_co], Collection[T_co])
3747
3748 Deprecated alias to :class:`collections.abc.Sequence`.
3749
3750 .. deprecated:: 3.9
3751 :class:`collections.abc.Sequence` now supports subscripting (``[]``).
3752 See :pep:`585` and :ref:`types-genericalias`.
3753
3754 .. class:: ValuesView(MappingView, Collection[_VT_co])
3755
3756 Deprecated alias to :class:`collections.abc.ValuesView`.
3757
3758 .. deprecated:: 3.9
3759 :class:`collections.abc.ValuesView` now supports subscripting (``[]``).
3760 See :pep:`585` and :ref:`types-genericalias`.
3761
3762 .. _asynchronous-programming:
3763
3764 Aliases to asynchronous ABCs in :mod:`collections.abc`
3765 """"""""""""""""""""""""""""""""""""""""""""""""""""""
3766
3767 .. class:: Coroutine(Awaitable[ReturnType], Generic[YieldType, SendType, ReturnType])
3768
3769 Deprecated alias to :class:`collections.abc.Coroutine`.
3770
3771 See :ref:`annotating-generators-and-coroutines`
3772 for details on using :class:`collections.abc.Coroutine`
3773 and ``typing.Coroutine`` in type annotations.
3774
3775 .. versionadded:: 3.5.3
3776
3777 .. deprecated:: 3.9
3778 :class:`collections.abc.Coroutine` now supports subscripting (``[]``).
3779 See :pep:`585` and :ref:`types-genericalias`.
3780
3781 .. class:: AsyncGenerator(AsyncIterator[YieldType], Generic[YieldType, SendType])
3782
3783 Deprecated alias to :class:`collections.abc.AsyncGenerator`.
3784
3785 See :ref:`annotating-generators-and-coroutines`
3786 for details on using :class:`collections.abc.AsyncGenerator`
3787 and ``typing.AsyncGenerator`` in type annotations.
3788
3789 .. versionadded:: 3.6.1
3790
3791 .. deprecated:: 3.9
3792 :class:`collections.abc.AsyncGenerator`
3793 now supports subscripting (``[]``).
3794 See :pep:`585` and :ref:`types-genericalias`.
3795
3796 .. versionchanged:: 3.13
3797 The ``SendType`` parameter now has a default.
3798
3799 .. class:: AsyncIterable(Generic[T_co])
3800
3801 Deprecated alias to :class:`collections.abc.AsyncIterable`.
3802
3803 .. versionadded:: 3.5.2
3804
3805 .. deprecated:: 3.9
3806 :class:`collections.abc.AsyncIterable` now supports subscripting (``[]``).
3807 See :pep:`585` and :ref:`types-genericalias`.
3808
3809 .. class:: AsyncIterator(AsyncIterable[T_co])
3810
3811 Deprecated alias to :class:`collections.abc.AsyncIterator`.
3812
3813 .. versionadded:: 3.5.2
3814
3815 .. deprecated:: 3.9
3816 :class:`collections.abc.AsyncIterator` now supports subscripting (``[]``).
3817 See :pep:`585` and :ref:`types-genericalias`.
3818
3819 .. class:: Awaitable(Generic[T_co])
3820
3821 Deprecated alias to :class:`collections.abc.Awaitable`.
3822
3823 .. versionadded:: 3.5.2
3824
3825 .. deprecated:: 3.9
3826 :class:`collections.abc.Awaitable` now supports subscripting (``[]``).
3827 See :pep:`585` and :ref:`types-genericalias`.
3828
3829 .. _corresponding-to-other-types-in-collections-abc:
3830
3831 Aliases to other ABCs in :mod:`collections.abc`
3832 """""""""""""""""""""""""""""""""""""""""""""""
3833
3834 .. class:: Iterable(Generic[T_co])
3835
3836 Deprecated alias to :class:`collections.abc.Iterable`.
3837
3838 .. deprecated:: 3.9
3839 :class:`collections.abc.Iterable` now supports subscripting (``[]``).
3840 See :pep:`585` and :ref:`types-genericalias`.
3841
3842 .. class:: Iterator(Iterable[T_co])
3843
3844 Deprecated alias to :class:`collections.abc.Iterator`.
3845
3846 .. deprecated:: 3.9
3847 :class:`collections.abc.Iterator` now supports subscripting (``[]``).
3848 See :pep:`585` and :ref:`types-genericalias`.
3849
3850 .. data:: Callable
3851
3852 Deprecated alias to :class:`collections.abc.Callable`.
3853
3854 See :ref:`annotating-callables` for details on how to use
3855 :class:`collections.abc.Callable` and ``typing.Callable`` in type annotations.
3856
3857 .. deprecated:: 3.9
3858 :class:`collections.abc.Callable` now supports subscripting (``[]``).
3859 See :pep:`585` and :ref:`types-genericalias`.
3860
3861 .. versionchanged:: 3.10
3862 ``Callable`` now supports :class:`ParamSpec` and :data:`Concatenate`.
3863 See :pep:`612` for more details.
3864
3865 .. class:: Generator(Iterator[YieldType], Generic[YieldType, SendType, ReturnType])
3866
3867 Deprecated alias to :class:`collections.abc.Generator`.
3868
3869 See :ref:`annotating-generators-and-coroutines`
3870 for details on using :class:`collections.abc.Generator`
3871 and ``typing.Generator`` in type annotations.
3872
3873 .. deprecated:: 3.9
3874 :class:`collections.abc.Generator` now supports subscripting (``[]``).
3875 See :pep:`585` and :ref:`types-genericalias`.
3876
3877 .. versionchanged:: 3.13
3878 Default values for the send and return types were added.
3879
3880 .. class:: Hashable
3881
3882 Deprecated alias to :class:`collections.abc.Hashable`.
3883
3884 .. deprecated:: 3.12
3885 Use :class:`collections.abc.Hashable` directly instead.
3886
3887 .. class:: Reversible(Iterable[T_co])
3888
3889 Deprecated alias to :class:`collections.abc.Reversible`.
3890
3891 .. deprecated:: 3.9
3892 :class:`collections.abc.Reversible` now supports subscripting (``[]``).
3893 See :pep:`585` and :ref:`types-genericalias`.
3894
3895 .. class:: Sized
3896
3897 Deprecated alias to :class:`collections.abc.Sized`.
3898
3899 .. deprecated:: 3.12
3900 Use :class:`collections.abc.Sized` directly instead.
3901
3902 .. _context-manager-types:
3903
3904 Aliases to :mod:`contextlib` ABCs
3905 """""""""""""""""""""""""""""""""
3906
3907 .. class:: ContextManager(Generic[T_co, ExitT_co])
3908
3909 Deprecated alias to :class:`contextlib.AbstractContextManager`.
3910
3911 The first type parameter, ``T_co``, represents the type returned by
3912 the :meth:`~object.__enter__` method. The optional second type parameter, ``ExitT_co``,
3913 which defaults to ``bool | None``, represents the type returned by the
3914 :meth:`~object.__exit__` method.
3915
3916 .. versionadded:: 3.5.4
3917
3918 .. deprecated:: 3.9
3919 :class:`contextlib.AbstractContextManager`
3920 now supports subscripting (``[]``).
3921 See :pep:`585` and :ref:`types-genericalias`.
3922
3923 .. versionchanged:: 3.13
3924 Added the optional second type parameter, ``ExitT_co``.
3925
3926 .. class:: AsyncContextManager(Generic[T_co, AExitT_co])
3927
3928 Deprecated alias to :class:`contextlib.AbstractAsyncContextManager`.
3929
3930 The first type parameter, ``T_co``, represents the type returned by
3931 the :meth:`~object.__aenter__` method. The optional second type parameter, ``AExitT_co``,
3932 which defaults to ``bool | None``, represents the type returned by the
3933 :meth:`~object.__aexit__` method.
3934
3935 .. versionadded:: 3.6.2
3936
3937 .. deprecated:: 3.9
3938 :class:`contextlib.AbstractAsyncContextManager`
3939 now supports subscripting (``[]``).
3940 See :pep:`585` and :ref:`types-genericalias`.
3941
3942 .. versionchanged:: 3.13
3943 Added the optional second type parameter, ``AExitT_co``.
3944
3945 Deprecation Timeline of Major Features
3946 ======================================
3947
3948 Certain features in ``typing`` are deprecated and may be removed in a future
3949 version of Python. The following table summarizes major deprecations for your
3950 convenience. This is subject to change, and not all deprecations are listed.
3951
3952 .. list-table::
3953 :header-rows: 1
3954
3955 * - Feature
3956 - Deprecated in
3957 - Projected removal
3958 - PEP/issue
3959 * - ``typing`` versions of standard collections
3960 - 3.9
3961 - Undecided (see :ref:`deprecated-aliases` for more information)
3962 - :pep:`585`
3963 * - :class:`typing.ByteString`
3964 - 3.9
3965 - 3.17
3966 - :gh:`91896`
3967 * - :data:`typing.Text`
3968 - 3.11
3969 - Undecided
3970 - :gh:`92332`
3971 * - :class:`typing.Hashable` and :class:`typing.Sized`
3972 - 3.12
3973 - Undecided
3974 - :gh:`94309`
3975 * - :data:`typing.TypeAlias`
3976 - 3.12
3977 - Undecided
3978 - :pep:`695`
3979 * - :func:`@typing.no_type_check_decorator <no_type_check_decorator>`
3980 - 3.13
3981 - 3.15
3982 - :gh:`106309`
3983 * - :data:`typing.AnyStr`
3984 - 3.13
3985 - 3.18
3986 - :gh:`105578`