@contextlib question
Peter Otten
__peter__ at web.de
Fri Nov 7 14:45:02 EST 2008
Neal Becker wrote:
> http://www.python.org/doc/2.5.2/lib/module-contextlib.html has this
> example: from contextlib import contextmanager
>
> @contextmanager
> def tag(name):
> print "<%s>" % name
> yield
> print "</%s>" % name
>
> contexlib.contextmanager doc string (2.5.1) says:
> Typical usage:
>
> @contextmanager
> def some_generator(<arguments>):
> <setup>
> try:
> yield <value>
> finally:
> <cleanup>
>
> Should I use the 'try', and 'finally' as in the 2nd example, or should I
> use the first example? Does it matter?
>
These examples are basically the same. try...finally does what it always
does -- ensure that the cleanup code is executed even if an exception
occurs in the try block. So
with some_generator(...):
1/0
will execute <cleanup> whereas
with tag("yadda"):
1/0
will print <yadda> but not </yadda>. (Both will raise the ZeroDivisionError)
Peter
More information about the Python-list
mailing list