converting a nested try/except statement into try/except/else

Simon Forman rogue_pedro at yahoo.com
Wed Aug 9 16:19:42 EDT 2006


John Salerno wrote:
> I'm starting out with this:
>
> try:
>      if int(text) > 0:
>          return True
>      else:
>          self.error_message()
>          return False
> except ValueError:
>      self.error_message()
>      return False
>
> I rewrote it as this:
>
> try:
>      int(text)
> except ValueError:
>      self.error_message()
>      return False
> else:
>      return True
>
> I think it's much cleaner, but obviously I lost the test in the original
> if statement.
>
> So my question is, can I still retain this second structure and still
> test for > 0, but not have any extra nesting?
>
> Thanks.

What about the version I gave you 8 days ago? ;-)

http://groups.google.ca/group/comp.lang.python/msg/a80fcd8932b0733a

It's clean, does the job, and doesn't have any extra nesting.

Peace,
~Simon




More information about the Python-list mailing list