Question

I'm currently writing a script that uses sqlite3. I recently ran into a problem with the database being in use by another program due to my code exiting early with an error.

With similar problems, one usually uses:

conn = sqlite3.connect(...)
try:
    #Do stuff
finally:
    conn.close()

But this won't work in my case. In a nutshell, this is my code:

import sqlite3

class Thingamadoodle:
    def __init__(self, ...):
        self.conn = sqlite3.connect(...)
        ...

    #Methods and stuff

    def __del__(self):
        self.conn.close()

poop = Thingamadoodle(...)
poop.do_stuff(...)
poop.throw_irritating_exception_that_you_cant_track_down(irritatingness=11)

After the program exits without closing the connection, I get errors when I try to modify the database.

Is there a way to safely close the connection, even on an unclean exit?

Was it helpful?

Solution

To be honest, i don't understand the question much, but why not just wrap the poop.do_stuff() in a try/except block?

try:
    poop.do_stuff()
except:
    poop.__del__()
finally:
    poop.__del__()

Or to be a bit cleaner, use a context manager:

class Thingamadoodle:
    def __init__(self, ...):
        ...

    #Methods and stuff
    def __enter__(self):
        self.conn = sqlite3.connect(...)
        return self
    def __exit__(self, errorType, errorValue, errorTrace):
        self.conn.close()

And just execute it as:

with Thingmadoodle(args) as poop:
    #do things

After all the code is done, or after an exception happened in the statement, __exit__ will be executed, and you can safely close it.

Hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top