@contextlib question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Neal Becker

    @contextlib question

    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.conte xtmanager 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?

  • Peter Otten

    #2
    Re: @contextlib question

    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.conte xtmanager 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 <cleanupwhere as

    with tag("yadda"):
        1/0

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

    Peter

    Comment

    Working...