New in version 2.5.
This module provides utilities for common tasks involving thewith statement.
Functions provided:
| func) |
A simple example (this is not recommended as a real way ofgenerating HTML!):
from __future__ import with_statementfrom contextlib import contextmanager@contextmanagerdef tag(name): print "<%s>" % name yield print "</%s>" % name>>> with tag("h1"):... print "foo"...<h1>foo</h1>The function being decorated must return a generator-iterator whencalled. This iterator must yield exactly one value, which will bebound to the targets in thewith statement'sasclause, if any.
At the point where the generator yields, the block nested in thewith statement is executed. The generator is then resumedafter the block is exited. If an unhandled exception occurs in theblock, it is reraised inside the generator at the point where the yieldoccurred. Thus, you can use atry...except...finally statement to trapthe error (if any), or ensure that some cleanup takes place. If anexception is trapped merely in order to log it or to perform someaction (rather than to suppress it entirely), the generator mustreraise that exception. Otherwise the generator context manager willindicate to thewith statement that the exception has beenhandled, and execution will resume with the statement immediatelyfollowing thewith statement.
| mgr1[, mgr2[, ...]]) |
Code like this:
from contextlib import nestedwith nested(A, B, C) as (X, Y, Z): do_something()
is equivalent to this:
with A as X: with B as Y: with C as Z: do_something()
Note that if the__exit__() method of one of the nestedcontext managers indicates an exception should be suppressed, noexception information will be passed to any remaining outer contextmanagers. Similarly, if the__exit__() method of one of thenested managers raises an exception, any previous exception state willbe lost; the new exception will be passed to the__exit__() methods of any remaining outer context managers.In general,__exit__() methods should avoid raisingexceptions, and in particular they should not re-raise apassed-in exception.
| thing) |
from contextlib import contextmanager@contextmanagerdef closing(thing): try: yield thing finally: thing.close()
And lets you write code like this:
from __future__ import with_statementfrom contextlib import closingimport urllibwith closing(urllib.urlopen('http://www.python.org')) as page: for line in page: print linewithout needing to explicitly closepage. Even if an erroroccurs,page.close() will be called when thewithblock is exited.
See Also: