simple-cache icon indicating copy to clipboard operation
simple-cache copied to clipboard

File handle leaks

Open m-kostrzewa opened this issue 7 years ago • 1 comments

Hi, saw your blog post and wanted to point something out. Namely, snippets similar to this one:

https://github.com/AlexanderEllis/simple-cache/blob/master/cache_server/cacheproxy.py#L85-L93

    try:
        # Check if we have this file locally
        fin = open('cache' + filename)
        content = fin.read()
        fin.close()
        # If we have it, let's send it
        return content
    except IOError:
        return None

If read() raises an exception, close() won't be called. This leaves us dependent on Python cleaning up after us. I know CPython does this (it uses a reference counter), but it's not a rule.

A common pattern is to use with keyword to open the file. Otherwise, finally block could be used to always close the handle.

Anyways, cool blog post :)

m-kostrzewa avatar May 28 '18 05:05 m-kostrzewa

That's a great call! I've seen that pattern before, but I didn't think of it when building the cache server from the simple http server code. I'll go ahead and add that in.

Thanks!

AlexanderEllis avatar Jun 04 '18 18:06 AlexanderEllis