with open('com1', 'r') as f:

Terry Reedy tjreedy at udel.edu
Tue Apr 7 23:51:11 CEST 2009

Lawrence D'Oliveiro wrote:
> In message <mailman.3438.1239062418.11746.python-list at python.org>, Delaney, 
> Timothy (Tim) wrote:
>> Lawrence D'Oliveiro wrote:
>>> In message <mailman.3332.1238914117.11746.python-list at python.org>,
>>> Terry Reedy wrote:
>>>> Lawrence D'Oliveiro wrote:
>>>>> All Python objects are reference-counted.
>>>> Nope.  Only in CPython, and even that could change.
>>> Why should it?
>> Because Guido has said it might some time in the future.
> It's still a matter of efficiency, not correctness.

If one wants to *ensure* that the file is closed as soon as it is not 
needed (perhaps because it is one of 100s of files being processed), in 
all versions of Python current and future, then 'with ...' is an easy 
way to do it, while 'open ...' is incorrect.

If one *does not care* about quick closure (perhaps because it is one of 
only a few files and they are all just read or the program will soon end 
(and cause closure anyway), then 'open ...' is both easy and correct.

The latter has typically applied to my work, but I know that is not true 
for everyone.

>>>>>> Once the file object becomes
>>>>> inaccessible, it is automatically closed. Simple.
>>>> Even in CPython, that would not be true now is the object became
>>>> involved in or became a dependent of a reference cycle.
>>> And how exactly would that happen with a file object?
>> Create a cycle of objects, and have one of them reference a file object.
> Which was not what was happening in the actual situation at hand.

For the simple toy example, sure.  But in general, anything could happen 
after a file is opened within 'with' block or any other chunk of code.


More information about the Python-list mailing list