pythonic way to free resources

Skip Montanaro skip at pobox.com
Wed Aug 14 14:30:44 EDT 2002


    Chirayu> I'm from the C++ world. I'm used to writing code like this.

    Chirayu> // some block of code - could be try/catch, func body, loop body, etc
    Chirayu> {
    Chirayu>      ifstream inp (inFIle, ios::read | ios::binary)
    Chirayu>      ofstream out (outFIle, ios::write | ios::binary)
    Chirayu>      ......
    Chirayu>      use inp and out
    Chirayu>      .......
    Chirayu> }
    ...
    Chirayu> What is the python idiom to do something like this?

In Python, you'd use try/finally.  Something like

    dbconn = self.db_pool.get()
    try:
        c = dbconn.cursor()
        c.execute("select ...")
        for row in c.fetchall():
            pass
    finally:
        self.db_pool.put(dbconn)

In the case of local file objects you don't need to use try/finally however.
When a name goes out of scope the reference count of the object who which it
refers is decremented, and if it reaches zero the object is reclaimed.  That
would hold true in this case if inFIle was opened successfully but outFIle
was not.  (Interesting studly caps by the way... ;-)

-- 
Skip Montanaro
skip at pobox.com
consulting: http://manatee.mojam.com/~skip/resume.html




More information about the Python-list mailing list