@contextlib question

N

Neal Becker

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?
 
P

Peter Otten

Neal said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top