diff --git a/Doc/library/contextlib.rst b/Doc/library/contextlib.rst --- a/Doc/library/contextlib.rst +++ b/Doc/library/contextlib.rst @@ -31,32 +31,38 @@ Functions and classes provided: .. decorator:: contextmanager This function is a :term:`decorator` that can be used to define a factory function for :keyword:`with` statement context managers, without needing to create a class or separate :meth:`__enter__` and :meth:`__exit__` methods. - A simple example (this is not recommended as a real way of generating HTML!):: + A simple example:: from contextlib import contextmanager @contextmanager - def tag(name): - print("<%s>" % name) - yield - print("" % name) + def swap_attr(obj, attr, val): + old_val = getattr(obj, attr) + setattr(obj, attr, val) + try: + yield + finally: + setattr(obj, attr, old_val) - >>> with tag("h1"): - ... print("foo") + Example usage of the ``swap_attr`` context manager:: + + >>> import string + >>> with swap_attr(string, 'ascii_letters', 'spameggs'): + ... print(string.ascii_letters) ... -

- foo -

+ spameggs + >>> print(string.ascii_letters) + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ The function being decorated must return a :term:`generator`-iterator when called. This iterator must yield exactly one value, which will be bound to the targets in the :keyword:`with` statement's :keyword:`as` clause, if any. At the point where the generator yields, the block nested in the :keyword:`with` statement is executed. The generator is then resumed after the block is exited. If an unhandled exception occurs in the block, it is reraised inside the