contextlib.contextmanager and try/finally

johannh at gmail.com johannh at gmail.com
Wed Jan 11 10:45:15 EST 2012


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



More information about the Python-list mailing list