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

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Wed Aug 9 16:28:08 EDT 2006


John Salerno a écrit :
> 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?

solution 1:

     def wrong():
         raise ValueError

     try:
         int(text) > 0 or wrong()
     except ValueError:
         self.error_message()
         return False
     else:
         return True

But that's being-too-clever imho...

solution 2:

     def error_message():
         self.error_message()
         return False

     try:
         return int(text) > 0 or error_message()
     except ValueError:
         return error_message()




More information about the Python-list mailing list