8000 bpo-29679: Implement @contextlib.asynccontextmanager by JelleZijlstra · Pull Request #360 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content
8000

bpo-29679: Implement @contextlib.asynccontextmanager #360

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
May 1, 2017
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
add docs
  • Loading branch information
JelleZijlstra committed Mar 1, 2017
commit c5b8b436c0bfae160478870d7838e5c416cfb1e1
29 changes: 29 additions & 0 deletions Doc/library/contextlib.rst
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,35 @@ Functions and classes provided:
Use of :class:`ContextDecorator`.


.. decorator:: asynccontextmanager

Similar to :func:`~contextlib.contextmanager`, but works with
:term:`coroutines <coroutine>`.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"works with coroutine" isn't really descriptive. I'd rephrase to something akin to "but creates asynchronous context managers".


This function is a :term:`decorator` that can be used to define a factory
function for :keyword:`async with` statement asynchronous context managers,
without needing to create a class or separate :meth:`__aenter__` and
:meth:`__aexit__` methods.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd add that the decorator expects to be applied to asynchronous generator functions.


A simple example::

from contextlib import asynccontextmanager

@asynccontextmanager
async def get_connection():
conn = await acquire_db_connection()
try:
yield
finally:
await release_db_connection(conn)

async def get_all_users():
async with get_connection() as conn:
return conn.query('SELECT ...')

.. versionadded:: 3.7


.. function:: closing(thing)

Return a context manager that closes *thing* upon completion of the block. This
Expand Down
0