[Python-ideas] with statement vs. try...except...finally

Nick Coghlan ncoghlan at gmail.com
Wed Jun 3 08:35:35 CEST 2009


Gerald Britton wrote:
> Fine so far, but what if I want to be more granular?  e.g. with "try...except":
> 
> try:
>     f = open('foo')
> except IOError:
>     line = "can't open"
> 
> try:
>     line = f.readline()
> except IOError:
>     line = "can't read"
> 
> try:
>     f.close()
> except IOError:
>     line = "can't close"
> 
> I can't see how to replace the above try-triplet with a "with"
> encapsulation.

The with statement is designed to simplify certain common use cases of
the try statement. That simplification comes at the cost of reduced
flexibility.

That's OK though: when you need the extra fine-grained control then the
original try statement is still around to help you out. Increasing the
complexity of the with statement so that it can cover every conceivable
try statement use case would defeat the whole point of adding the new
statement in the first place.

Cheers,
Nick.

P.S. You could always factor the above out into a simple function:

def get_first_line(fname):
  try:
    f = open('foo')
  except IOError:
    line = "can't open"
  try:
    line = f.readline()
  except IOError:
    line = "can't read"
  try:
    f.close()
  except IOError:
    line = "can't close"
  return line

line = get_first_line('foo')

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------



More information about the Python-ideas mailing list