pythonic way to free resources

Chirayu thephoenix235 at gmx.net
Wed Aug 14 21:11:52 CEST 2002


The NullObject class is just great. Nesting try blocks is....yes....a 
little messy....but works well enough. Thanks for the help. I'll follow 
this technique.

I did'nt know about automatic cleanup (for file objects) without calling 
__del__. It helps quite a bit.


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

>     Chirayu> It seems I cant use try/except/finally. Its either try/finally
>     Chirayu> or try/except or nesting to get the desired effect.
>
>Yup.
>
>     Chirayu> But even if it were possible, its tough to write good stuff in
>     Chirayu> the finally clause - if u're dealing with more than 1 resource.
>
>Just nest the try/finally statements or initialize the variables to None
>before the block.
>
>     Chirayu> try:
>     Chirayu>     f1 = file (.......)
>     Chirayu>     f2 = file (.......)
>     Chirayu>     # some other processing - may throw
>     Chirayu>     f3 = file (.......)
>     Chirayu>     # more processing - may throw
>     Chirayu> finally:
>     Chirayu>     # which ones of f1, f2, f3 do i close?
>
>     Chirayu> I'm using files as a placeholder for a resource in general.
>     Chirayu> Any of the above lines may throw. Sorry, any of the above lines
>     Chirayu> may raise an exception.
>
>Also, note that you should initialize the object before the try:
>
>     f1 = file(...)
>     try:
>         # do stuff with f1
>         f2 = file(...)
>         try:
>             # do stuff with f2
>         finally:
>             f2.close()
>     finally:
>         f1.close()
>
>Sort of messy, but effective.
>
>     Chirayu> I'm currently using
>     Chirayu> f1,f2,f3 = None
>     Chirayu> and then checking for None in the finally block. Not a nice
>     Chirayu> solution.
>
>How about
>
>     class NullObject:
>         def close(self):
>             pass
>
>     f1 = f2 = f3 = NullObject()
>     try:
>         f1 = file(...)
>         f2 = file(...)
>         f3 = file(...)
>         ...
>     finally:
>         f1.close()
>         f2.close()
>         f3.close()
>
>     Chirayu> does not list a '__del__'. So i assume that even if the ref
>     Chirayu> count goes to 0, the file wont be closed. (Assuming CPython of
>     Chirayu> course.)
>
>You assume wrong. ;-)  __del__ is a user-defined method.  File objects are
>closed automatically when their ref counts reach zero.
>
>--
>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






More information about the Python-list mailing list