Search code examples
pythoncontextmanager

Python contextmanager() vs closing(): which is appropriate for a stream object?


In another answer here that uses contextlib to define a custom "open" function for use with with, contextmanager from contextlib is used to define a function that handles opening and streaming of data and finally closing of the stream.

In learning about this, I see there is also a closing function that seems to work similarly, with a specific focus on closing the stream when done.

I understand how the contextmanager construction presented works (explicitly closing the stream as necessary), but I wonder if it is incomplete - for correctness (and to be Pythonic), should closing be involved as well, or preferred?

Edit: that answer I referred to currently calls fh.close() - I am wondering if somehow closing ought to be involved here in some way instead of that. The documentation on contextlib didn't help me in this either-or-both question in the first place, thus this question.


Solution

  • It would be completely inappropriate to stick contextlib.closing around the context manager in that answer, for many reasons:

    1. They don't always want to close the file! That context manager is specifically designed to sometimes leave the file open. This is the entire reason that context manager was written.
    2. When they do want to close the file, the context manager already does that.
    3. Wrapping closing around the context manager would attempt to close the wrong object.

    In the case where you do always want to close the file, you usually need neither closing nor a custom context manager, because files are already context managers. Sticking a file in a with statement will close it at the end without needing any special wrappers.