Message320069
Right, the HTML example was always a bit cutesy (hence the disclaimer in the header), but it's hard to come up with a good illustrative example that isn't already a native context manager in the standard library.
Perhaps it would make sense to change the example text completely, and write something entirely abstract like:
from contextlib import contextmanager
@contextmanager
def managed_resource(*args, **kwds):
# Code to acquire resource, e.g.:
resource = acquire_resource(*args, **kwds)
try:
yield resource
finally:
# Code to release resource, e.g.:
release_resource(resource)
>>> with managed_resource(*args, **kwds) as resource:
... # Resource is released at the end of this block,
... # even if code in the block raises an exception
Then the introductory text could be updated to say something like "While many objects natively support use in with statements, sometimes a resource needs to be managed that isn't a context manager in its own right, and doesn't implement a ``close()`` method for use with ``contextlib.closing``.". |
|
Date |
User |
Action |
Args |
2018-06-20 11:23:01 | ncoghlan | set | recipients:
+ ncoghlan, petr.viktorin, serhiy.storchaka |
2018-06-20 11:23:01 | ncoghlan | set | messageid: <1529493781.77.0.56676864532.issue33468@psf.upfronthosting.co.za> |
2018-06-20 11:23:01 | ncoghlan | link | issue33468 messages |
2018-06-20 11:23:01 | ncoghlan | create | |
|