By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,587 Members | 1,666 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,587 IT Pros & Developers. It's quick & easy.

@contextlib question

P: n/a
http://www.python.org/doc/2.5.2/lib/...ontextlib.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?

Nov 7 '08 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Neal Becker wrote:
http://www.python.org/doc/2.5.2/lib/...ontextlib.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 <cleanupwhereas

with tag("yadda"):
* * 1/0

will print <yaddabut not </yadda>. (Both will raise the ZeroDivisionError)

Peter

Nov 7 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.