python / python/cpython

Move `ContextManager` and `AsyncContextManager` type hinting docs from `typing` to `contextlib`

Open
#123,584 0 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

docs topic-typing
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Documentation

PEP585 deprecated typing.ContextManager and typing.AsyncContextManager in favour of their contextlib counterparts. However, contextlib documentation lacks any type hinting information and does not even list generic parameters.

Several relevant changes were discussed along #123523.

Currently there's no backlink from contextlib to typing docs, hence users don't have any trivial way to discover type parameters of ContextManager (that's worse than collections.abc.Generator where such a link exists).

Similarly to #123583, I propose to add a "Type hinting" section to both of them in contextlib documentation:

.. class:: AbstractContextManager

   An :term:`abstract base class` for classes that implement
   :meth:`object.__enter__` and :meth:`object.__exit__`. A default
   implementation for :meth:`object.__enter__` is provided which returns
   ``self`` while :meth:`object.__exit__` is an abstract method which by default
   returns ``None``. See also the definition of :ref:`typecontextmanager`.

   :class:`!AbstractContextManager` can be used in type annotations and accepts
   two type parameters: ``AbstractContextManager[T_co, ExitT_co]``. 
   The first type parameter, ``T_co``, represents the type returned by
   the :meth:`~object.__enter__` method. The optional second type parameter, 
   ``ExitT_co``, which defaults to ``bool | None``, represents the type 
   returned by the :meth:`~object.__exit__` method.

   .. versionadded:: 3.6

   .. versionchanged:: 3.13
      Added the optional second type parameter, ``ExitT_co``.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the existing ContextManager and AsyncContextManager entries in the contextlib documentation, then review the related discussion in #123523 and the linked typing documentation. Add the requested Type hinting sections and backlinks for the generic parameters, covering both context manager types and their documented type arguments.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
52/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.