try pattern for database connection with the close method

Chris Kaynor ckaynor at zindagigames.com
Fri Feb 20 21:59:03 EST 2015


On Fri, Feb 20, 2015 at 6:42 PM, Mario Figueiredo <marfig at gmail.com> wrote:
>         import sqlite3 as lite
>
>         try:
>             db = lite.connect('data.db')
>         except lite.DatabaseError:
>             raise OSError('database file corrupt or not found.')
>         else:
>             try:
>                 with db:
>                     db.execute(sql, parms)
>             except lite.IntegrityError:
>                 raise ValueError('invalid data')
>             finally:
>                 db.close()

Two comments:

You could remove the "else" statement, as it will work exactly the same
with or without it. This will reduce the indentation of the bulk of the
code by 1 level.
You MIGHT be able to remove the finally...close as the with-statement
probably does the same thing. I do not know sqlite3, however, so it may do
something different, such as committing, but that would normally be on some
transition object you get from a call.

Basically, you could probably get the same result with (untested):
try:
    db = lite.connect('data.db')
except lite.DatabaseError:
    raise OSError('database file corrupt or not found.')
try:
    with db:
        db.execute(sql, parms)
except lite.IntegrityError:
    raise ValueError('invalid data')
# You may still need the finally, depending on what the with statement does
in sqlite3 - you'd have to check the documentation.

Chris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20150220/80e28ebb/attachment.html>


More information about the Python-list mailing list