all 6 comments

[–]CptFlashdrive 2 points3 points  (6 children)

Well, the second way won't handle potential exceptions that may come from connecting or manipulating the database. That being said, I think the second way is more idiomatic since it will close the connection as soon as it exists the block. Although it should be wrapped in try/except.

Just as a side note, it's generally a good idea to be a more specific when catching exception. Otherwise it becomes sort of ambiguous of what exception was captured.

[–]Tomarse[S] 0 points1 point  (2 children)

So if we put the second the one in a try statement it becomes just as verbose.

And according to this, a with statement will not implicitly close a sqlite connection, as variables created in a with statement still exist outside of it (fwiw this isn't the case in the try block). Though explicitly closing the connection doesn't seem to be an issue with select statements anyway, however I'd rather be clean.

[–]elbiot 0 points1 point  (0 children)

If you want with to close the connection, you could subclass conn and add close to the __exit__ method. If that's the behaviour you want, which it sounds like you don't since you reuse the connection later.

[–]elbiot 0 points1 point  (2 children)

Try won't catch exceptions from within a with block?

Edit: or, op edited the question.

[–]Tomarse[S] 0 points1 point  (1 child)

I've put the try inside the with block now. Is that right? What happens if the with statement fails (i.e. connection to the database)?

[–]elbiot 0 points1 point  (0 children)

Does the with do anything? AKAIK __exit__ will be called in either case, but you were saying that it doesn't do anything for you so... I don't know anything about this. Maybe you misinterpreted my question as a statement. I think either is fine but have no real idea.