Search code examples
pythonpython-3.xcontextmanagerresource-management

Is it possible to close a file directly after a function call


I have the following line:

service = discovery.build('sheets', 'v4', credentials=pickle.load(open('google_sheets_token.pickle', 'rb')))

And while it's trivial to implement something like this:

with open('google_sheets_token.pickle', 'rb') as f:
    service = discovery.build('sheets', 'v4', credentials=pickle.load(f)) 

I was wondering if it's possible to automatically close files after being passed to a function?


Solution

  • Nope. In the CPython reference interpreter, if no reference cycles occur (they're easier to trigger than you might think, so don't assume anything), the first example will automatically close the file as the reference count drops to 0 immediately after the function in question returns (assuming it didn't save off a reference). But it's not something to rely on; use a with statement if you want guarantees on CPython, and even a hope of the correct behavior on non-reference counted alternate interpreters like PyPy, Jython, IronPython, etc. Without with management, the file will probably eventually close, but there's no guarantees on when it will happen (or even if; it's best effort, not an ironclad guarantee).