contextlib.asynccontextmanager
Prev: contextlib.aclosing | Up: contextlib | Next: contextlib.AsyncExitStack
Rel: contextlib.AbstractAsyncContextManager, contextlib.AbstractContextManager, contextlib.aclosing, contextlib.AsyncExitStack
Ref: docs.python.org — contextlib.asynccontextmanager
Tags: #public #python3 #stdlib #contextlib
Import
import contextlib
from contextlib import asynccontextmanager
Signature & Overview
contextlib.asynccontextmanager(func)
@asynccontextmanager decorator.
Usage
import asyncio
from contextlib import asynccontextmanager
@asynccontextmanager
async def opened(name: str):
yield f"conn:{name}"
async def main():
async with opened("db") as c:
assert c == "conn:db"
asyncio.run(main())
Gotchas
- Always wrap
yieldintry ... finally:for cleanup: If theasync withbody raises an exception, it is thrown back into theyieldline. - Must yield exactly once: Yielding zero or multiple times raises
RuntimeError.
REPL Inspect
from contextlib import asynccontextmanager
help(asynccontextmanager)
Linked from
- tuts/python3/stdlib_module/contextlib
- tuts/python3/stdlib_module/contextlib/AbstractAsyncContextManager
- tuts/python3/stdlib_module/contextlib/AbstractContextManager
- tuts/python3/stdlib_module/contextlib/aclosing
- tuts/python3/stdlib_module/contextlib/AsyncExitStack
- tuts/python3/stdlib_module/contextlib/chdir
- tuts/python3/stdlib_module/contextlib/closing
- tuts/python3/stdlib_module/contextlib/ContextDecorator
- tuts/python3/stdlib_module/contextlib/contextmanager
- tuts/python3/stdlib_module/contextlib/ExitStack
- tuts/python3/stdlib_module/contextlib/nullcontext
- tuts/python3/stdlib_module/contextlib/redirect_stderr
- tuts/python3/stdlib_module/contextlib/redirect_stdout
- tuts/python3/stdlib_module/contextlib/suppress
Related notes
- tuts/python3/stdlib_module/contextlib/AbstractAsyncContextManager Linked here; links to this page; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/AbstractContextManager Linked here; links to this page; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/aclosing Linked here; links to this page; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/AsyncExitStack Linked here; links to this page; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/contextlib/chdir links to this page; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/closing links to this page; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/ContextDecorator links to this page; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/contextmanager links to this page; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/ExitStack links to this page; shared tags: #contextlib, #stdlib