cleaner way to write this try/except statement?

John Salerno johnjsal at NOSPAMgmail.com
Tue Aug 1 16:45:52 EDT 2006


John Salerno wrote:
> The code to look at is the try statement in the NumbersValidator class, 
> just a few lines down. Is this a clean way to write it? i.e. is it okay 
> to have all those return statements? Is this a good use of try? Etc.

I cleaned it up a little and did this, but of course this doesn't work. 
Is this the wrong way to create a function (not method) within a class?



def Validate(self, parent):
         text_ctrl = self.GetWindow()
         text = text_ctrl.GetValue()

         try:
             if not text or int(text) <= 0:
                 error_message()
                 return False
             else:
                 return True
         except ValueError:
             error_message()
             return False

     @staticmethod
     def error_message():
         wx.MessageBox('Enter a valid time.', 'Invalid time entered',
                       wx.OK | wx.ICON_ERROR)



More information about the Python-list mailing list