On Fri, Feb 20, 2015 at 6:42 PM, Mario Figueiredo <[email protected]> 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
--
https://mail.python.org/mailman/listinfo/python-list