Resources and non-exhausted generators

Hamish Lawson hbl at st-andrews.ac.uk
Thu May 2 07:05:33 EDT 2002


I've written a generator (slightly modified below) that returns results
from a database. Normally this is intended to be run from a for-loop
that will exhaust the produced results. However it occurred to me that
if the generator is not run to completion, then the cursor and
connection will not get properly closed. I can't see any way to do this
using a generator, and I've come to the conclusion that I must
reengineer this as an iterator with a __del__ method that can tidy up
resources (with probably also an explicit method for allowing this to be
done earlier than object destruction). Is my analysis correct?

    def fetchsome_by_status(status):
        conn = connection()
        cursor = conn.cursor()
        cursor.execute(status_select_query, (status,))
        for (student_id,) in cursor.fetchall():
            yield student_id
        cursor.close()
        conn.commit()
	conn.close()


Hamish Lawson





More information about the Python-list mailing list