cleaner way to write this try/except statement?

Roy Smith roy at panix.com
Wed Aug 2 11:04:41 EDT 2006


John Salerno  <johnjsal at NOSPAMgmail.com> wrote:
>         try:
>             if int(text) != 0:
>                 return True
>             else:
>                 self.error_message()
>                 return False
>         except ValueError:
>             self.error_message()
>             return False

One possible refactoring would be:

try:
  if int(text) != 0:
    return True
except:
  pass
self.error_message()
return False

It's two less lines of code, one less return, and eliminates the
duplicate call to error_message().  On the other hand, the "except:
pass" clause is unusual and would make me (as a reader of the code)
stop and think what was going on.  Pick your poison.

If you want to be truly cryptic and obfuscatory, there's always:

try:
  1 / int(text)
  return True
except:
  return False



More information about the Python-list mailing list