Home > python > Dead Man’s Last Wish: the atexit module

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):

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):
    if not conn:
        conn = sqlite3.connect(SQLITE_DB)

def commit_and_close():
    """Commit and close DB connection."""
    if conn:

You can find the full source code here.

About these ads
Categories: python Tags: ,
  1. No comments yet.
  1. No trackbacks yet.
You must be logged in to post a comment.

Get every new post delivered to your Inbox.

Join 61 other followers

%d bloggers like this: