try...except...finally problem in Python 2.5

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Wed Feb 14 20:59:03 EST 2007


On Wed, 14 Feb 2007 12:09:34 -0800, Paul Rubin wrote:

> "redawgts" <redawgts at gmail.com> writes:
>>         try:
>>             f = file(self.filename, 'rb') ...
>> Can someone tell me what's wrong with the code? 
> 
> Various people have explained the error: if the file open attempt
> fails, f is never assigned.  Doing it the right way (i.e. handling the
> potential exceptions separately) with try/except statements is messy,
> so it's worth mentioning that 2.5 adds the new "with" statement to
> clean this up.  I'm not using 2.5 myself yet so maybe someone will
> have to correct me, but I think you'd write:
> 
>     from __future__ import with_statement
> 
>     self.isDataLoaded = False
>     with open(self.filename, 'rb') as f:
>         f.seek(DATA_OFFSET)
>         self.__data = f.read(DATA_SIZE)
>         self.isDataLoaded = True
> 
> and that should handle everything, closing the file automatically.


I don't have Python 2.5 here to experiment, but how is that different from
this?


self.isDataLoaded = False
try:
    f = open(self.filename, 'rb')
    f.seek(DATA_OFFSET)
    self.__data = f.read(DATA_SIZE)
    self.isDataLoaded = True
except:
    pass
else:
    pass

(apart from being four lines shorter)



-- 
Steven D'Aprano 




More information about the Python-list mailing list