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("%s>" % 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) ... -