1:mod:`typing` --- Support for type hints
2========================================
3
4.. module:: typing
5   :synopsis: Support for type hints (see :pep:`484`).
6
7.. versionadded:: 3.5
8
9**Source code:** :source:`Lib/typing.py`
10
11.. note::
12
13   The Python runtime does not enforce function and variable type annotations.
14   They can be used by third party tools such as type checkers, IDEs, linters,
15   etc.
16
17--------------
18
19This module provides runtime support for type hints as specified by
20:pep:`484`, :pep:`526`, :pep:`544`, :pep:`586`, :pep:`589`, and :pep:`591`.
21The most fundamental support consists of the types :data:`Any`, :data:`Union`,
22:data:`Tuple`, :data:`Callable`, :class:`TypeVar`, and
23:class:`Generic`.  For full specification please see :pep:`484`.  For
24a simplified introduction to type hints see :pep:`483`.
25
26
27The function below takes and returns a string and is annotated as follows::
28
29   def greeting(name: str) -> str:
30       return 'Hello ' + name
31
32In the function ``greeting``, the argument ``name`` is expected to be of type
33:class:`str` and the return type :class:`str`. Subtypes are accepted as
34arguments.
35
36Type aliases
37------------
38
39A type alias is defined by assigning the type to the alias. In this example,
40``Vector`` and ``List[float]`` will be treated as interchangeable synonyms::
41
42   from typing import List
43   Vector = List[float]
44
45   def scale(scalar: float, vector: Vector) -> Vector:
46       return [scalar * num for num in vector]
47
48   # typechecks; a list of floats qualifies as a Vector.
49   new_vector = scale(2.0, [1.0, -4.2, 5.4])
50
51Type aliases are useful for simplifying complex type signatures. For example::
52
53   from typing import Dict, Tuple, Sequence
54
55   ConnectionOptions = Dict[str, str]
56   Address = Tuple[str, int]
57   Server = Tuple[Address, ConnectionOptions]
58
59   def broadcast_message(message: str, servers: Sequence[Server]) -> None:
60       ...
61
62   # The static type checker will treat the previous type signature as
63   # being exactly equivalent to this one.
64   def broadcast_message(
65           message: str,
66           servers: Sequence[Tuple[Tuple[str, int], Dict[str, str]]]) -> None:
67       ...
68
69Note that ``None`` as a type hint is a special case and is replaced by
70``type(None)``.
71
72.. _distinct:
73
74NewType
75-------
76
77Use the :func:`NewType` helper function to create distinct types::
78
79   from typing import NewType
80
81   UserId = NewType('UserId', int)
82   some_id = UserId(524313)
83
84The static type checker will treat the new type as if it were a subclass
85of the original type. This is useful in helping catch logical errors::
86
87   def get_user_name(user_id: UserId) -> str:
88       ...
89
90   # typechecks
91   user_a = get_user_name(UserId(42351))
92
93   # does not typecheck; an int is not a UserId
94   user_b = get_user_name(-1)
95
96You may still perform all ``int`` operations on a variable of type ``UserId``,
97but the result will always be of type ``int``. This lets you pass in a
98``UserId`` wherever an ``int`` might be expected, but will prevent you from
99accidentally creating a ``UserId`` in an invalid way::
100
101   # 'output' is of type 'int', not 'UserId'
102   output = UserId(23413) + UserId(54341)
103
104Note that these checks are enforced only by the static type checker. At runtime,
105the statement ``Derived = NewType('Derived', Base)`` will make ``Derived`` a
106function that immediately returns whatever parameter you pass it. That means
107the expression ``Derived(some_value)`` does not create a new class or introduce
108any overhead beyond that of a regular function call.
109
110More precisely, the expression ``some_value is Derived(some_value)`` is always
111true at runtime.
112
113This also means that it is not possible to create a subtype of ``Derived``
114since it is an identity function at runtime, not an actual type::
115
116   from typing import NewType
117
118   UserId = NewType('UserId', int)
119
120   # Fails at runtime and does not typecheck
121   class AdminUserId(UserId): pass
122
123However, it is possible to create a :func:`NewType` based on a 'derived' ``NewType``::
124
125   from typing import NewType
126
127   UserId = NewType('UserId', int)
128
129   ProUserId = NewType('ProUserId', UserId)
130
131and typechecking for ``ProUserId`` will work as expected.
132
133See :pep:`484` for more details.
134
135.. note::
136
137   Recall that the use of a type alias declares two types to be *equivalent* to
138   one another. Doing ``Alias = Original`` will make the static type checker
139   treat ``Alias`` as being *exactly equivalent* to ``Original`` in all cases.
140   This is useful when you want to simplify complex type signatures.
141
142   In contrast, ``NewType`` declares one type to be a *subtype* of another.
143   Doing ``Derived = NewType('Derived', Original)`` will make the static type
144   checker treat ``Derived`` as a *subclass* of ``Original``, which means a
145   value of type ``Original`` cannot be used in places where a value of type
146   ``Derived`` is expected. This is useful when you want to prevent logic
147   errors with minimal runtime cost.
148
149.. versionadded:: 3.5.2
150
151Callable
152--------
153
154Frameworks expecting callback functions of specific signatures might be
155type hinted using ``Callable[[Arg1Type, Arg2Type], ReturnType]``.
156
157For example::
158
159   from typing import Callable
160
161   def feeder(get_next_item: Callable[[], str]) -> None:
162       # Body
163
164   def async_query(on_success: Callable[[int], None],
165                   on_error: Callable[[int, Exception], None]) -> None:
166       # Body
167
168It is possible to declare the return type of a callable without specifying
169the call signature by substituting a literal ellipsis
170for the list of arguments in the type hint: ``Callable[..., ReturnType]``.
171
172.. _generics:
173
174Generics
175--------
176
177Since type information about objects kept in containers cannot be statically
178inferred in a generic way, abstract base classes have been extended to support
179subscription to denote expected types for container elements.
180
181::
182
183   from typing import Mapping, Sequence
184
185   def notify_by_email(employees: Sequence[Employee],
186                       overrides: Mapping[str, str]) -> None: ...
187
188Generics can be parameterized by using a new factory available in typing
189called :class:`TypeVar`.
190
191::
192
193   from typing import Sequence, TypeVar
194
195   T = TypeVar('T')      # Declare type variable
196
197   def first(l: Sequence[T]) -> T:   # Generic function
198       return l[0]
199
200
201User-defined generic types
202--------------------------
203
204A user-defined class can be defined as a generic class.
205
206::
207
208   from typing import TypeVar, Generic
209   from logging import Logger
210
211   T = TypeVar('T')
212
213   class LoggedVar(Generic[T]):
214       def __init__(self, value: T, name: str, logger: Logger) -> None:
215           self.name = name
216           self.logger = logger
217           self.value = value
218
219       def set(self, new: T) -> None:
220           self.log('Set ' + repr(self.value))
221           self.value = new
222
223       def get(self) -> T:
224           self.log('Get ' + repr(self.value))
225           return self.value
226
227       def log(self, message: str) -> None:
228           self.logger.info('%s: %s', self.name, message)
229
230``Generic[T]`` as a base class defines that the class ``LoggedVar`` takes a
231single type parameter ``T`` . This also makes ``T`` valid as a type within the
232class body.
233
234The :class:`Generic` base class defines :meth:`__class_getitem__` so that
235``LoggedVar[t]`` is valid as a type::
236
237   from typing import Iterable
238
239   def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:
240       for var in vars:
241           var.set(0)
242
243A generic type can have any number of type variables, and type variables may
244be constrained::
245
246   from typing import TypeVar, Generic
247   ...
248
249   T = TypeVar('T')
250   S = TypeVar('S', int, str)
251
252   class StrangePair(Generic[T, S]):
253       ...
254
255Each type variable argument to :class:`Generic` must be distinct.
256This is thus invalid::
257
258   from typing import TypeVar, Generic
259   ...
260
261   T = TypeVar('T')
262
263   class Pair(Generic[T, T]):   # INVALID
264       ...
265
266You can use multiple inheritance with :class:`Generic`::
267
268   from typing import TypeVar, Generic, Sized
269
270   T = TypeVar('T')
271
272   class LinkedList(Sized, Generic[T]):
273       ...
274
275When inheriting from generic classes, some type variables could be fixed::
276
277    from typing import TypeVar, Mapping
278
279    T = TypeVar('T')
280
281    class MyDict(Mapping[str, T]):
282        ...
283
284In this case ``MyDict`` has a single parameter, ``T``.
285
286Using a generic class without specifying type parameters assumes
287:data:`Any` for each position. In the following example, ``MyIterable`` is
288not generic but implicitly inherits from ``Iterable[Any]``::
289
290   from typing import Iterable
291
292   class MyIterable(Iterable): # Same as Iterable[Any]
293
294User defined generic type aliases are also supported. Examples::
295
296   from typing import TypeVar, Iterable, Tuple, Union
297   S = TypeVar('S')
298   Response = Union[Iterable[S], int]
299
300   # Return type here is same as Union[Iterable[str], int]
301   def response(query: str) -> Response[str]:
302       ...
303
304   T = TypeVar('T', int, float, complex)
305   Vec = Iterable[Tuple[T, T]]
306
307   def inproduct(v: Vec[T]) -> T: # Same as Iterable[Tuple[T, T]]
308       return sum(x*y for x, y in v)
309
310.. versionchanged:: 3.7
311    :class:`Generic` no longer has a custom metaclass.
312
313A user-defined generic class can have ABCs as base classes without a metaclass
314conflict. Generic metaclasses are not supported. The outcome of parameterizing
315generics is cached, and most types in the typing module are hashable and
316comparable for equality.
317
318
319The :data:`Any` type
320--------------------
321
322A special kind of type is :data:`Any`. A static type checker will treat
323every type as being compatible with :data:`Any` and :data:`Any` as being
324compatible with every type.
325
326This means that it is possible to perform any operation or method call on a
327value of type :data:`Any` and assign it to any variable::
328
329   from typing import Any
330
331   a = None    # type: Any
332   a = []      # OK
333   a = 2       # OK
334
335   s = ''      # type: str
336   s = a       # OK
337
338   def foo(item: Any) -> int:
339       # Typechecks; 'item' could be any type,
340       # and that type might have a 'bar' method
341       item.bar()
342       ...
343
344Notice that no typechecking is performed when assigning a value of type
345:data:`Any` to a more precise type. For example, the static type checker did
346not report an error when assigning ``a`` to ``s`` even though ``s`` was
347declared to be of type :class:`str` and receives an :class:`int` value at
348runtime!
349
350Furthermore, all functions without a return type or parameter types will
351implicitly default to using :data:`Any`::
352
353   def legacy_parser(text):
354       ...
355       return data
356
357   # A static type checker will treat the above
358   # as having the same signature as:
359   def legacy_parser(text: Any) -> Any:
360       ...
361       return data
362
363This behavior allows :data:`Any` to be used as an *escape hatch* when you
364need to mix dynamically and statically typed code.
365
366Contrast the behavior of :data:`Any` with the behavior of :class:`object`.
367Similar to :data:`Any`, every type is a subtype of :class:`object`. However,
368unlike :data:`Any`, the reverse is not true: :class:`object` is *not* a
369subtype of every other type.
370
371That means when the type of a value is :class:`object`, a type checker will
372reject almost all operations on it, and assigning it to a variable (or using
373it as a return value) of a more specialized type is a type error. For example::
374
375   def hash_a(item: object) -> int:
376       # Fails; an object does not have a 'magic' method.
377       item.magic()
378       ...
379
380   def hash_b(item: Any) -> int:
381       # Typechecks
382       item.magic()
383       ...
384
385   # Typechecks, since ints and strs are subclasses of object
386   hash_a(42)
387   hash_a("foo")
388
389   # Typechecks, since Any is compatible with all types
390   hash_b(42)
391   hash_b("foo")
392
393Use :class:`object` to indicate that a value could be any type in a typesafe
394manner. Use :data:`Any` to indicate that a value is dynamically typed.
395
396
397Nominal vs structural subtyping
398-------------------------------
399
400Initially :pep:`484` defined Python static type system as using
401*nominal subtyping*. This means that a class ``A`` is allowed where
402a class ``B`` is expected if and only if ``A`` is a subclass of ``B``.
403
404This requirement previously also applied to abstract base classes, such as
405:class:`~collections.abc.Iterable`. The problem with this approach is that a class had
406to be explicitly marked to support them, which is unpythonic and unlike
407what one would normally do in idiomatic dynamically typed Python code.
408For example, this conforms to :pep:`484`::
409
410   from typing import Sized, Iterable, Iterator
411
412   class Bucket(Sized, Iterable[int]):
413       ...
414       def __len__(self) -> int: ...
415       def __iter__(self) -> Iterator[int]: ...
416
417:pep:`544` allows to solve this problem by allowing users to write
418the above code without explicit base classes in the class definition,
419allowing ``Bucket`` to be implicitly considered a subtype of both ``Sized``
420and ``Iterable[int]`` by static type checkers. This is known as
421*structural subtyping* (or static duck-typing)::
422
423   from typing import Iterator, Iterable
424
425   class Bucket:  # Note: no base classes
426       ...
427       def __len__(self) -> int: ...
428       def __iter__(self) -> Iterator[int]: ...
429
430   def collect(items: Iterable[int]) -> int: ...
431   result = collect(Bucket())  # Passes type check
432
433Moreover, by subclassing a special class :class:`Protocol`, a user
434can define new custom protocols to fully enjoy structural subtyping
435(see examples below).
436
437
438Classes, functions, and decorators
439----------------------------------
440
441The module defines the following classes, functions and decorators:
442
443.. class:: TypeVar
444
445    Type variable.
446
447    Usage::
448
449      T = TypeVar('T')  # Can be anything
450      A = TypeVar('A', str, bytes)  # Must be str or bytes
451
452    Type variables exist primarily for the benefit of static type
453    checkers.  They serve as the parameters for generic types as well
454    as for generic function definitions.  See class Generic for more
455    information on generic types.  Generic functions work as follows::
456
457       def repeat(x: T, n: int) -> Sequence[T]:
458           """Return a list containing n references to x."""
459           return [x]*n
460
461       def longest(x: A, y: A) -> A:
462           """Return the longest of two strings."""
463           return x if len(x) >= len(y) else y
464
465    The latter example's signature is essentially the overloading
466    of ``(str, str) -> str`` and ``(bytes, bytes) -> bytes``.  Also note
467    that if the arguments are instances of some subclass of :class:`str`,
468    the return type is still plain :class:`str`.
469
470    At runtime, ``isinstance(x, T)`` will raise :exc:`TypeError`.  In general,
471    :func:`isinstance` and :func:`issubclass` should not be used with types.
472
473    Type variables may be marked covariant or contravariant by passing
474    ``covariant=True`` or ``contravariant=True``.  See :pep:`484` for more
475    details.  By default type variables are invariant.  Alternatively,
476    a type variable may specify an upper bound using ``bound=<type>``.
477    This means that an actual type substituted (explicitly or implicitly)
478    for the type variable must be a subclass of the boundary type,
479    see :pep:`484`.
480
481.. class:: Generic
482
483   Abstract base class for generic types.
484
485   A generic type is typically declared by inheriting from an
486   instantiation of this class with one or more type variables.
487   For example, a generic mapping type might be defined as::
488
489      class Mapping(Generic[KT, VT]):
490          def __getitem__(self, key: KT) -> VT:
491              ...
492              # Etc.
493
494   This class can then be used as follows::
495
496      X = TypeVar('X')
497      Y = TypeVar('Y')
498
499      def lookup_name(mapping: Mapping[X, Y], key: X, default: Y) -> Y:
500          try:
501              return mapping[key]
502          except KeyError:
503              return default
504
505.. class:: Protocol(Generic)
506
507   Base class for protocol classes. Protocol classes are defined like this::
508
509      class Proto(Protocol):
510          def meth(self) -> int:
511              ...
512
513   Such classes are primarily used with static type checkers that recognize
514   structural subtyping (static duck-typing), for example::
515
516      class C:
517          def meth(self) -> int:
518              return 0
519
520      def func(x: Proto) -> int:
521          return x.meth()
522
523      func(C())  # Passes static type check
524
525   See :pep:`544` for details. Protocol classes decorated with
526   :func:`runtime_checkable` (described later) act as simple-minded runtime
527   protocols that check only the presence of given attributes, ignoring their
528   type signatures.
529
530   Protocol classes can be generic, for example::
531
532      class GenProto(Protocol[T]):
533          def meth(self) -> T:
534              ...
535
536   .. versionadded:: 3.8
537
538.. class:: Type(Generic[CT_co])
539
540   A variable annotated with ``C`` may accept a value of type ``C``. In
541   contrast, a variable annotated with ``Type[C]`` may accept values that are
542   classes themselves -- specifically, it will accept the *class object* of
543   ``C``. For example::
544
545      a = 3         # Has type 'int'
546      b = int       # Has type 'Type[int]'
547      c = type(a)   # Also has type 'Type[int]'
548
549   Note that ``Type[C]`` is covariant::
550
551      class User: ...
552      class BasicUser(User): ...
553      class ProUser(User): ...
554      class TeamUser(User): ...
555
556      # Accepts User, BasicUser, ProUser, TeamUser, ...
557      def make_new_user(user_class: Type[User]) -> User:
558          # ...
559          return user_class()
560
561   The fact that ``Type[C]`` is covariant implies that all subclasses of
562   ``C`` should implement the same constructor signature and class method
563   signatures as ``C``. The type checker should flag violations of this,
564   but should also allow constructor calls in subclasses that match the
565   constructor calls in the indicated base class. How the type checker is
566   required to handle this particular case may change in future revisions of
567   :pep:`484`.
568
569   The only legal parameters for :class:`Type` are classes, :data:`Any`,
570   :ref:`type variables <generics>`, and unions of any of these types.
571   For example::
572
573      def new_non_team_user(user_class: Type[Union[BasicUser, ProUser]]): ...
574
575   ``Type[Any]`` is equivalent to ``Type`` which in turn is equivalent
576   to ``type``, which is the root of Python's metaclass hierarchy.
577
578   .. versionadded:: 3.5.2
579
580.. class:: Iterable(Generic[T_co])
581
582    A generic version of :class:`collections.abc.Iterable`.
583
584.. class:: Iterator(Iterable[T_co])
585
586    A generic version of :class:`collections.abc.Iterator`.
587
588.. class:: Reversible(Iterable[T_co])
589
590    A generic version of :class:`collections.abc.Reversible`.
591
592.. class:: SupportsInt
593
594    An ABC with one abstract method ``__int__``.
595
596.. class:: SupportsFloat
597
598    An ABC with one abstract method ``__float__``.
599
600.. class:: SupportsComplex
601
602    An ABC with one abstract method ``__complex__``.
603
604.. class:: SupportsBytes
605
606    An ABC with one abstract method ``__bytes__``.
607
608.. class:: SupportsIndex
609
610    An ABC with one abstract method ``__index__``.
611
612    .. versionadded:: 3.8
613
614.. class:: SupportsAbs
615
616    An ABC with one abstract method ``__abs__`` that is covariant
617    in its return type.
618
619.. class:: SupportsRound
620
621    An ABC with one abstract method ``__round__``
622    that is covariant in its return type.
623
624.. class:: Container(Generic[T_co])
625
626    A generic version of :class:`collections.abc.Container`.
627
628.. class:: Hashable
629
630   An alias to :class:`collections.abc.Hashable`
631
632.. class:: Sized
633
634   An alias to :class:`collections.abc.Sized`
635
636.. class:: Collection(Sized, Iterable[T_co], Container[T_co])
637
638   A generic version of :class:`collections.abc.Collection`
639
640   .. versionadded:: 3.6.0
641
642.. class:: AbstractSet(Sized, Collection[T_co])
643
644    A generic version of :class:`collections.abc.Set`.
645
646.. class:: MutableSet(AbstractSet[T])
647
648    A generic version of :class:`collections.abc.MutableSet`.
649
650.. class:: Mapping(Sized, Collection[KT], Generic[VT_co])
651
652    A generic version of :class:`collections.abc.Mapping`.
653    This type can be used as follows::
654
655      def get_position_in_index(word_list: Mapping[str, int], word: str) -> int:
656          return word_list[word]
657
658.. class:: MutableMapping(Mapping[KT, VT])
659
660    A generic version of :class:`collections.abc.MutableMapping`.
661
662.. class:: Sequence(Reversible[T_co], Collection[T_co])
663
664    A generic version of :class:`collections.abc.Sequence`.
665
666.. class:: MutableSequence(Sequence[T])
667
668   A generic version of :class:`collections.abc.MutableSequence`.
669
670.. class:: ByteString(Sequence[int])
671
672   A generic version of :class:`collections.abc.ByteString`.
673
674   This type represents the types :class:`bytes`, :class:`bytearray`,
675   and :class:`memoryview` of byte sequences.
676
677   As a shorthand for this type, :class:`bytes` can be used to
678   annotate arguments of any of the types mentioned above.
679
680.. class:: Deque(deque, MutableSequence[T])
681
682   A generic version of :class:`collections.deque`.
683
684   .. versionadded:: 3.5.4
685   .. versionadded:: 3.6.1
686
687.. class:: List(list, MutableSequence[T])
688
689   Generic version of :class:`list`.
690   Useful for annotating return types. To annotate arguments it is preferred
691   to use an abstract collection type such as :class:`Sequence` or
692   :class:`Iterable`.
693
694   This type may be used as follows::
695
696      T = TypeVar('T', int, float)
697
698      def vec2(x: T, y: T) -> List[T]:
699          return [x, y]
700
701      def keep_positives(vector: Sequence[T]) -> List[T]:
702          return [item for item in vector if item > 0]
703
704.. class:: Set(set, MutableSet[T])
705
706   A generic version of :class:`builtins.set <set>`.
707   Useful for annotating return types. To annotate arguments it is preferred
708   to use an abstract collection type such as :class:`AbstractSet`.
709
710.. class:: FrozenSet(frozenset, AbstractSet[T_co])
711
712   A generic version of :class:`builtins.frozenset <frozenset>`.
713
714.. class:: MappingView(Sized, Iterable[T_co])
715
716   A generic version of :class:`collections.abc.MappingView`.
717
718.. class:: KeysView(MappingView[KT_co], AbstractSet[KT_co])
719
720   A generic version of :class:`collections.abc.KeysView`.
721
722.. class:: ItemsView(MappingView, Generic[KT_co, VT_co])
723
724   A generic version of :class:`collections.abc.ItemsView`.
725
726.. class:: ValuesView(MappingView[VT_co])
727
728   A generic version of :class:`collections.abc.ValuesView`.
729
730.. class:: Awaitable(Generic[T_co])
731
732   A generic version of :class:`collections.abc.Awaitable`.
733
734   .. versionadded:: 3.5.2
735
736.. class:: Coroutine(Awaitable[V_co], Generic[T_co, T_contra, V_co])
737
738   A generic version of :class:`collections.abc.Coroutine`.
739   The variance and order of type variables
740   correspond to those of :class:`Generator`, for example::
741
742      from typing import List, Coroutine
743      c = None # type: Coroutine[List[str], str, int]
744      ...
745      x = c.send('hi') # type: List[str]
746      async def bar() -> None:
747          x = await c # type: int
748
749   .. versionadded:: 3.5.3
750
751.. class:: AsyncIterable(Generic[T_co])
752
753   A generic version of :class:`collections.abc.AsyncIterable`.
754
755   .. versionadded:: 3.5.2
756
757.. class:: AsyncIterator(AsyncIterable[T_co])
758
759   A generic version of :class:`collections.abc.AsyncIterator`.
760
761   .. versionadded:: 3.5.2
762
763.. class:: ContextManager(Generic[T_co])
764
765   A generic version of :class:`contextlib.AbstractContextManager`.
766
767   .. versionadded:: 3.5.4
768   .. versionadded:: 3.6.0
769
770.. class:: AsyncContextManager(Generic[T_co])
771
772   A generic version of :class:`contextlib.AbstractAsyncContextManager`.
773
774   .. versionadded:: 3.5.4
775   .. versionadded:: 3.6.2
776
777.. class:: Dict(dict, MutableMapping[KT, VT])
778
779   A generic version of :class:`dict`.
780   Useful for annotating return types. To annotate arguments it is preferred
781   to use an abstract collection type such as :class:`Mapping`.
782
783   This type can be used as follows::
784
785      def count_words(text: str) -> Dict[str, int]:
786          ...
787
788.. class:: DefaultDict(collections.defaultdict, MutableMapping[KT, VT])
789
790   A generic version of :class:`collections.defaultdict`.
791
792   .. versionadded:: 3.5.2
793
794.. class:: OrderedDict(collections.OrderedDict, MutableMapping[KT, VT])
795
796   A generic version of :class:`collections.OrderedDict`.
797
798   .. versionadded:: 3.7.2
799
800.. class:: Counter(collections.Counter, Dict[T, int])
801
802   A generic version of :class:`collections.Counter`.
803
804   .. versionadded:: 3.5.4
805   .. versionadded:: 3.6.1
806
807.. class:: ChainMap(collections.ChainMap, MutableMapping[KT, VT])
808
809   A generic version of :class:`collections.ChainMap`.
810
811   .. versionadded:: 3.5.4
812   .. versionadded:: 3.6.1
813
814.. class:: Generator(Iterator[T_co], Generic[T_co, T_contra, V_co])
815
816   A generator can be annotated by the generic type
817   ``Generator[YieldType, SendType, ReturnType]``. For example::
818
819      def echo_round() -> Generator[int, float, str]:
820          sent = yield 0
821          while sent >= 0:
822              sent = yield round(sent)
823          return 'Done'
824
825   Note that unlike many other generics in the typing module, the ``SendType``
826   of :class:`Generator` behaves contravariantly, not covariantly or
827   invariantly.
828
829   If your generator will only yield values, set the ``SendType`` and
830   ``ReturnType`` to ``None``::
831
832      def infinite_stream(start: int) -> Generator[int, None, None]:
833          while True:
834              yield start
835              start += 1
836
837   Alternatively, annotate your generator as having a return type of
838   either ``Iterable[YieldType]`` or ``Iterator[YieldType]``::
839
840      def infinite_stream(start: int) -> Iterator[int]:
841          while True:
842              yield start
843              start += 1
844
845.. class:: AsyncGenerator(AsyncIterator[T_co], Generic[T_co, T_contra])
846
847   An async generator can be annotated by the generic type
848   ``AsyncGenerator[YieldType, SendType]``. For example::
849
850      async def echo_round() -> AsyncGenerator[int, float]:
851          sent = yield 0
852          while sent >= 0.0:
853              rounded = await round(sent)
854              sent = yield rounded
855
856   Unlike normal generators, async generators cannot return a value, so there
857   is no ``ReturnType`` type parameter. As with :class:`Generator`, the
858   ``SendType`` behaves contravariantly.
859
860   If your generator will only yield values, set the ``SendType`` to
861   ``None``::
862
863      async def infinite_stream(start: int) -> AsyncGenerator[int, None]:
864          while True:
865              yield start
866              start = await increment(start)
867
868   Alternatively, annotate your generator as having a return type of
869   either ``AsyncIterable[YieldType]`` or ``AsyncIterator[YieldType]``::
870
871      async def infinite_stream(start: int) -> AsyncIterator[int]:
872          while True:
873              yield start
874              start = await increment(start)
875
876   .. versionadded:: 3.6.1
877
878.. class:: Text
879
880   ``Text`` is an alias for ``str``. It is provided to supply a forward
881   compatible path for Python 2 code: in Python 2, ``Text`` is an alias for
882   ``unicode``.
883
884   Use ``Text`` to indicate that a value must contain a unicode string in
885   a manner that is compatible with both Python 2 and Python 3::
886
887       def add_unicode_checkmark(text: Text) -> Text:
888           return text + u' \u2713'
889
890   .. versionadded:: 3.5.2
891
892.. class:: IO
893           TextIO
894           BinaryIO
895
896   Generic type ``IO[AnyStr]`` and its subclasses ``TextIO(IO[str])``
897   and ``BinaryIO(IO[bytes])``
898   represent the types of I/O streams such as returned by
899   :func:`open`.
900
901.. class:: Pattern
902           Match
903
904   These type aliases
905   correspond to the return types from :func:`re.compile` and
906   :func:`re.match`.  These types (and the corresponding functions)
907   are generic in ``AnyStr`` and can be made specific by writing
908   ``Pattern[str]``, ``Pattern[bytes]``, ``Match[str]``, or
909   ``Match[bytes]``.
910
911.. class:: NamedTuple
912
913   Typed version of :func:`collections.namedtuple`.
914
915   Usage::
916
917       class Employee(NamedTuple):
918           name: str
919           id: int
920
921   This is equivalent to::
922
923       Employee = collections.namedtuple('Employee', ['name', 'id'])
924
925   To give a field a default value, you can assign to it in the class body::
926
927      class Employee(NamedTuple):
928          name: str
929          id: int = 3
930
931      employee = Employee('Guido')
932      assert employee.id == 3
933
934   Fields with a default value must come after any fields without a default.
935
936   The resulting class has an extra attribute ``__annotations__`` giving a
937   dict that maps the field names to the field types.  (The field names are in
938   the ``_fields`` attribute and the default values are in the
939   ``_field_defaults`` attribute both of which are part of the namedtuple
940   API.)
941
942   ``NamedTuple`` subclasses can also have docstrings and methods::
943
944      class Employee(NamedTuple):
945          """Represents an employee."""
946          name: str
947          id: int = 3
948
949          def __repr__(self) -> str:
950              return f'<Employee {self.name}, id={self.id}>'
951
952   Backward-compatible usage::
953
954       Employee = NamedTuple('Employee', [('name', str), ('id', int)])
955
956   .. versionchanged:: 3.6
957      Added support for :pep:`526` variable annotation syntax.
958
959   .. versionchanged:: 3.6.1
960      Added support for default values, methods, and docstrings.
961
962   .. deprecated-removed:: 3.8 3.9
963      Deprecated the ``_field_types`` attribute in favor of the more
964      standard ``__annotations__`` attribute which has the same information.
965
966   .. versionchanged:: 3.8
967      The ``_field_types`` and ``__annotations__`` attributes are
968      now regular dictionaries instead of instances of ``OrderedDict``.
969
970.. class:: TypedDict(dict)
971
972   A simple typed namespace. At runtime it is equivalent to
973   a plain :class:`dict`.
974
975   ``TypedDict`` creates a dictionary type that expects all of its
976   instances to have a certain set of keys, where each key is
977   associated with a value of a consistent type. This expectation
978   is not checked at runtime but is only enforced by type checkers.
979   Usage::
980
981      class Point2D(TypedDict):
982          x: int
983          y: int
984          label: str
985
986      a: Point2D = {'x': 1, 'y': 2, 'label': 'good'}  # OK
987      b: Point2D = {'z': 3, 'label': 'bad'}           # Fails type check
988
989      assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
990
991   The type info for introspection can be accessed via ``Point2D.__annotations__``
992   and ``Point2D.__total__``.  To allow using this feature with older versions
993   of Python that do not support :pep:`526`, ``TypedDict`` supports two additional
994   equivalent syntactic forms::
995
996      Point2D = TypedDict('Point2D', x=int, y=int, label=str)
997      Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
998
999   By default, all keys must be present in a TypedDict. It is possible
1000   to override this by specifying totality.
1001   Usage::
1002
1003      class point2D(TypedDict, total=False):
1004          x: int
1005          y: int
1006
1007   This means that a point2D TypedDict can have any of the keys omitted. A type
1008   checker is only expected to support a literal False or True as the value of
1009   the total argument. True is the default, and makes all items defined in the
1010   class body be required.
1011
1012   See :pep:`589` for more examples and detailed rules of using ``TypedDict``.
1013
1014   .. versionadded:: 3.8
1015
1016.. class:: ForwardRef
1017
1018   A class used for internal typing representation of string forward references.
1019   For example, ``List["SomeClass"]`` is implicitly transformed into
1020   ``List[ForwardRef("SomeClass")]``.  This class should not be instantiated by
1021   a user, but may be used by introspection tools.
1022
1023   .. versionadded:: 3.7.4
1024
1025.. function:: NewType(name, tp)
1026
1027   A helper function to indicate a distinct type to a typechecker,
1028   see :ref:`distinct`. At runtime it returns a function that returns
1029   its argument. Usage::
1030
1031      UserId = NewType('UserId', int)
1032      first_user = UserId(1)
1033
1034   .. versionadded:: 3.5.2
1035
1036.. function:: cast(typ, val)
1037
1038   Cast a value to a type.
1039
1040   This returns the value unchanged.  To the type checker this
1041   signals that the return value has the designated type, but at
1042   runtime we intentionally don't check anything (we want this
1043   to be as fast as possible).
1044
1045.. function:: get_type_hints(obj[, globals[, locals]])
1046
1047   Return a dictionary containing type hints for a function, method, module
1048   or class object.
1049
1050   This is often the same as ``obj.__annotations__``. In addition,
1051   forward references encoded as string literals are handled by evaluating
1052   them in ``globals`` and ``locals`` namespaces. If necessary,
1053   ``Optional[t]`` is added for function and method annotations if a default
1054   value equal to ``None`` is set. For a class ``C``, return
1055   a dictionary constructed by merging all the ``__annotations__`` along
1056   ``C.__mro__`` in reverse order.
1057
1058.. function:: get_origin(tp)
1059.. function:: get_args(tp)
1060
1061   Provide basic introspection for generic types and special typing forms.
1062
1063   For a typing object of the form ``X[Y, Z, ...]`` these functions return
1064   ``X`` and ``(Y, Z, ...)``. If ``X`` is a generic alias for a builtin or
1065   :mod:`collections` class, it gets normalized to the original class.
1066   For unsupported objects return ``None`` and ``()`` correspondingly.
1067   Examples::
1068
1069      assert get_origin(Dict[str, int]) is dict
1070      assert get_args(Dict[int, str]) == (int, str)
1071
1072      assert get_origin(Union[int, str]) is Union
1073      assert get_args(Union[int, str]) == (int, str)
1074
1075   .. versionadded:: 3.8
1076
1077.. decorator:: overload
1078
1079   The ``@overload`` decorator allows describing functions and methods
1080   that support multiple different combinations of argument types. A series
1081   of ``@overload``-decorated definitions must be followed by exactly one
1082   non-``@overload``-decorated definition (for the same function/method).
1083   The ``@overload``-decorated definitions are for the benefit of the
1084   type checker only, since they will be overwritten by the
1085   non-``@overload``-decorated definition, while the latter is used at
1086   runtime but should be ignored by a type checker.  At runtime, calling
1087   a ``@overload``-decorated function directly will raise
1088   :exc:`NotImplementedError`. An example of overload that gives a more
1089   precise type than can be expressed using a union or a type variable::
1090
1091      @overload
1092      def process(response: None) -> None:
1093          ...
1094      @overload
1095      def process(response: int) -> Tuple[int, str]:
1096          ...
1097      @overload
1098      def process(response: bytes) -> str:
1099          ...
1100      def process(response):
1101          <actual implementation>
1102
1103   See :pep:`484` for details and comparison with other typing semantics.
1104
1105.. decorator:: final
1106
1107   A decorator to indicate to type checkers that the decorated method
1108   cannot be overridden, and the decorated class cannot be subclassed.
1109   For example::
1110
1111      class Base:
1112          @final
1113          def done(self) -> None:
1114              ...
1115      class Sub(Base):
1116          def done(self) -> None:  # Error reported by type checker
1117                ...
1118
1119      @final
1120      class Leaf:
1121          ...
1122      class Other(Leaf):  # Error reported by type checker
1123          ...
1124
1125   There is no runtime checking of these properties. See :pep:`591` for
1126   more details.
1127
1128   .. versionadded:: 3.8
1129
1130.. decorator:: no_type_check
1131
1132   Decorator to indicate that annotations are not type hints.
1133
1134   This works as class or function :term:`decorator`.  With a class, it
1135   applies recursively to all methods defined in that class (but not
1136   to methods defined in its superclasses or subclasses).
1137
1138   This mutates the function(s) in place.
1139
1140.. decorator:: no_type_check_decorator
1141
1142   Decorator to give another decorator the :func:`no_type_check` effect.
1143
1144   This wraps the decorator with something that wraps the decorated
1145   function in :func:`no_type_check`.
1146
1147.. decorator:: type_check_only
1148
1149   Decorator to mark a class or function to be unavailable at runtime.
1150
1151   This decorator is itself not available at runtime. It is mainly
1152   intended to mark classes that are defined in type stub files if
1153   an implementation returns an instance of a private class::
1154
1155      @type_check_only
1156      class Response:  # private or not available at runtime
1157          code: int
1158          def get_header(self, name: str) -> str: ...
1159
1160      def fetch_response() -> Response: ...
1161
1162   Note that returning instances of private classes is not recommended.
1163   It is usually preferable to make such classes public.
1164
1165.. decorator:: runtime_checkable
1166
1167   Mark a protocol class as a runtime protocol.
1168
1169   Such a protocol can be used with :func:`isinstance` and :func:`issubclass`.
1170   This raises :exc:`TypeError` when applied to a non-protocol class.  This
1171   allows a simple-minded structural check, very similar to "one trick ponies"
1172   in :mod:`collections.abc` such as :class:`~collections.abc.Iterable`.  For example::
1173
1174      @runtime_checkable
1175      class Closable(Protocol):
1176          def close(self): ...
1177
1178      assert isinstance(open('/some/file'), Closable)
1179
1180   **Warning:** this will check only the presence of the required methods,
1181   not their type signatures!
1182
1183   .. versionadded:: 3.8
1184
1185.. data:: Any
1186
1187   Special type indicating an unconstrained type.
1188
1189   * Every type is compatible with :data:`Any`.
1190   * :data:`Any` is compatible with every type.
1191
1192.. data:: NoReturn
1193
1194   Special type indicating that a function never returns.
1195   For example::
1196
1197      from typing import NoReturn
1198
1199      def stop() -> NoReturn:
1200          raise RuntimeError('no way')
1201
1202   .. versionadded:: 3.5.4
1203   .. versionadded:: 3.6.2
1204
1205.. data:: Union
1206
1207   Union type; ``Union[X, Y]`` means either X or Y.
1208
1209   To define a union, use e.g. ``Union[int, str]``.  Details:
1210
1211   * The arguments must be types and there must be at least one.
1212
1213   * Unions of unions are flattened, e.g.::
1214
1215       Union[Union[int, str], float] == Union[int, str, float]
1216
1217   * Unions of a single argument vanish, e.g.::
1218
1219       Union[int] == int  # The constructor actually returns int
1220
1221   * Redundant arguments are skipped, e.g.::
1222
1223       Union[int, str, int] == Union[int, str]
1224
1225   * When comparing unions, the argument order is ignored, e.g.::
1226
1227       Union[int, str] == Union[str, int]
1228
1229   * You cannot subclass or instantiate a union.
1230
1231   * You cannot write ``Union[X][Y]``.
1232
1233   * You can use ``Optional[X]`` as a shorthand for ``Union[X, None]``.
1234
1235   .. versionchanged:: 3.7
1236      Don't remove explicit subclasses from unions at runtime.
1237
1238.. data:: Optional
1239
1240   Optional type.
1241
1242   ``Optional[X]`` is equivalent to ``Union[X, None]``.
1243
1244   Note that this is not the same concept as an optional argument,
1245   which is one that has a default.  An optional argument with a
1246   default does not require the ``Optional`` qualifier on its type
1247   annotation just because it is optional. For example::
1248
1249      def foo(arg: int = 0) -> None:
1250          ...
1251
1252   On the other hand, if an explicit value of ``None`` is allowed, the
1253   use of ``Optional`` is appropriate, whether the argument is optional
1254   or not. For example::
1255
1256      def foo(arg: Optional[int] = None) -> None:
1257          ...
1258
1259.. data:: Tuple
1260
1261   Tuple type; ``Tuple[X, Y]`` is the type of a tuple of two items
1262   with the first item of type X and the second of type Y. The type of
1263   the empty tuple can be written as ``Tuple[()]``.
1264
1265   Example: ``Tuple[T1, T2]`` is a tuple of two elements corresponding
1266   to type variables T1 and T2.  ``Tuple[int, float, str]`` is a tuple
1267   of an int, a float and a string.
1268
1269   To specify a variable-length tuple of homogeneous type,
1270   use literal ellipsis, e.g. ``Tuple[int, ...]``. A plain :data:`Tuple`
1271   is equivalent to ``Tuple[Any, ...]``, and in turn to :class:`tuple`.
1272
1273.. data:: Callable
1274
1275   Callable type; ``Callable[[int], str]`` is a function of (int) -> str.
1276
1277   The subscription syntax must always be used with exactly two
1278   values: the argument list and the return type.  The argument list
1279   must be a list of types or an ellipsis; the return type must be
1280   a single type.
1281
1282   There is no syntax to indicate optional or keyword arguments;
1283   such function types are rarely used as callback types.
1284   ``Callable[..., ReturnType]`` (literal ellipsis) can be used to
1285   type hint a callable taking any number of arguments and returning
1286   ``ReturnType``.  A plain :data:`Callable` is equivalent to
1287   ``Callable[..., Any]``, and in turn to
1288   :class:`collections.abc.Callable`.
1289
1290.. data:: Literal
1291
1292   A type that can be used to indicate to type checkers that the
1293   corresponding variable or function parameter has a value equivalent to
1294   the provided literal (or one of several literals). For example::
1295
1296      def validate_simple(data: Any) -> Literal[True]:  # always returns True
1297          ...
1298
1299      MODE = Literal['r', 'rb', 'w', 'wb']
1300      def open_helper(file: str, mode: MODE) -> str:
1301          ...
1302
1303      open_helper('/some/path', 'r')  # Passes type check
1304      open_helper('/other/path', 'typo')  # Error in type checker
1305
1306   ``Literal[...]`` cannot be subclassed. At runtime, an arbitrary value
1307   is allowed as type argument to ``Literal[...]``, but type checkers may
1308   impose restrictions. See :pep:`586` for more details about literal types.
1309
1310   .. versionadded:: 3.8
1311
1312.. data:: ClassVar
1313
1314   Special type construct to mark class variables.
1315
1316   As introduced in :pep:`526`, a variable annotation wrapped in ClassVar
1317   indicates that a given attribute is intended to be used as a class variable
1318   and should not be set on instances of that class. Usage::
1319
1320      class Starship:
1321          stats: ClassVar[Dict[str, int]] = {} # class variable
1322          damage: int = 10                     # instance variable
1323
1324   :data:`ClassVar` accepts only types and cannot be further subscribed.
1325
1326   :data:`ClassVar` is not a class itself, and should not
1327   be used with :func:`isinstance` or :func:`issubclass`.
1328   :data:`ClassVar` does not change Python runtime behavior, but
1329   it can be used by third-party type checkers. For example, a type checker
1330   might flag the following code as an error::
1331
1332      enterprise_d = Starship(3000)
1333      enterprise_d.stats = {} # Error, setting class variable on instance
1334      Starship.stats = {}     # This is OK
1335
1336   .. versionadded:: 3.5.3
1337
1338.. data:: Final
1339
1340   A special typing construct to indicate to type checkers that a name
1341   cannot be re-assigned or overridden in a subclass. For example::
1342
1343      MAX_SIZE: Final = 9000
1344      MAX_SIZE += 1  # Error reported by type checker
1345
1346      class Connection:
1347          TIMEOUT: Final[int] = 10
1348
1349      class FastConnector(Connection):
1350          TIMEOUT = 1  # Error reported by type checker
1351
1352   There is no runtime checking of these properties. See :pep:`591` for
1353   more details.
1354
1355   .. versionadded:: 3.8
1356
1357.. data:: AnyStr
1358
1359   ``AnyStr`` is a type variable defined as
1360   ``AnyStr = TypeVar('AnyStr', str, bytes)``.
1361
1362   It is meant to be used for functions that may accept any kind of string
1363   without allowing different kinds of strings to mix. For example::
1364
1365      def concat(a: AnyStr, b: AnyStr) -> AnyStr:
1366          return a + b
1367
1368      concat(u"foo", u"bar")  # Ok, output has type 'unicode'
1369      concat(b"foo", b"bar")  # Ok, output has type 'bytes'
1370      concat(u"foo", b"bar")  # Error, cannot mix unicode and bytes
1371
1372.. data:: TYPE_CHECKING
1373
1374   A special constant that is assumed to be ``True`` by 3rd party static
1375   type checkers. It is ``False`` at runtime. Usage::
1376
1377      if TYPE_CHECKING:
1378          import expensive_mod
1379
1380      def fun(arg: 'expensive_mod.SomeType') -> None:
1381          local_var: expensive_mod.AnotherType = other_fun()
1382
1383   Note that the first type annotation must be enclosed in quotes, making it a
1384   "forward reference", to hide the ``expensive_mod`` reference from the
1385   interpreter runtime.  Type annotations for local variables are not
1386   evaluated, so the second annotation does not need to be enclosed in quotes.
1387
1388   .. versionadded:: 3.5.2
1389