pythonic way to free resources

Chirayu thephoenix235 at gmx.net
Wed Aug 14 20:47:59 CEST 2002


Hi,

It seems I cant use try/except/finally. Its either try/finally or 
try/except or nesting to get the desired effect. But even if it were 
possible, its tough to write good stuff in the finally clause - if u're 
dealing with more than 1 resource.

try:
    f1 = file (.......)
    f2 = file (.......)
    # some other processing - may throw
    f3 = file (.......)
    # more processing - may throw
finally:
    # which ones of f1, f2, f3 do i close?

I'm using files as a placeholder for a resource in general.  Any of the 
above lines may throw. Sorry, any of the above lines may raise an exception.

I'm currently using
f1,f2,f3 = None
and then checking for None in the finally block. Not a nice solution.

also,

f=file ('c:/config.sys','r')
print dir(f)

does not list a '__del__'. So i assume that even if the ref count goes to 
0, the file wont be closed. (Assuming CPython of course.)

ps: Studly caps a typo :D

ciao,
Chirayu.

At 01:30 PM 8/14/02 -0500, Skip Montanaro wrote:

>     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

Only those who will risk going too far
can possibly find out how far one can go.
- T.S. Eliot

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20020815/c8d4e76b/attachment.html>


More information about the Python-list mailing list