diff -r 4e7ea18f171a Doc/library/contextlib.rst
--- a/Doc/library/contextlib.rst Fri Dec 09 17:15:43 2016 +0100
+++ b/Doc/library/contextlib.rst Mon Jan 02 20:05:40 2017 +0100
@@ -36,22 +36,23 @@
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 (this is not recommended as a real way of generating HTML!):
- from contextlib import contextmanager
+ .. doctest::
- @contextmanager
- def tag(name):
- print("<%s>" % name)
- yield
- print("%s>" % name)
-
- >>> with tag("h1"):
- ... print("foo")
- ...
-
- foo
-
+ >>> from contextlib import contextmanager
+ >>> @contextmanager
+ ... def tag(name):
+ ... print("<%s>" % name)
+ ... yield
+ ... print("<%s>" % name)
+ ...
+ >>> with tag("h1"):
+ ... print("foo")
+ ...
+
+ foo
+
The function being decorated must return a :term:`generator`-iterator when
called. This iterator must yield exactly one value, which will be bound to
@@ -205,34 +206,34 @@
``ContextDecorator`` is used by :func:`contextmanager`, so you get this
functionality automatically.
- Example of ``ContextDecorator``::
+ Example of ``ContextDecorator``:
- from contextlib import ContextDecorator
+ .. doctest::
- class mycontext(ContextDecorator):
- def __enter__(self):
- print('Starting')
- return self
+ >>> from contextlib import ContextDecorator
+ >>> class mycontext(ContextDecorator):
+ ... def __enter__(self):
+ ... print('Starting')
+ ... return self
+ ... def __exit__(self, *exc):
+ ... print('Finishing')
+ ... return False
+ ...
+ >>> @mycontext()
+ ... def function():
+ ... print('The bit in the middle')
+ ...
+ >>> function()
+ Starting
+ The bit in the middle
+ Finishing
- def __exit__(self, *exc):
- print('Finishing')
- return False
-
- >>> @mycontext()
- ... def function():
- ... print('The bit in the middle')
- ...
- >>> function()
- Starting
- The bit in the middle
- Finishing
-
- >>> with mycontext():
- ... print('The bit in the middle')
- ...
- Starting
- The bit in the middle
- Finishing
+ >>> with mycontext():
+ ... print('The bit in the middle')
+ ...
+ Starting
+ The bit in the middle
+ Finishing
This change is just syntactic sugar for any construct of the following form::