pythonic way to free resources

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


    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




More information about the Python-list mailing list