[Python-checkins] [3.12] Typing docs: move the deprecated stuff below the non-deprecated stuff (#105781) (#105783)
AlexWaygood
webhook-mailer at python.org
Wed Jun 14 11:03:38 EDT 2023
https://github.com/python/cpython/commit/52a2bbdc9d6d62bad34d9bc42db613ea498ded1a
commit: 52a2bbdc9d6d62bad34d9bc42db613ea498ded1a
branch: 3.12
author: Alex Waygood <Alex.Waygood at Gmail.com>
committer: AlexWaygood <Alex.Waygood at Gmail.com>
date: 2023-06-14T16:03:30+01:00
summary:
[3.12] Typing docs: move the deprecated stuff below the non-deprecated stuff (#105781) (#105783)
files:
M Doc/library/typing.rst
diff --git a/Doc/library/typing.rst b/Doc/library/typing.rst
index caf4a53006f5e..7e10b03eaa89d 100644
--- a/Doc/library/typing.rst
+++ b/Doc/library/typing.rst
@@ -2383,1093 +2383,1093 @@ These are not used in annotations. They are building blocks for declaring types.
.. versionchanged:: 3.11
Added support for generic ``TypedDict``\ s.
-Generic concrete collections
-----------------------------
+Protocols
+---------
-Corresponding to built-in types
-"""""""""""""""""""""""""""""""
+These protocols are decorated with :func:`runtime_checkable`.
-.. class:: Dict(dict, MutableMapping[KT, VT])
+.. class:: SupportsAbs
- Deprecated alias to :class:`dict`.
+ An ABC with one abstract method ``__abs__`` that is covariant
+ in its return type.
- Note that to annotate arguments, it is preferred
- to use an abstract collection type such as :class:`Mapping`
- rather than to use :class:`dict` or :class:`!typing.Dict`.
+.. class:: SupportsBytes
- This type can be used as follows::
+ An ABC with one abstract method ``__bytes__``.
- def count_words(text: str) -> Dict[str, int]:
- ...
+.. class:: SupportsComplex
- .. deprecated:: 3.9
- :class:`builtins.dict <dict>` now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+ An ABC with one abstract method ``__complex__``.
-.. class:: List(list, MutableSequence[T])
+.. class:: SupportsFloat
- Deprecated alias to :class:`list`.
+ An ABC with one abstract method ``__float__``.
- Note that to annotate arguments, it is preferred
- to use an abstract collection type such as :class:`Sequence` or
- :class:`Iterable` rather than to use :class:`list` or :class:`!typing.List`.
+.. class:: SupportsIndex
- This type may be used as follows::
+ An ABC with one abstract method ``__index__``.
- def vec2[T: (int, float)](x: T, y: T) -> List[T]:
- return [x, y]
+ .. versionadded:: 3.8
- def keep_positives[T: (int, float)](vector: Sequence[T]) -> List[T]:
- return [item for item in vector if item > 0]
+.. class:: SupportsInt
- .. deprecated:: 3.9
- :class:`builtins.list <list>` now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+ An ABC with one abstract method ``__int__``.
-.. class:: Set(set, MutableSet[T])
+.. class:: SupportsRound
- Deprecated alias to :class:`builtins.set <set>`.
+ An ABC with one abstract method ``__round__``
+ that is covariant in its return type.
- Note that to annotate arguments, it is preferred
- to use an abstract collection type such as :class:`AbstractSet`
- rather than to use :class:`set` or :class:`!typing.Set`.
+Functions and decorators
+------------------------
- .. deprecated:: 3.9
- :class:`builtins.set <set>` now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+.. function:: cast(typ, val)
-.. class:: FrozenSet(frozenset, AbstractSet[T_co])
+ Cast a value to a type.
- Deprecated alias to :class:`builtins.frozenset <frozenset>`.
+ This returns the value unchanged. To the type checker this
+ signals that the return value has the designated type, but at
+ runtime we intentionally don't check anything (we want this
+ to be as fast as possible).
- .. deprecated:: 3.9
- :class:`builtins.frozenset <frozenset>`
- now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+.. function:: assert_type(val, typ, /)
-.. note:: :data:`Tuple` is a special form.
+ Ask a static type checker to confirm that *val* has an inferred type of *typ*.
-Corresponding to types in :mod:`collections`
-""""""""""""""""""""""""""""""""""""""""""""
+ At runtime this does nothing: it returns the first argument unchanged with no
+ checks or side effects, no matter the actual type of the argument.
-.. class:: DefaultDict(collections.defaultdict, MutableMapping[KT, VT])
+ When a static type checker encounters a call to ``assert_type()``, it
+ emits an error if the value is not of the specified type::
- Deprecated alias to :class:`collections.defaultdict`.
+ def greet(name: str) -> None:
+ assert_type(name, str) # OK, inferred type of `name` is `str`
+ assert_type(name, int) # type checker error
- .. versionadded:: 3.5.2
+ This function is useful for ensuring the type checker's understanding of a
+ script is in line with the developer's intentions::
- .. deprecated:: 3.9
- :class:`collections.defaultdict` now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+ def complex_function(arg: object):
+ # Do some complex type-narrowing logic,
+ # after which we hope the inferred type will be `int`
+ ...
+ # Test whether the type checker correctly understands our function
+ assert_type(arg, int)
-.. class:: OrderedDict(collections.OrderedDict, MutableMapping[KT, VT])
+ .. versionadded:: 3.11
- Deprecated alias to :class:`collections.OrderedDict`.
+.. function:: assert_never(arg, /)
- .. versionadded:: 3.7.2
+ Ask a static type checker to confirm that a line of code is unreachable.
- .. deprecated:: 3.9
- :class:`collections.OrderedDict` now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+ Example::
-.. class:: ChainMap(collections.ChainMap, MutableMapping[KT, VT])
+ def int_or_str(arg: int | str) -> None:
+ match arg:
+ case int():
+ print("It's an int")
+ case str():
+ print("It's a str")
+ case _ as unreachable:
+ assert_never(unreachable)
- Deprecated alias to :class:`collections.ChainMap`.
+ Here, the annotations allow the type checker to infer that the
+ last case can never execute, because ``arg`` is either
+ an :class:`int` or a :class:`str`, and both options are covered by
+ earlier cases.
- .. versionadded:: 3.5.4
- .. versionadded:: 3.6.1
+ If a type checker finds that a call to ``assert_never()`` is
+ reachable, it will emit an error. For example, if the type annotation
+ for ``arg`` was instead ``int | str | float``, the type checker would
+ emit an error pointing out that ``unreachable`` is of type :class:`float`.
+ For a call to ``assert_never`` to pass type checking, the inferred type of
+ the argument passed in must be the bottom type, :data:`Never`, and nothing
+ else.
- .. deprecated:: 3.9
- :class:`collections.ChainMap` now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+ At runtime, this throws an exception when called.
-.. class:: Counter(collections.Counter, Dict[T, int])
+ .. seealso::
+ `Unreachable Code and Exhaustiveness Checking
+ <https://typing.readthedocs.io/en/latest/source/unreachable.html>`__ has more
+ information about exhaustiveness checking with static typing.
- Deprecated alias to :class:`collections.Counter`.
+ .. versionadded:: 3.11
- .. versionadded:: 3.5.4
- .. versionadded:: 3.6.1
+.. function:: reveal_type(obj, /)
- .. deprecated:: 3.9
- :class:`collections.Counter` now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+ Reveal the inferred static type of an expression.
-.. class:: Deque(deque, MutableSequence[T])
+ When a static type checker encounters a call to this function,
+ it emits a diagnostic with the type of the argument. For example::
- Deprecated alias to :class:`collections.deque`.
+ x: int = 1
+ reveal_type(x) # Revealed type is "builtins.int"
- .. versionadded:: 3.5.4
- .. versionadded:: 3.6.1
+ This can be useful when you want to debug how your type checker
+ handles a particular piece of code.
- .. deprecated:: 3.9
- :class:`collections.deque` now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+ The function returns its argument unchanged, which allows using
+ it within an expression::
-Other concrete types
-""""""""""""""""""""
+ x = reveal_type(1) # Revealed type is "builtins.int"
-.. class:: IO
- TextIO
- BinaryIO
+ Most type checkers support ``reveal_type()`` anywhere, even if the
+ name is not imported from ``typing``. Importing the name from
+ ``typing`` allows your code to run without runtime errors and
+ communicates intent more clearly.
- Generic type ``IO[AnyStr]`` and its subclasses ``TextIO(IO[str])``
- and ``BinaryIO(IO[bytes])``
- represent the types of I/O streams such as returned by
- :func:`open`.
+ At runtime, this function prints the runtime type of its argument to stderr
+ and returns it unchanged::
- .. deprecated-removed:: 3.8 3.13
- The ``typing.io`` namespace is deprecated and will be removed.
- These types should be directly imported from ``typing`` instead.
+ x = reveal_type(1) # prints "Runtime type is int"
+ print(x) # prints "1"
-.. class:: Pattern
- Match
+ .. versionadded:: 3.11
- Deprecated aliases corresponding to the return types from
- :func:`re.compile` and :func:`re.match`.
+.. decorator:: dataclass_transform
- These types (and the corresponding functions) are generic over
- :data:`AnyStr`. ``Pattern`` can be specialised as ``Pattern[str]`` or
- ``Pattern[bytes]``; ``Match`` can be specialised as ``Match[str]`` or
- ``Match[bytes]``.
+ Decorator to mark an object as providing
+ :func:`~dataclasses.dataclass`-like behavior.
- .. deprecated-removed:: 3.8 3.13
- The ``typing.re`` namespace is deprecated and will be removed.
- These types should be directly imported from ``typing`` instead.
+ ``dataclass_transform`` may be used to
+ decorate a class, metaclass, or a function that is itself a decorator.
+ The presence of ``@dataclass_transform()`` tells a static type checker that the
+ decorated object performs runtime "magic" that
+ transforms a class in a similar way to :func:`dataclasses.dataclass`.
- .. deprecated:: 3.9
- Classes ``Pattern`` and ``Match`` from :mod:`re` now support ``[]``.
- See :pep:`585` and :ref:`types-genericalias`.
+ Example usage with a decorator function:
-.. class:: Text
+ .. testcode::
- Deprecated alias for :class:`str`.
+ @dataclass_transform()
+ def create_model[T](cls: type[T]) -> type[T]:
+ ...
+ return cls
- ``Text`` is provided to supply a forward
- compatible path for Python 2 code: in Python 2, ``Text`` is an alias for
- ``unicode``.
+ @create_model
+ class CustomerModel:
+ id: int
+ name: str
- Use ``Text`` to indicate that a value must contain a unicode string in
- a manner that is compatible with both Python 2 and Python 3::
+ On a base class::
- def add_unicode_checkmark(text: Text) -> Text:
- return text + u' \u2713'
+ @dataclass_transform()
+ class ModelBase: ...
- .. versionadded:: 3.5.2
+ class CustomerModel(ModelBase):
+ id: int
+ name: str
- .. deprecated:: 3.11
- Python 2 is no longer supported, and most type checkers also no longer
- support type checking Python 2 code. Removal of the alias is not
- currently planned, but users are encouraged to use
- :class:`str` instead of ``Text``.
+ On a metaclass::
-Abstract Base Classes
----------------------
+ @dataclass_transform()
+ class ModelMeta(type): ...
-Corresponding to collections in :mod:`collections.abc`
-""""""""""""""""""""""""""""""""""""""""""""""""""""""
+ class ModelBase(metaclass=ModelMeta): ...
-.. class:: AbstractSet(Collection[T_co])
+ class CustomerModel(ModelBase):
+ id: int
+ name: str
- Deprecated alias to :class:`collections.abc.Set`.
+ The ``CustomerModel`` classes defined above will
+ be treated by type checkers similarly to classes created with
+ :func:`@dataclasses.dataclass <dataclasses.dataclass>`.
+ For example, type checkers will assume these classes have
+ ``__init__`` methods that accept ``id`` and ``name``.
- .. deprecated:: 3.9
- :class:`collections.abc.Set` now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+ The decorated class, metaclass, or function may accept the following bool
+ arguments which type checkers will assume have the same effect as they
+ would have on the
+ :func:`@dataclasses.dataclass<dataclasses.dataclass>` decorator: ``init``,
+ ``eq``, ``order``, ``unsafe_hash``, ``frozen``, ``match_args``,
+ ``kw_only``, and ``slots``. It must be possible for the value of these
+ arguments (``True`` or ``False``) to be statically evaluated.
-.. class:: ByteString(Sequence[int])
+ The arguments to the ``dataclass_transform`` decorator can be used to
+ customize the default behaviors of the decorated class, metaclass, or
+ function:
- This type represents the types :class:`bytes`, :class:`bytearray`,
- and :class:`memoryview` of byte sequences.
+ * ``eq_default`` indicates whether the ``eq`` parameter is assumed to be
+ ``True`` or ``False`` if it is omitted by the caller.
+ * ``order_default`` indicates whether the ``order`` parameter is
+ assumed to be True or False if it is omitted by the caller.
+ * ``kw_only_default`` indicates whether the ``kw_only`` parameter is
+ assumed to be True or False if it is omitted by the caller.
+ * ``frozen_default`` indicates whether the ``frozen`` parameter is
+ assumed to be True or False if it is omitted by the caller.
- .. deprecated-removed:: 3.9 3.14
- Prefer :class:`collections.abc.Buffer`, or a union like ``bytes | bytearray | memoryview``.
+ .. versionadded:: 3.12
+ * ``field_specifiers`` specifies a static list of supported classes
+ or functions that describe fields, similar to ``dataclasses.field()``.
+ * Arbitrary other keyword arguments are accepted in order to allow for
+ possible future extensions.
-.. class:: Collection(Sized, Iterable[T_co], Container[T_co])
+ Type checkers recognize the following optional arguments on field
+ specifiers:
- Deprecated alias to :class:`collections.abc.Collection`.
+ * ``init`` indicates whether the field should be included in the
+ synthesized ``__init__`` method. If unspecified, ``init`` defaults to
+ ``True``.
+ * ``default`` provides the default value for the field.
+ * ``default_factory`` provides a runtime callback that returns the
+ default value for the field. If neither ``default`` nor
+ ``default_factory`` are specified, the field is assumed to have no
+ default value and must be provided a value when the class is
+ instantiated.
+ * ``factory`` is an alias for ``default_factory``.
+ * ``kw_only`` indicates whether the field should be marked as
+ keyword-only. If ``True``, the field will be keyword-only. If
+ ``False``, it will not be keyword-only. If unspecified, the value of
+ the ``kw_only`` parameter on the object decorated with
+ ``dataclass_transform`` will be used, or if that is unspecified, the
+ value of ``kw_only_default`` on ``dataclass_transform`` will be used.
+ * ``alias`` provides an alternative name for the field. This alternative
+ name is used in the synthesized ``__init__`` method.
- .. versionadded:: 3.6.0
+ At runtime, this decorator records its arguments in the
+ ``__dataclass_transform__`` attribute on the decorated object.
+ It has no other runtime effect.
- .. deprecated:: 3.9
- :class:`collections.abc.Collection` now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+ See :pep:`681` for more details.
-.. class:: Container(Generic[T_co])
+ .. versionadded:: 3.11
- Deprecated alias to :class:`collections.abc.Container`.
+.. decorator:: overload
- .. deprecated:: 3.9
- :class:`collections.abc.Container` now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+ Decorator for creating overloaded functions and methods.
-.. class:: ItemsView(MappingView, AbstractSet[tuple[KT_co, VT_co]])
+ The ``@overload`` decorator allows describing functions and methods
+ that support multiple different combinations of argument types. A series
+ of ``@overload``-decorated definitions must be followed by exactly one
+ non-``@overload``-decorated definition (for the same function/method).
- Deprecated alias to :class:`collections.abc.ItemsView`.
+ ``@overload``-decorated definitions are for the benefit of the
+ type checker only, since they will be overwritten by the
+ non-``@overload``-decorated definition. The non-``@overload``-decorated
+ definition, meanwhile, will be used at
+ runtime but should be ignored by a type checker. At runtime, calling
+ an ``@overload``-decorated function directly will raise
+ :exc:`NotImplementedError`.
- .. deprecated:: 3.9
- :class:`collections.abc.ItemsView` now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+ An example of overload that gives a more
+ precise type than can be expressed using a union or a type variable:
-.. class:: KeysView(MappingView, AbstractSet[KT_co])
+ .. testcode::
- Deprecated alias to :class:`collections.abc.KeysView`.
+ @overload
+ def process(response: None) -> None:
+ ...
+ @overload
+ def process(response: int) -> tuple[int, str]:
+ ...
+ @overload
+ def process(response: bytes) -> str:
+ ...
+ def process(response):
+ ... # actual implementation goes here
- .. deprecated:: 3.9
- :class:`collections.abc.KeysView` now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+ See :pep:`484` for more details and comparison with other typing semantics.
-.. class:: Mapping(Collection[KT], Generic[KT, VT_co])
+ .. versionchanged:: 3.11
+ Overloaded functions can now be introspected at runtime using
+ :func:`get_overloads`.
- Deprecated alias to :class:`collections.abc.Mapping`.
- This type can be used as follows::
+.. function:: get_overloads(func)
- def get_position_in_index(word_list: Mapping[str, int], word: str) -> int:
- return word_list[word]
+ Return a sequence of :func:`@overload <overload>`-decorated definitions for
+ *func*.
- .. deprecated:: 3.9
- :class:`collections.abc.Mapping` now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+ *func* is the function object for the implementation of the
+ overloaded function. For example, given the definition of ``process`` in
+ the documentation for :func:`@overload <overload>`,
+ ``get_overloads(process)`` will return a sequence of three function objects
+ for the three defined overloads. If called on a function with no overloads,
+ ``get_overloads()`` returns an empty sequence.
-.. class:: MappingView(Sized)
+ ``get_overloads()`` can be used for introspecting an overloaded function at
+ runtime.
- Deprecated alias to :class:`collections.abc.MappingView`.
+ .. versionadded:: 3.11
- .. deprecated:: 3.9
- :class:`collections.abc.MappingView` now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
-.. class:: MutableMapping(Mapping[KT, VT])
+.. function:: clear_overloads()
- Deprecated alias to :class:`collections.abc.MutableMapping`.
+ Clear all registered overloads in the internal registry.
- .. deprecated:: 3.9
- :class:`collections.abc.MutableMapping`
- now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+ This can be used to reclaim the memory used by the registry.
-.. class:: MutableSequence(Sequence[T])
+ .. versionadded:: 3.11
- Deprecated alias to :class:`collections.abc.MutableSequence`.
- .. deprecated:: 3.9
- :class:`collections.abc.MutableSequence`
- now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+.. decorator:: final
-.. class:: MutableSet(AbstractSet[T])
+ Decorator to indicate final methods and final classes.
- Deprecated alias to :class:`collections.abc.MutableSet`.
+ Decorating a method with ``@final`` indicates to a type checker that the
+ method cannot be overridden in a subclass. Decorating a class with ``@final``
+ indicates that it cannot be subclassed.
- .. deprecated:: 3.9
- :class:`collections.abc.MutableSet` now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+ For example::
-.. class:: Sequence(Reversible[T_co], Collection[T_co])
+ class Base:
+ @final
+ def done(self) -> None:
+ ...
+ class Sub(Base):
+ def done(self) -> None: # Error reported by type checker
+ ...
- Deprecated alias to :class:`collections.abc.Sequence`.
+ @final
+ class Leaf:
+ ...
+ class Other(Leaf): # Error reported by type checker
+ ...
- .. deprecated:: 3.9
- :class:`collections.abc.Sequence` now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+ There is no runtime checking of these properties. See :pep:`591` for
+ more details.
-.. class:: ValuesView(MappingView, Collection[_VT_co])
+ .. versionadded:: 3.8
- Deprecated alias to :class:`collections.abc.ValuesView`.
+ .. versionchanged:: 3.11
+ The decorator will now attempt to set a ``__final__`` attribute to ``True``
+ on the decorated object. Thus, a check like
+ ``if getattr(obj, "__final__", False)`` can be used at runtime
+ to determine whether an object ``obj`` has been marked as final.
+ If the decorated object does not support setting attributes,
+ the decorator returns the object unchanged without raising an exception.
- .. deprecated:: 3.9
- :class:`collections.abc.ValuesView` now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
-Corresponding to other types in :mod:`collections.abc`
-""""""""""""""""""""""""""""""""""""""""""""""""""""""
+.. decorator:: no_type_check
-.. class:: Iterable(Generic[T_co])
+ Decorator to indicate that annotations are not type hints.
- Deprecated alias to :class:`collections.abc.Iterable`.
+ This works as a class or function :term:`decorator`. With a class, it
+ applies recursively to all methods and classes defined in that class
+ (but not to methods defined in its superclasses or subclasses). Type
+ checkers will ignore all annotations in a function or class with this
+ decorator.
- .. deprecated:: 3.9
- :class:`collections.abc.Iterable` now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+ ``@no_type_check`` mutates the decorated object in place.
-.. class:: Iterator(Iterable[T_co])
+.. decorator:: no_type_check_decorator
- Deprecated alias to :class:`collections.abc.Iterator`.
+ Decorator to give another decorator the :func:`no_type_check` effect.
- .. deprecated:: 3.9
- :class:`collections.abc.Iterator` now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+ This wraps the decorator with something that wraps the decorated
+ function in :func:`no_type_check`.
-.. class:: Generator(Iterator[YieldType], Generic[YieldType, SendType, ReturnType])
- Deprecated alias to :class:`collections.abc.Generator`.
+.. decorator:: override
- A generator can be annotated by the generic type
- ``Generator[YieldType, SendType, ReturnType]``. For example::
+ Decorator to indicate that a method in a subclass is intended to override a
+ method or attribute in a superclass.
- def echo_round() -> Generator[int, float, str]:
- sent = yield 0
- while sent >= 0:
- sent = yield round(sent)
- return 'Done'
+ Type checkers should emit an error if a method decorated with ``@override``
+ does not, in fact, override anything.
+ This helps prevent bugs that may occur when a base class is changed without
+ an equivalent change to a child class.
- Note that unlike many other generics in the typing module, the ``SendType``
- of :class:`Generator` behaves contravariantly, not covariantly or
- invariantly.
+ For example:
- If your generator will only yield values, set the ``SendType`` and
- ``ReturnType`` to ``None``::
+ .. testcode::
- def infinite_stream(start: int) -> Generator[int, None, None]:
- while True:
- yield start
- start += 1
+ class Base:
+ def log_status(self) -> None:
+ ...
- Alternatively, annotate your generator as having a return type of
- either ``Iterable[YieldType]`` or ``Iterator[YieldType]``::
+ class Sub(Base):
+ @override
+ def log_status(self) -> None: # Okay: overrides Base.log_status
+ ...
- def infinite_stream(start: int) -> Iterator[int]:
- while True:
- yield start
- start += 1
+ @override
+ def done(self) -> None: # Error reported by type checker
+ ...
- .. deprecated:: 3.9
- :class:`collections.abc.Generator` now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+ There is no runtime checking of this property.
-.. class:: Hashable
+ The decorator will attempt to set an ``__override__`` attribute to ``True`` on
+ the decorated object. Thus, a check like
+ ``if getattr(obj, "__override__", False)`` can be used at runtime to determine
+ whether an object ``obj`` has been marked as an override. If the decorated object
+ does not support setting attributes, the decorator returns the object unchanged
+ without raising an exception.
- Deprecated alias to :class:`collections.abc.Hashable`.
+ See :pep:`698` for more details.
- .. deprecated:: 3.12
- Use :class:`collections.abc.Hashable` directly instead.
+ .. versionadded:: 3.12
-.. class:: Reversible(Iterable[T_co])
- Deprecated alias to :class:`collections.abc.Reversible`.
+.. decorator:: type_check_only
- .. deprecated:: 3.9
- :class:`collections.abc.Reversible` now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+ Decorator to mark a class or function as unavailable at runtime.
-.. class:: Sized
+ This decorator is itself not available at runtime. It is mainly
+ intended to mark classes that are defined in type stub files if
+ an implementation returns an instance of a private class::
- Deprecated alias to :class:`collections.abc.Sized`.
+ @type_check_only
+ class Response: # private or not available at runtime
+ code: int
+ def get_header(self, name: str) -> str: ...
- .. deprecated:: 3.12
- Use :class:`collections.abc.Sized` directly instead.
+ def fetch_response() -> Response: ...
-Asynchronous programming
-""""""""""""""""""""""""
+ Note that returning instances of private classes is not recommended.
+ It is usually preferable to make such classes public.
-.. class:: Coroutine(Awaitable[ReturnType], Generic[YieldType, SendType, ReturnType])
+Introspection helpers
+---------------------
- Deprecated alias to :class:`collections.abc.Coroutine`.
+.. function:: get_type_hints(obj, globalns=None, localns=None, include_extras=False)
- The variance and order of type variables
- correspond to those of :class:`Generator`, for example::
+ Return a dictionary containing type hints for a function, method, module
+ or class object.
- from collections.abc import Coroutine
- c: Coroutine[list[str], str, int] # Some coroutine defined elsewhere
- x = c.send('hi') # Inferred type of 'x' is list[str]
- async def bar() -> None:
- y = await c # Inferred type of 'y' is int
+ This is often the same as ``obj.__annotations__``. In addition,
+ forward references encoded as string literals are handled by evaluating
+ them in ``globals`` and ``locals`` namespaces. For a class ``C``, return
+ a dictionary constructed by merging all the ``__annotations__`` along
+ ``C.__mro__`` in reverse order.
- .. versionadded:: 3.5.3
+ The function recursively replaces all ``Annotated[T, ...]`` with ``T``,
+ unless ``include_extras`` is set to ``True`` (see :class:`Annotated` for
+ more information). For example:
- .. deprecated:: 3.9
- :class:`collections.abc.Coroutine` now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+ .. testcode::
-.. class:: AsyncGenerator(AsyncIterator[YieldType], Generic[YieldType, SendType])
+ class Student(NamedTuple):
+ name: Annotated[str, 'some marker']
- Deprecated alias to :class:`collections.abc.AsyncGenerator`.
+ assert get_type_hints(Student) == {'name': str}
+ assert get_type_hints(Student, include_extras=False) == {'name': str}
+ assert get_type_hints(Student, include_extras=True) == {
+ 'name': Annotated[str, 'some marker']
+ }
- An async generator can be annotated by the generic type
- ``AsyncGenerator[YieldType, SendType]``. For example::
+ .. note::
- async def echo_round() -> AsyncGenerator[int, float]:
- sent = yield 0
- while sent >= 0.0:
- rounded = await round(sent)
- sent = yield rounded
+ :func:`get_type_hints` does not work with imported
+ :ref:`type aliases <type-aliases>` that include forward references.
+ Enabling postponed evaluation of annotations (:pep:`563`) may remove
+ the need for most forward references.
- Unlike normal generators, async generators cannot return a value, so there
- is no ``ReturnType`` type parameter. As with :class:`Generator`, the
- ``SendType`` behaves contravariantly.
+ .. versionchanged:: 3.9
+ Added ``include_extras`` parameter as part of :pep:`593`.
+ See the documentation on :data:`Annotated` for more information.
- If your generator will only yield values, set the ``SendType`` to
- ``None``::
+ .. versionchanged:: 3.11
+ Previously, ``Optional[t]`` was added for function and method annotations
+ if a default value equal to ``None`` was set.
+ Now the annotation is returned unchanged.
- async def infinite_stream(start: int) -> AsyncGenerator[int, None]:
- while True:
- yield start
- start = await increment(start)
+.. function:: get_origin(tp)
- Alternatively, annotate your generator as having a return type of
- either ``AsyncIterable[YieldType]`` or ``AsyncIterator[YieldType]``::
+ Get the unsubscripted version of a type: for a typing object of the form
+ ``X[Y, Z, ...]`` return ``X``.
- async def infinite_stream(start: int) -> AsyncIterator[int]:
- while True:
- yield start
- start = await increment(start)
+ If ``X`` is a typing-module alias for a builtin or
+ :mod:`collections` class, it will be normalized to the original class.
+ If ``X`` is an instance of :class:`ParamSpecArgs` or :class:`ParamSpecKwargs`,
+ return the underlying :class:`ParamSpec`.
+ Return ``None`` for unsupported objects.
- .. versionadded:: 3.6.1
+ Examples:
- .. deprecated:: 3.9
- :class:`collections.abc.AsyncGenerator`
- now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+ .. testcode::
-.. class:: AsyncIterable(Generic[T_co])
+ assert get_origin(str) is None
+ assert get_origin(Dict[str, int]) is dict
+ assert get_origin(Union[int, str]) is Union
+ P = ParamSpec('P')
+ assert get_origin(P.args) is P
+ assert get_origin(P.kwargs) is P
- Deprecated alias to :class:`collections.abc.AsyncIterable`.
+ .. versionadded:: 3.8
- .. versionadded:: 3.5.2
+.. function:: get_args(tp)
- .. deprecated:: 3.9
- :class:`collections.abc.AsyncIterable` now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+ Get type arguments with all substitutions performed: for a typing object
+ of the form ``X[Y, Z, ...]`` return ``(Y, Z, ...)``.
-.. class:: AsyncIterator(AsyncIterable[T_co])
+ If ``X`` is a union or :class:`Literal` contained in another
+ generic type, the order of ``(Y, Z, ...)`` may be different from the order
+ of the original arguments ``[Y, Z, ...]`` due to type caching.
+ Return ``()`` for unsupported objects.
- Deprecated alias to :class:`collections.abc.AsyncIterator`.
+ Examples:
- .. versionadded:: 3.5.2
+ .. testcode::
- .. deprecated:: 3.9
- :class:`collections.abc.AsyncIterator` now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+ assert get_args(int) == ()
+ assert get_args(Dict[int, str]) == (int, str)
+ assert get_args(Union[int, str]) == (int, str)
-.. class:: Awaitable(Generic[T_co])
+ .. versionadded:: 3.8
- Deprecated alias to :class:`collections.abc.Awaitable`.
+.. function:: is_typeddict(tp)
- .. versionadded:: 3.5.2
+ Check if a type is a :class:`TypedDict`.
- .. deprecated:: 3.9
- :class:`collections.abc.Awaitable` now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+ For example:
+ .. testcode::
-Context manager types
-"""""""""""""""""""""
+ class Film(TypedDict):
+ title: str
+ year: int
-.. class:: ContextManager(Generic[T_co])
+ assert is_typeddict(Film)
+ assert not is_typeddict(list | str)
- Deprecated alias to :class:`contextlib.AbstractContextManager`.
+ # TypedDict is a factory for creating typed dicts,
+ # not a typed dict itself
+ assert not is_typeddict(TypedDict)
- .. versionadded:: 3.5.4
- .. versionadded:: 3.6.0
+ .. versionadded:: 3.10
- .. deprecated:: 3.9
- :class:`contextlib.AbstractContextManager`
- now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+.. class:: ForwardRef
-.. class:: AsyncContextManager(Generic[T_co])
+ Class used for internal typing representation of string forward references.
- Deprecated alias to :class:`contextlib.AbstractAsyncContextManager`.
+ For example, ``List["SomeClass"]`` is implicitly transformed into
+ ``List[ForwardRef("SomeClass")]``. ``ForwardRef`` should not be instantiated by
+ a user, but may be used by introspection tools.
- .. versionadded:: 3.5.4
- .. versionadded:: 3.6.2
+ .. note::
+ :pep:`585` generic types such as ``list["SomeClass"]`` will not be
+ implicitly transformed into ``list[ForwardRef("SomeClass")]`` and thus
+ will not automatically resolve to ``list[SomeClass]``.
- .. deprecated:: 3.9
- :class:`contextlib.AbstractAsyncContextManager`
- now supports subscripting (``[]``).
- See :pep:`585` and :ref:`types-genericalias`.
+ .. versionadded:: 3.7.4
-Protocols
----------
+Constant
+--------
-These protocols are decorated with :func:`runtime_checkable`.
+.. data:: TYPE_CHECKING
-.. class:: SupportsAbs
+ A special constant that is assumed to be ``True`` by 3rd party static
+ type checkers. It is ``False`` at runtime.
- An ABC with one abstract method ``__abs__`` that is covariant
- in its return type.
+ Usage::
-.. class:: SupportsBytes
+ if TYPE_CHECKING:
+ import expensive_mod
- An ABC with one abstract method ``__bytes__``.
+ def fun(arg: 'expensive_mod.SomeType') -> None:
+ local_var: expensive_mod.AnotherType = other_fun()
-.. class:: SupportsComplex
+ The first type annotation must be enclosed in quotes, making it a
+ "forward reference", to hide the ``expensive_mod`` reference from the
+ interpreter runtime. Type annotations for local variables are not
+ evaluated, so the second annotation does not need to be enclosed in quotes.
- An ABC with one abstract method ``__complex__``.
+ .. note::
-.. class:: SupportsFloat
+ If ``from __future__ import annotations`` is used,
+ annotations are not evaluated at function definition time.
+ Instead, they are stored as strings in ``__annotations__``.
+ This makes it unnecessary to use quotes around the annotation
+ (see :pep:`563`).
- An ABC with one abstract method ``__float__``.
+ .. versionadded:: 3.5.2
-.. class:: SupportsIndex
+Generic concrete collections
+----------------------------
- An ABC with one abstract method ``__index__``.
+Corresponding to built-in types
+"""""""""""""""""""""""""""""""
- .. versionadded:: 3.8
+.. class:: Dict(dict, MutableMapping[KT, VT])
-.. class:: SupportsInt
+ Deprecated alias to :class:`dict`.
- An ABC with one abstract method ``__int__``.
+ Note that to annotate arguments, it is preferred
+ to use an abstract collection type such as :class:`Mapping`
+ rather than to use :class:`dict` or :class:`!typing.Dict`.
-.. class:: SupportsRound
+ This type can be used as follows::
- An ABC with one abstract method ``__round__``
- that is covariant in its return type.
+ def count_words(text: str) -> Dict[str, int]:
+ ...
-Functions and decorators
-------------------------
+ .. deprecated:: 3.9
+ :class:`builtins.dict <dict>` now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
-.. function:: cast(typ, val)
+.. class:: List(list, MutableSequence[T])
- Cast a value to a type.
+ Deprecated alias to :class:`list`.
- This returns the value unchanged. To the type checker this
- signals that the return value has the designated type, but at
- runtime we intentionally don't check anything (we want this
- to be as fast as possible).
+ Note that to annotate arguments, it is preferred
+ to use an abstract collection type such as :class:`Sequence` or
+ :class:`Iterable` rather than to use :class:`list` or :class:`!typing.List`.
-.. function:: assert_type(val, typ, /)
+ This type may be used as follows::
- Ask a static type checker to confirm that *val* has an inferred type of *typ*.
+ def vec2[T: (int, float)](x: T, y: T) -> List[T]:
+ return [x, y]
- At runtime this does nothing: it returns the first argument unchanged with no
- checks or side effects, no matter the actual type of the argument.
+ def keep_positives[T: (int, float)](vector: Sequence[T]) -> List[T]:
+ return [item for item in vector if item > 0]
- When a static type checker encounters a call to ``assert_type()``, it
- emits an error if the value is not of the specified type::
+ .. deprecated:: 3.9
+ :class:`builtins.list <list>` now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
- def greet(name: str) -> None:
- assert_type(name, str) # OK, inferred type of `name` is `str`
- assert_type(name, int) # type checker error
+.. class:: Set(set, MutableSet[T])
- This function is useful for ensuring the type checker's understanding of a
- script is in line with the developer's intentions::
+ Deprecated alias to :class:`builtins.set <set>`.
- def complex_function(arg: object):
- # Do some complex type-narrowing logic,
- # after which we hope the inferred type will be `int`
- ...
- # Test whether the type checker correctly understands our function
- assert_type(arg, int)
+ Note that to annotate arguments, it is preferred
+ to use an abstract collection type such as :class:`AbstractSet`
+ rather than to use :class:`set` or :class:`!typing.Set`.
- .. versionadded:: 3.11
+ .. deprecated:: 3.9
+ :class:`builtins.set <set>` now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
-.. function:: assert_never(arg, /)
+.. class:: FrozenSet(frozenset, AbstractSet[T_co])
- Ask a static type checker to confirm that a line of code is unreachable.
+ Deprecated alias to :class:`builtins.frozenset <frozenset>`.
- Example::
+ .. deprecated:: 3.9
+ :class:`builtins.frozenset <frozenset>`
+ now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
- def int_or_str(arg: int | str) -> None:
- match arg:
- case int():
- print("It's an int")
- case str():
- print("It's a str")
- case _ as unreachable:
- assert_never(unreachable)
+.. note:: :data:`Tuple` is a special form.
- Here, the annotations allow the type checker to infer that the
- last case can never execute, because ``arg`` is either
- an :class:`int` or a :class:`str`, and both options are covered by
- earlier cases.
+Corresponding to types in :mod:`collections`
+""""""""""""""""""""""""""""""""""""""""""""
- If a type checker finds that a call to ``assert_never()`` is
- reachable, it will emit an error. For example, if the type annotation
- for ``arg`` was instead ``int | str | float``, the type checker would
- emit an error pointing out that ``unreachable`` is of type :class:`float`.
- For a call to ``assert_never`` to pass type checking, the inferred type of
- the argument passed in must be the bottom type, :data:`Never`, and nothing
- else.
+.. class:: DefaultDict(collections.defaultdict, MutableMapping[KT, VT])
- At runtime, this throws an exception when called.
+ Deprecated alias to :class:`collections.defaultdict`.
- .. seealso::
- `Unreachable Code and Exhaustiveness Checking
- <https://typing.readthedocs.io/en/latest/source/unreachable.html>`__ has more
- information about exhaustiveness checking with static typing.
+ .. versionadded:: 3.5.2
- .. versionadded:: 3.11
+ .. deprecated:: 3.9
+ :class:`collections.defaultdict` now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
-.. function:: reveal_type(obj, /)
+.. class:: OrderedDict(collections.OrderedDict, MutableMapping[KT, VT])
- Reveal the inferred static type of an expression.
+ Deprecated alias to :class:`collections.OrderedDict`.
- When a static type checker encounters a call to this function,
- it emits a diagnostic with the type of the argument. For example::
+ .. versionadded:: 3.7.2
- x: int = 1
- reveal_type(x) # Revealed type is "builtins.int"
+ .. deprecated:: 3.9
+ :class:`collections.OrderedDict` now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
- This can be useful when you want to debug how your type checker
- handles a particular piece of code.
+.. class:: ChainMap(collections.ChainMap, MutableMapping[KT, VT])
- The function returns its argument unchanged, which allows using
- it within an expression::
+ Deprecated alias to :class:`collections.ChainMap`.
- x = reveal_type(1) # Revealed type is "builtins.int"
+ .. versionadded:: 3.5.4
+ .. versionadded:: 3.6.1
- Most type checkers support ``reveal_type()`` anywhere, even if the
- name is not imported from ``typing``. Importing the name from
- ``typing`` allows your code to run without runtime errors and
- communicates intent more clearly.
+ .. deprecated:: 3.9
+ :class:`collections.ChainMap` now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
- At runtime, this function prints the runtime type of its argument to stderr
- and returns it unchanged::
+.. class:: Counter(collections.Counter, Dict[T, int])
- x = reveal_type(1) # prints "Runtime type is int"
- print(x) # prints "1"
+ Deprecated alias to :class:`collections.Counter`.
- .. versionadded:: 3.11
+ .. versionadded:: 3.5.4
+ .. versionadded:: 3.6.1
-.. decorator:: dataclass_transform
+ .. deprecated:: 3.9
+ :class:`collections.Counter` now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
- Decorator to mark an object as providing
- :func:`~dataclasses.dataclass`-like behavior.
+.. class:: Deque(deque, MutableSequence[T])
- ``dataclass_transform`` may be used to
- decorate a class, metaclass, or a function that is itself a decorator.
- The presence of ``@dataclass_transform()`` tells a static type checker that the
- decorated object performs runtime "magic" that
- transforms a class in a similar way to :func:`dataclasses.dataclass`.
+ Deprecated alias to :class:`collections.deque`.
- Example usage with a decorator function:
+ .. versionadded:: 3.5.4
+ .. versionadded:: 3.6.1
- .. testcode::
+ .. deprecated:: 3.9
+ :class:`collections.deque` now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
- @dataclass_transform()
- def create_model[T](cls: type[T]) -> type[T]:
- ...
- return cls
+Other concrete types
+""""""""""""""""""""
- @create_model
- class CustomerModel:
- id: int
- name: str
+.. class:: IO
+ TextIO
+ BinaryIO
- On a base class::
+ Generic type ``IO[AnyStr]`` and its subclasses ``TextIO(IO[str])``
+ and ``BinaryIO(IO[bytes])``
+ represent the types of I/O streams such as returned by
+ :func:`open`.
- @dataclass_transform()
- class ModelBase: ...
+ .. deprecated-removed:: 3.8 3.13
+ The ``typing.io`` namespace is deprecated and will be removed.
+ These types should be directly imported from ``typing`` instead.
- class CustomerModel(ModelBase):
- id: int
- name: str
+.. class:: Pattern
+ Match
- On a metaclass::
+ Deprecated aliases corresponding to the return types from
+ :func:`re.compile` and :func:`re.match`.
- @dataclass_transform()
- class ModelMeta(type): ...
+ These types (and the corresponding functions) are generic over
+ :data:`AnyStr`. ``Pattern`` can be specialised as ``Pattern[str]`` or
+ ``Pattern[bytes]``; ``Match`` can be specialised as ``Match[str]`` or
+ ``Match[bytes]``.
- class ModelBase(metaclass=ModelMeta): ...
+ .. deprecated-removed:: 3.8 3.13
+ The ``typing.re`` namespace is deprecated and will be removed.
+ These types should be directly imported from ``typing`` instead.
- class CustomerModel(ModelBase):
- id: int
- name: str
+ .. deprecated:: 3.9
+ Classes ``Pattern`` and ``Match`` from :mod:`re` now support ``[]``.
+ See :pep:`585` and :ref:`types-genericalias`.
- The ``CustomerModel`` classes defined above will
- be treated by type checkers similarly to classes created with
- :func:`@dataclasses.dataclass <dataclasses.dataclass>`.
- For example, type checkers will assume these classes have
- ``__init__`` methods that accept ``id`` and ``name``.
+.. class:: Text
- The decorated class, metaclass, or function may accept the following bool
- arguments which type checkers will assume have the same effect as they
- would have on the
- :func:`@dataclasses.dataclass<dataclasses.dataclass>` decorator: ``init``,
- ``eq``, ``order``, ``unsafe_hash``, ``frozen``, ``match_args``,
- ``kw_only``, and ``slots``. It must be possible for the value of these
- arguments (``True`` or ``False``) to be statically evaluated.
+ Deprecated alias for :class:`str`.
- The arguments to the ``dataclass_transform`` decorator can be used to
- customize the default behaviors of the decorated class, metaclass, or
- function:
+ ``Text`` is provided to supply a forward
+ compatible path for Python 2 code: in Python 2, ``Text`` is an alias for
+ ``unicode``.
- * ``eq_default`` indicates whether the ``eq`` parameter is assumed to be
- ``True`` or ``False`` if it is omitted by the caller.
- * ``order_default`` indicates whether the ``order`` parameter is
- assumed to be True or False if it is omitted by the caller.
- * ``kw_only_default`` indicates whether the ``kw_only`` parameter is
- assumed to be True or False if it is omitted by the caller.
- * ``frozen_default`` indicates whether the ``frozen`` parameter is
- assumed to be True or False if it is omitted by the caller.
+ Use ``Text`` to indicate that a value must contain a unicode string in
+ a manner that is compatible with both Python 2 and Python 3::
- .. versionadded:: 3.12
- * ``field_specifiers`` specifies a static list of supported classes
- or functions that describe fields, similar to ``dataclasses.field()``.
- * Arbitrary other keyword arguments are accepted in order to allow for
- possible future extensions.
+ def add_unicode_checkmark(text: Text) -> Text:
+ return text + u' \u2713'
- Type checkers recognize the following optional arguments on field
- specifiers:
+ .. versionadded:: 3.5.2
- * ``init`` indicates whether the field should be included in the
- synthesized ``__init__`` method. If unspecified, ``init`` defaults to
- ``True``.
- * ``default`` provides the default value for the field.
- * ``default_factory`` provides a runtime callback that returns the
- default value for the field. If neither ``default`` nor
- ``default_factory`` are specified, the field is assumed to have no
- default value and must be provided a value when the class is
- instantiated.
- * ``factory`` is an alias for ``default_factory``.
- * ``kw_only`` indicates whether the field should be marked as
- keyword-only. If ``True``, the field will be keyword-only. If
- ``False``, it will not be keyword-only. If unspecified, the value of
- the ``kw_only`` parameter on the object decorated with
- ``dataclass_transform`` will be used, or if that is unspecified, the
- value of ``kw_only_default`` on ``dataclass_transform`` will be used.
- * ``alias`` provides an alternative name for the field. This alternative
- name is used in the synthesized ``__init__`` method.
+ .. deprecated:: 3.11
+ Python 2 is no longer supported, and most type checkers also no longer
+ support type checking Python 2 code. Removal of the alias is not
+ currently planned, but users are encouraged to use
+ :class:`str` instead of ``Text``.
- At runtime, this decorator records its arguments in the
- ``__dataclass_transform__`` attribute on the decorated object.
- It has no other runtime effect.
+Abstract Base Classes
+---------------------
- See :pep:`681` for more details.
+Corresponding to collections in :mod:`collections.abc`
+""""""""""""""""""""""""""""""""""""""""""""""""""""""
- .. versionadded:: 3.11
+.. class:: AbstractSet(Collection[T_co])
-.. decorator:: overload
+ Deprecated alias to :class:`collections.abc.Set`.
- Decorator for creating overloaded functions and methods.
+ .. deprecated:: 3.9
+ :class:`collections.abc.Set` now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
- The ``@overload`` decorator allows describing functions and methods
- that support multiple different combinations of argument types. A series
- of ``@overload``-decorated definitions must be followed by exactly one
- non-``@overload``-decorated definition (for the same function/method).
+.. class:: ByteString(Sequence[int])
- ``@overload``-decorated definitions are for the benefit of the
- type checker only, since they will be overwritten by the
- non-``@overload``-decorated definition. The non-``@overload``-decorated
- definition, meanwhile, will be used at
- runtime but should be ignored by a type checker. At runtime, calling
- an ``@overload``-decorated function directly will raise
- :exc:`NotImplementedError`.
+ This type represents the types :class:`bytes`, :class:`bytearray`,
+ and :class:`memoryview` of byte sequences.
- An example of overload that gives a more
- precise type than can be expressed using a union or a type variable:
+ .. deprecated-removed:: 3.9 3.14
+ Prefer :class:`collections.abc.Buffer`, or a union like ``bytes | bytearray | memoryview``.
- .. testcode::
+.. class:: Collection(Sized, Iterable[T_co], Container[T_co])
- @overload
- def process(response: None) -> None:
- ...
- @overload
- def process(response: int) -> tuple[int, str]:
- ...
- @overload
- def process(response: bytes) -> str:
- ...
- def process(response):
- ... # actual implementation goes here
+ Deprecated alias to :class:`collections.abc.Collection`.
- See :pep:`484` for more details and comparison with other typing semantics.
+ .. versionadded:: 3.6.0
- .. versionchanged:: 3.11
- Overloaded functions can now be introspected at runtime using
- :func:`get_overloads`.
+ .. deprecated:: 3.9
+ :class:`collections.abc.Collection` now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
+.. class:: Container(Generic[T_co])
-.. function:: get_overloads(func)
+ Deprecated alias to :class:`collections.abc.Container`.
- Return a sequence of :func:`@overload <overload>`-decorated definitions for
- *func*.
+ .. deprecated:: 3.9
+ :class:`collections.abc.Container` now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
- *func* is the function object for the implementation of the
- overloaded function. For example, given the definition of ``process`` in
- the documentation for :func:`@overload <overload>`,
- ``get_overloads(process)`` will return a sequence of three function objects
- for the three defined overloads. If called on a function with no overloads,
- ``get_overloads()`` returns an empty sequence.
+.. class:: ItemsView(MappingView, AbstractSet[tuple[KT_co, VT_co]])
- ``get_overloads()`` can be used for introspecting an overloaded function at
- runtime.
+ Deprecated alias to :class:`collections.abc.ItemsView`.
- .. versionadded:: 3.11
+ .. deprecated:: 3.9
+ :class:`collections.abc.ItemsView` now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
+.. class:: KeysView(MappingView, AbstractSet[KT_co])
-.. function:: clear_overloads()
+ Deprecated alias to :class:`collections.abc.KeysView`.
- Clear all registered overloads in the internal registry.
+ .. deprecated:: 3.9
+ :class:`collections.abc.KeysView` now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
- This can be used to reclaim the memory used by the registry.
+.. class:: Mapping(Collection[KT], Generic[KT, VT_co])
- .. versionadded:: 3.11
+ Deprecated alias to :class:`collections.abc.Mapping`.
+ This type can be used as follows::
-.. decorator:: final
+ def get_position_in_index(word_list: Mapping[str, int], word: str) -> int:
+ return word_list[word]
- Decorator to indicate final methods and final classes.
+ .. deprecated:: 3.9
+ :class:`collections.abc.Mapping` now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
- Decorating a method with ``@final`` indicates to a type checker that the
- method cannot be overridden in a subclass. Decorating a class with ``@final``
- indicates that it cannot be subclassed.
+.. class:: MappingView(Sized)
- For example::
+ Deprecated alias to :class:`collections.abc.MappingView`.
- class Base:
- @final
- def done(self) -> None:
- ...
- class Sub(Base):
- def done(self) -> None: # Error reported by type checker
- ...
+ .. deprecated:: 3.9
+ :class:`collections.abc.MappingView` now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
- @final
- class Leaf:
- ...
- class Other(Leaf): # Error reported by type checker
- ...
+.. class:: MutableMapping(Mapping[KT, VT])
- There is no runtime checking of these properties. See :pep:`591` for
- more details.
+ Deprecated alias to :class:`collections.abc.MutableMapping`.
- .. versionadded:: 3.8
+ .. deprecated:: 3.9
+ :class:`collections.abc.MutableMapping`
+ now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
- .. versionchanged:: 3.11
- The decorator will now attempt to set a ``__final__`` attribute to ``True``
- on the decorated object. Thus, a check like
- ``if getattr(obj, "__final__", False)`` can be used at runtime
- to determine whether an object ``obj`` has been marked as final.
- If the decorated object does not support setting attributes,
- the decorator returns the object unchanged without raising an exception.
+.. class:: MutableSequence(Sequence[T])
+ Deprecated alias to :class:`collections.abc.MutableSequence`.
-.. decorator:: no_type_check
+ .. deprecated:: 3.9
+ :class:`collections.abc.MutableSequence`
+ now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
- Decorator to indicate that annotations are not type hints.
+.. class:: MutableSet(AbstractSet[T])
- This works as a class or function :term:`decorator`. With a class, it
- applies recursively to all methods and classes defined in that class
- (but not to methods defined in its superclasses or subclasses). Type
- checkers will ignore all annotations in a function or class with this
- decorator.
+ Deprecated alias to :class:`collections.abc.MutableSet`.
- ``@no_type_check`` mutates the decorated object in place.
+ .. deprecated:: 3.9
+ :class:`collections.abc.MutableSet` now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
-.. decorator:: no_type_check_decorator
+.. class:: Sequence(Reversible[T_co], Collection[T_co])
- Decorator to give another decorator the :func:`no_type_check` effect.
+ Deprecated alias to :class:`collections.abc.Sequence`.
- This wraps the decorator with something that wraps the decorated
- function in :func:`no_type_check`.
+ .. deprecated:: 3.9
+ :class:`collections.abc.Sequence` now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
+.. class:: ValuesView(MappingView, Collection[_VT_co])
-.. decorator:: override
+ Deprecated alias to :class:`collections.abc.ValuesView`.
- Decorator to indicate that a method in a subclass is intended to override a
- method or attribute in a superclass.
+ .. deprecated:: 3.9
+ :class:`collections.abc.ValuesView` now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
- Type checkers should emit an error if a method decorated with ``@override``
- does not, in fact, override anything.
- This helps prevent bugs that may occur when a base class is changed without
- an equivalent change to a child class.
+Corresponding to other types in :mod:`collections.abc`
+""""""""""""""""""""""""""""""""""""""""""""""""""""""
- For example:
+.. class:: Iterable(Generic[T_co])
- .. testcode::
+ Deprecated alias to :class:`collections.abc.Iterable`.
- class Base:
- def log_status(self) -> None:
- ...
+ .. deprecated:: 3.9
+ :class:`collections.abc.Iterable` now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
- class Sub(Base):
- @override
- def log_status(self) -> None: # Okay: overrides Base.log_status
- ...
+.. class:: Iterator(Iterable[T_co])
- @override
- def done(self) -> None: # Error reported by type checker
- ...
+ Deprecated alias to :class:`collections.abc.Iterator`.
- There is no runtime checking of this property.
+ .. deprecated:: 3.9
+ :class:`collections.abc.Iterator` now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
- The decorator will attempt to set an ``__override__`` attribute to ``True`` on
- the decorated object. Thus, a check like
- ``if getattr(obj, "__override__", False)`` can be used at runtime to determine
- whether an object ``obj`` has been marked as an override. If the decorated object
- does not support setting attributes, the decorator returns the object unchanged
- without raising an exception.
+.. class:: Generator(Iterator[YieldType], Generic[YieldType, SendType, ReturnType])
- See :pep:`698` for more details.
+ Deprecated alias to :class:`collections.abc.Generator`.
- .. versionadded:: 3.12
+ A generator can be annotated by the generic type
+ ``Generator[YieldType, SendType, ReturnType]``. For example::
+ def echo_round() -> Generator[int, float, str]:
+ sent = yield 0
+ while sent >= 0:
+ sent = yield round(sent)
+ return 'Done'
-.. decorator:: type_check_only
+ Note that unlike many other generics in the typing module, the ``SendType``
+ of :class:`Generator` behaves contravariantly, not covariantly or
+ invariantly.
- Decorator to mark a class or function as unavailable at runtime.
+ If your generator will only yield values, set the ``SendType`` and
+ ``ReturnType`` to ``None``::
- This decorator is itself not available at runtime. It is mainly
- intended to mark classes that are defined in type stub files if
- an implementation returns an instance of a private class::
+ def infinite_stream(start: int) -> Generator[int, None, None]:
+ while True:
+ yield start
+ start += 1
- @type_check_only
- class Response: # private or not available at runtime
- code: int
- def get_header(self, name: str) -> str: ...
+ Alternatively, annotate your generator as having a return type of
+ either ``Iterable[YieldType]`` or ``Iterator[YieldType]``::
- def fetch_response() -> Response: ...
+ def infinite_stream(start: int) -> Iterator[int]:
+ while True:
+ yield start
+ start += 1
- Note that returning instances of private classes is not recommended.
- It is usually preferable to make such classes public.
+ .. deprecated:: 3.9
+ :class:`collections.abc.Generator` now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
-Introspection helpers
----------------------
+.. class:: Hashable
-.. function:: get_type_hints(obj, globalns=None, localns=None, include_extras=False)
+ Deprecated alias to :class:`collections.abc.Hashable`.
- Return a dictionary containing type hints for a function, method, module
- or class object.
+ .. deprecated:: 3.12
+ Use :class:`collections.abc.Hashable` directly instead.
- This is often the same as ``obj.__annotations__``. In addition,
- forward references encoded as string literals are handled by evaluating
- them in ``globals`` and ``locals`` namespaces. For a class ``C``, return
- a dictionary constructed by merging all the ``__annotations__`` along
- ``C.__mro__`` in reverse order.
+.. class:: Reversible(Iterable[T_co])
- The function recursively replaces all ``Annotated[T, ...]`` with ``T``,
- unless ``include_extras`` is set to ``True`` (see :class:`Annotated` for
- more information). For example:
+ Deprecated alias to :class:`collections.abc.Reversible`.
- .. testcode::
+ .. deprecated:: 3.9
+ :class:`collections.abc.Reversible` now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
- class Student(NamedTuple):
- name: Annotated[str, 'some marker']
+.. class:: Sized
- assert get_type_hints(Student) == {'name': str}
- assert get_type_hints(Student, include_extras=False) == {'name': str}
- assert get_type_hints(Student, include_extras=True) == {
- 'name': Annotated[str, 'some marker']
- }
+ Deprecated alias to :class:`collections.abc.Sized`.
- .. note::
+ .. deprecated:: 3.12
+ Use :class:`collections.abc.Sized` directly instead.
- :func:`get_type_hints` does not work with imported
- :ref:`type aliases <type-aliases>` that include forward references.
- Enabling postponed evaluation of annotations (:pep:`563`) may remove
- the need for most forward references.
+Asynchronous programming
+""""""""""""""""""""""""
- .. versionchanged:: 3.9
- Added ``include_extras`` parameter as part of :pep:`593`.
- See the documentation on :data:`Annotated` for more information.
+.. class:: Coroutine(Awaitable[ReturnType], Generic[YieldType, SendType, ReturnType])
- .. versionchanged:: 3.11
- Previously, ``Optional[t]`` was added for function and method annotations
- if a default value equal to ``None`` was set.
- Now the annotation is returned unchanged.
+ Deprecated alias to :class:`collections.abc.Coroutine`.
-.. function:: get_origin(tp)
+ The variance and order of type variables
+ correspond to those of :class:`Generator`, for example::
- Get the unsubscripted version of a type: for a typing object of the form
- ``X[Y, Z, ...]`` return ``X``.
+ from collections.abc import Coroutine
+ c: Coroutine[list[str], str, int] # Some coroutine defined elsewhere
+ x = c.send('hi') # Inferred type of 'x' is list[str]
+ async def bar() -> None:
+ y = await c # Inferred type of 'y' is int
- If ``X`` is a typing-module alias for a builtin or
- :mod:`collections` class, it will be normalized to the original class.
- If ``X`` is an instance of :class:`ParamSpecArgs` or :class:`ParamSpecKwargs`,
- return the underlying :class:`ParamSpec`.
- Return ``None`` for unsupported objects.
+ .. versionadded:: 3.5.3
- Examples:
+ .. deprecated:: 3.9
+ :class:`collections.abc.Coroutine` now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
- .. testcode::
+.. class:: AsyncGenerator(AsyncIterator[YieldType], Generic[YieldType, SendType])
- assert get_origin(str) is None
- assert get_origin(Dict[str, int]) is dict
- assert get_origin(Union[int, str]) is Union
- P = ParamSpec('P')
- assert get_origin(P.args) is P
- assert get_origin(P.kwargs) is P
+ Deprecated alias to :class:`collections.abc.AsyncGenerator`.
- .. versionadded:: 3.8
+ An async generator can be annotated by the generic type
+ ``AsyncGenerator[YieldType, SendType]``. For example::
-.. function:: get_args(tp)
+ async def echo_round() -> AsyncGenerator[int, float]:
+ sent = yield 0
+ while sent >= 0.0:
+ rounded = await round(sent)
+ sent = yield rounded
- Get type arguments with all substitutions performed: for a typing object
- of the form ``X[Y, Z, ...]`` return ``(Y, Z, ...)``.
+ Unlike normal generators, async generators cannot return a value, so there
+ is no ``ReturnType`` type parameter. As with :class:`Generator`, the
+ ``SendType`` behaves contravariantly.
- If ``X`` is a union or :class:`Literal` contained in another
- generic type, the order of ``(Y, Z, ...)`` may be different from the order
- of the original arguments ``[Y, Z, ...]`` due to type caching.
- Return ``()`` for unsupported objects.
+ If your generator will only yield values, set the ``SendType`` to
+ ``None``::
- Examples:
+ async def infinite_stream(start: int) -> AsyncGenerator[int, None]:
+ while True:
+ yield start
+ start = await increment(start)
- .. testcode::
+ Alternatively, annotate your generator as having a return type of
+ either ``AsyncIterable[YieldType]`` or ``AsyncIterator[YieldType]``::
- assert get_args(int) == ()
- assert get_args(Dict[int, str]) == (int, str)
- assert get_args(Union[int, str]) == (int, str)
+ async def infinite_stream(start: int) -> AsyncIterator[int]:
+ while True:
+ yield start
+ start = await increment(start)
- .. versionadded:: 3.8
+ .. versionadded:: 3.6.1
-.. function:: is_typeddict(tp)
+ .. deprecated:: 3.9
+ :class:`collections.abc.AsyncGenerator`
+ now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
- Check if a type is a :class:`TypedDict`.
+.. class:: AsyncIterable(Generic[T_co])
- For example:
+ Deprecated alias to :class:`collections.abc.AsyncIterable`.
- .. testcode::
+ .. versionadded:: 3.5.2
- class Film(TypedDict):
- title: str
- year: int
+ .. deprecated:: 3.9
+ :class:`collections.abc.AsyncIterable` now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
- assert is_typeddict(Film)
- assert not is_typeddict(list | str)
+.. class:: AsyncIterator(AsyncIterable[T_co])
- # TypedDict is a factory for creating typed dicts,
- # not a typed dict itself
- assert not is_typeddict(TypedDict)
+ Deprecated alias to :class:`collections.abc.AsyncIterator`.
- .. versionadded:: 3.10
+ .. versionadded:: 3.5.2
-.. class:: ForwardRef
+ .. deprecated:: 3.9
+ :class:`collections.abc.AsyncIterator` now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
- Class used for internal typing representation of string forward references.
+.. class:: Awaitable(Generic[T_co])
- For example, ``List["SomeClass"]`` is implicitly transformed into
- ``List[ForwardRef("SomeClass")]``. ``ForwardRef`` should not be instantiated by
- a user, but may be used by introspection tools.
+ Deprecated alias to :class:`collections.abc.Awaitable`.
- .. note::
- :pep:`585` generic types such as ``list["SomeClass"]`` will not be
- implicitly transformed into ``list[ForwardRef("SomeClass")]`` and thus
- will not automatically resolve to ``list[SomeClass]``.
+ .. versionadded:: 3.5.2
- .. versionadded:: 3.7.4
+ .. deprecated:: 3.9
+ :class:`collections.abc.Awaitable` now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
-Constant
---------
-.. data:: TYPE_CHECKING
+Context manager types
+"""""""""""""""""""""
- A special constant that is assumed to be ``True`` by 3rd party static
- type checkers. It is ``False`` at runtime.
+.. class:: ContextManager(Generic[T_co])
- Usage::
+ Deprecated alias to :class:`contextlib.AbstractContextManager`.
- if TYPE_CHECKING:
- import expensive_mod
+ .. versionadded:: 3.5.4
+ .. versionadded:: 3.6.0
- def fun(arg: 'expensive_mod.SomeType') -> None:
- local_var: expensive_mod.AnotherType = other_fun()
+ .. deprecated:: 3.9
+ :class:`contextlib.AbstractContextManager`
+ now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
- The first type annotation must be enclosed in quotes, making it a
- "forward reference", to hide the ``expensive_mod`` reference from the
- interpreter runtime. Type annotations for local variables are not
- evaluated, so the second annotation does not need to be enclosed in quotes.
+.. class:: AsyncContextManager(Generic[T_co])
- .. note::
+ Deprecated alias to :class:`contextlib.AbstractAsyncContextManager`.
- If ``from __future__ import annotations`` is used,
- annotations are not evaluated at function definition time.
- Instead, they are stored as strings in ``__annotations__``.
- This makes it unnecessary to use quotes around the annotation
- (see :pep:`563`).
+ .. versionadded:: 3.5.4
+ .. versionadded:: 3.6.2
- .. versionadded:: 3.5.2
+ .. deprecated:: 3.9
+ :class:`contextlib.AbstractAsyncContextManager`
+ now supports subscripting (``[]``).
+ See :pep:`585` and :ref:`types-genericalias`.
Deprecation Timeline of Major Features
======================================
More information about the Python-checkins
mailing list