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