Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #18834

contextlib.contextmanager and try/finally

From johannh@gmail.com
Newsgroups comp.lang.python
Subject contextlib.contextmanager and try/finally
Date 2012-01-11 07:45 -0800
Organization http://groups.google.com
Message-ID <10841855.1646.1326296715536.JavaMail.geo-discussion-forums@yqiz15> (permalink)

Show all headers | View raw


I'm trying to write a context manager to handle database connections, under the principle that I should not rely on CPython's reference-counting semantics to clean up scarce resources, like connections.

I wrote:

@contexlib.contextmanager
def ensure_connection(con=None):
    con_created = False
    if con is None:
        con_created, con = True, make_connection()
    try:
        yield con
    finally:
        if con_created:
            con.close()

However, then I read the following paragraph from PEP-343:

    Note that we're not guaranteeing that the finally-clause is
    executed immediately after the generator object becomes unused,
    even though this is how it will work in CPython.  This is similar
    to auto-closing files: while a reference-counting implementation
    like CPython deallocates an object as soon as the last reference
    to it goes away, implementations that use other GC algorithms do
    not make the same guarantee.  This applies to Jython, IronPython,
    and probably to Python running on Parrot.

That suggests that I cannot rely on the contextlib.contextmanager decorator to ensure that the connection is closed and would have to write my own object with __enter__ and __exit__ methods to guarantee this.

Is this understanding accurate?  If so, could someone illustrate why this is so? 

Thanks,
Johann

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

contextlib.contextmanager and try/finally johannh@gmail.com - 2012-01-11 07:45 -0800
  Re: contextlib.contextmanager and try/finally Neil Cerutti <neilc@norwich.edu> - 2012-01-11 16:46 +0000
  Re: contextlib.contextmanager and try/finally Robert Kern <robert.kern@gmail.com> - 2012-01-11 17:14 +0000
  Re: contextlib.contextmanager and try/finally Ian Kelly <ian.g.kelly@gmail.com> - 2012-01-11 10:20 -0700
    Re: contextlib.contextmanager and try/finally johannh@gmail.com - 2012-01-11 09:30 -0800
    Re: contextlib.contextmanager and try/finally johannh@gmail.com - 2012-01-11 09:30 -0800
  RE: contextlib.contextmanager and try/finally "Prasad, Ramit" <ramit.prasad@jpmorgan.com> - 2012-01-31 21:07 +0000
  RE: contextlib.contextmanager and try/finally Peter Otten <__peter__@web.de> - 2012-01-31 23:02 +0100
  Re: contextlib.contextmanager and try/finally Ian Kelly <ian.g.kelly@gmail.com> - 2012-01-31 15:09 -0700
    Re: contextlib.contextmanager and try/finally Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-02-01 02:15 +0000

csiph-web