Differences between revisions 1 and 4 (spanning 3 versions)
Revision 1 as of 2023-01-07 04:02:37
Size: 1078
Comment:
Revision 4 as of 2023-06-15 20:50:29
Size: 1318
Comment:
Deletions are marked like this. Additions are marked like this.
Line 11: Line 11:
== @ContextManager == == Decorators ==



=
== @ContextManager ===
Line 50: Line 54:
----



== See also ==

[[https://docs.python.org/3/library/contextlib.html|Python contextlib module documentation]]

[[https://pymotw.com/3/contextlib/|Python Module of the Day article for contextlib]]

Python ContextLib

contextlib is a module for working with context managers.


Decorators

@ContextManager

To convert a function that yields a value into a context manager, try:

from contextlib import contextmanager

@contextmanager
def managed_resource():
    resource = acquire_resource()
    try:
        yield resource
    finally:
        release_resource(resource)

with managed_resource() as resource:
    ...


Abstract Base Classes

The module contains two abstract base classes that can be used with isinstance or issubclass, and for type annotations

AbstractContextManager

Implements a simple __enter__() method (which returns self) and an abstract __exit__() method (which returns None).

AbstractAsyncContextManager

Implements a simple __aenter__() method (which returns self) and an abstract __aexit__() method (which returns None).


See also

Python contextlib module documentation

Python Module of the Day article for contextlib


CategoryRicottone

Python/ContextLib (last edited 2023-06-15 20:50:29 by DominicRicottone)