Movatterモバイル変換


[0]ホーム

URL:


Up one LevelPython Library ReferenceContentsModule IndexIndex

26.5contextlib -- Utilities forwith-statement contexts.

New in version 2.5.

This module provides utilities for common tasks involving thewith statement.

Functions provided:

contextmanager(func)
This function is a decorator that can be used to define a factoryfunction forwith statement context managers, withoutneeding to create a class or separate__enter__() and__exit__() methods.

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.

nested(mgr1[, mgr2[, ...]])
Combine multiple context managers into a single nested context manager.

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.

closing(thing)
Return a context manager that closesthing upon completion ofthe block. This is basically equivalent to:

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 line

without needing to explicitly closepage. Even if an erroroccurs,page.close() will be called when thewithblock is exited.

See Also:

PEP 0343,The "with" statement
The specification, background, and examples for the Pythonwith statement.


Up one LevelPython Library ReferenceContentsModule IndexIndex

Release 2.5.2, documentation updated on 21st February, 2008.
SeeAbout this document... for information on suggesting changes.
[8]ページ先頭

©2009-2025 Movatter.jp