Aaron S
Aaron S

Reputation: 5323

Is calling `close()` redundant if file opened with `with` statement

Assume I have the following code:

with open('somefile.txt') as my_file:
    # some processing
    my_file.close()

Is my_file.close() above redundant?

Upvotes: 3

Views: 163

Answers (4)

Kruupös
Kruupös

Reputation: 5484

Yes it is; Beside, it is not guarranty that your close() will always be executed. (for instance if an Exception occurs).

with open('somefile.txt') as my_file:
    1/0 # raise Exception
    my_file.close() # Your close() call is never going to be called

But the __exit__() function of the with statement is always executed because it follows the try...except...finally pattern.

The with statement is used to wrap the execution of a block with methods defined by a context manager (see section With Statement Context Managers). This allows common try...except...finally usage patterns to be encapsulated for convenient reuse.

The context manager’s __exit__() method is invoked. If an exception caused the suite to be exited, its type, value, and traceback are passed as arguments to __exit__()

You can check that the file have been close right after the with statement using closed

>>> with open('somefile.txt') as f:
...     pass
>>> f.closed
# True

Source for my answer:

Upvotes: 1

Ofer Sadan
Ofer Sadan

Reputation: 11942

yes, the with statement takes care of that

as you can see in the documentation:

The context manager’s __exit__() method is invoked. If an exception caused the suite to be exited, its type, value, and traceback are passed as arguments to __exit__().

In the case of files, the __exit__() method will close the file

Upvotes: 0

Vibhutha Kumarage
Vibhutha Kumarage

Reputation: 1399

The with statement creates a runtime context.Python creates the stream object of the file and tells it that it is entering a runtime context. When the with code block is completed, Python tells the stream object that it is exiting the runtime context,and the stream object calls its own close() method.

Upvotes: 1

Daniel Pryden
Daniel Pryden

Reputation: 60997

Yes. Exiting the with block will close the file.

However, that is not necessarily true for objects that are not files. Normally, exiting the context should trigger an operation conceptually equivalent to "close", but in fact __exit__ can be overloaded to execute any code the object wishes.

Upvotes: 2

Related Questions