Dead Man’s Last Wish: the atexit module
The atexit module defines a single function to register cleanup functions. Functions thus registered are automatically executed upon normal interpreter termination.
I tried today SQLite and I noticed that commit() must be called explicitly, it’s not called automatically when the program terminates. I thought that when the connection object goes out of scope, it calls commit and close, but no…
So here is my solution (extract):
SQLITE_DB = None conn = None def init(sqlite_db): """Initialize the DB.""" global SQLITE_DB, conn atexit.register(commit_and_close) # HERE SQLITE_DB = sqlite_db if not os.path.exists(SQLITE_DB): create_db() if not conn: conn = sqlite3.connect(SQLITE_DB) def commit_and_close(): """Commit and close DB connection.""" if conn: conn.commit() conn.close()
You can find the full source code here.