[Tutor] Program review
Ricardo Aráoz
ricaraoz at gmail.com
Tue Jan 8 01:46:40 CET 2008
Torsten Marek wrote:
>> try :
>> with open('/etc/passwd', 'r') as f:
>> for line in f:
>> print line
>> ... more processing code ...
>> except ExceptionsOnOpening :
>> ... exception handling
>> except :
>> ... exceptions inside the for
>>
>>
>>
>> Whereas traditionally :
>>
>> try :
>> f = open('/etc/passwd', 'r')
>> for line in f:
>> print line
>> ... more processing code ...
>> except ExceptionsOnOpening :
>> ... exception handling
>> except :
>> ... exceptions inside the for
>
> Hi Ricardo,
>
> don't forget the "f.close()" call after the for loop, in a finally block
> [0]. Context managers are all about generalizing non-adjacent parts of
> setup and teardown code
>
> Actually, the fact that you forgot the close call is an argument for
> using the context manager;)
>
Hi Torsten,
or an argument for going to sleep at 10 pm after a hard day's work and
38º Centigrades temperature. ;c)
More information about the Tutor
mailing list