[Tutor] Program review

Jeff Younker jeff at drinktomi.com
Mon Jan 7 04:32:43 CET 2008


>
> Maybe it is my poor understanding of exception handling. My intention
> here is to open the first file, if error then report in logging and
> finish normally, else open the 2nd file, if error then report in  
> logging
> close the 1st file and finish normally. If no error then process.
>

Right, but it helps to break up the error handling and the cleanup.
Right now the error reporting exception handlers are intermixed
with your cleanup error handlers.  Separating them makes the code
clearer.

def open_file(filename):
      try :
          return open(filename)
      except Exception:
          logging.error('No pude abrir "%s"' % filename, exec_info=True)
          raise

# Goes into configuration class
def mails(self):
   fIncl = open_file(self.direcciones)
   try:
      fExcl = open_file(self.excluidas)
      try:
          return enumerate(
                      set(addr.strip() for addr in fIncl)
                      - set(excl.strip() for excl in fExcl))
      finally:
           fExcl.close()
   finally:
        fIncl.close()

Or if you're using python 2.5 then you can use with statements:

from __future__ import with_statements
from contextlib import closing
...
def mails(self):
     with closing(open_file(self.direcciones)) as fIncl:
            with closing(open_file(self.excluidas)) as fExcl:
                return enumerate(
                        set(addr.strip() for addr in fIncl)
                        - set(excl.strip() for excl in fExcl))

> close the 1st file and finish normally. If no error then process.

If an exception is raised then the code terminates right there and
then.   So, if procesar is written as:

def procesar(mensaje):
      mails = mensaje.mails()
      miCorreo = Correo(mensaje)
      ....

then if mensaje.mails() raises an exception then the code
terminates immediately, and the body of Correo will only be
executed if there is no error.

As you have it written it terminates, but it also silently consumes the
exception.  If something goes wrong with your program then there is
no way of diagnosing the problem because the failure cause is never
reported.

-jeff


More information about the Tutor mailing list