cleaner way to write this try/except statement?

Boris Borcic bborcic at gmail.com
Tue Aug 1 18:54:53 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.
> 
> Thanks.
> 
> ----------------------------
> 
> import wx
> 
> 
> class NumbersValidator(wx.PyValidator):
> 
>     def __init__(self):
>         wx.PyValidator.__init__(self)
> 
>     def Clone(self):
>         return NumbersValidator()
> 
>     def Validate(self, parent):
>         text_ctrl = self.GetWindow()
>         text = text_ctrl.GetValue()
> 
>         try:
>             if not text or int(text) <= 0:
>                 wx.MessageBox('Enter a valid time.', 'Invalid time
>                               entered', wx.OK | wx.ICON_ERROR)
>                 return False
>             else:
>                 return True
>         except ValueError, error:
>             wx.MessageBox('Enter a valid time.', 'Invalid time entered',
>                           wx.OK | wx.ICON_ERROR)
>             return False

well, assuming you are unsatisfied with the above, you could try to assert the 
validation condition and catch together all failures, eg :

def Validate(self, parent):
         text_ctrl = self.GetWindow()
         text = text_ctrl.GetValue()
         try :
             assert int(text)>0
             return True
         except (ValueError,AssertionError) :
             wx.MessageBox('Enter a valid time.', 'Invalid time entered',
                           wx.OK | wx.ICON_ERROR)
             return False

hth, BB



More information about the Python-list mailing list