[Tutor] Program review
Kent Johnson
kent37 at tds.net
Tue Jan 8 00:50:53 CET 2008
Ricardo Aráoz wrote:
> looking at the simpler use, if you would have exception handling in :
>
> 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
>
>
> I don't see much difference except in the with example you have one more
> level of indentation.
The with version will close the file when the with block exits.
> Don't know about more advanced uses, I'll try to understand them when
> and if I ever need them.
Maybe 'with open(...) as ...' is more useful in contexts where you are
not so picky about exception handling.
Here is a context manager and associated decorator you might be
interested in - it traps errors and logs them :-)
http://blogmaker.googlecode.com/svn/trunk/blogmaker/util/trap_errors.py
Kent
More information about the Tutor
mailing list