[Tutor] sqlite: don't understand a code snippet

David ldl08 at gmx.net
Sat Jul 25 19:17:41 CEST 2009

Dear tutors,

I am trying to teach myself the way Python's works with databases.
I decided to start with SQLite, and am looking at Summerfield's
'Programming in Python 3'.
I got a code snippet that I don't fully understand (the comments are mine):

def get_and_set_director(db, director):
    # try to fetch existing director ID from db
    director_id = get_director_id(db, director)
    # if director ID was found in db, return ID
    if director_id is not None:
    return director_id
cursor = db.cursor()
# insert new director record
cursor.execute("INSERT INTO directors (name) VALUES (?)",
# retrieve and return new director ID from db
return get_director_id(db, director)

Here is what I think is going on:

The function get_and_set_director() gets the director ID from the db
by calling the function get_director-id() and returns its value.

If the director ID is not in the db then, from outside the
get_and_set_director() function, the ID gets inserted to the db via
the commit() method. Finally, the director ID is returned (from the db)
by once again calling the get_director_id() function.

Question: where does a new the director ID come from?

Thanks for your directions!


More information about the Tutor mailing list