Index: Doc/library/contextlib.rst =================================================================== --- Doc/library/contextlib.rst (revision 82949) +++ Doc/library/contextlib.rst (working copy) @@ -57,6 +57,7 @@ .. versionchanged:: 3.2 Use of :class:`ContextDecorator`. + .. function:: closing(thing) Return a context manager that closes *thing* upon completion of the block. This @@ -91,8 +92,11 @@ Context managers inheriting from ``ContextDecorator`` have to implement ``__enter__`` and ``__exit__`` as normal. ``__exit__`` retains its optional exception handling even when used as a decorator. + + ``ContextDecorator`` is used by :func:`contextmanager`, so you get this + functionality automatically. - Example:: + Example of ``ContextDecorator``:: from contextlib import ContextDecorator @@ -121,6 +125,21 @@ The bit in the middle Finishing + This change is just syntactic sugar for any construct of the following form:: + + def f(): + with cm(): + # Do stuff + + ``ContextDecorator`` lets you instead write:: + + @cm() + def f(): + # Do stuff + + It makes it clear that the cm applies to the whole function, rather than + just a piece of it (and saving an indentation level is nice, too). + Existing context managers that already have a base class can be extended by using ``ContextDecorator`` as a mixin class::