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 > > def TransferToWindow(self): > return True > > def TransferFromWindow(self): > return True
Here's how I might do it: def is_positive_int_str(s): try: value = int(s) except ValueError: return False return value > 0 class PositiveIntegerValidator(wx.PyValidator): # ... def Validate(self, parent): text = self.GetWindow().GetValue() if is_positive_int_str(text): return True wx.MessageBox(...) return False Two usability notes: - "Invalid time entered" is a confusing message when you actually want a positive integer. - Pop-up messages are a major annoyance. An alternative would be to change the text color of the control and show a hint as to what input you expect in a status bar. Peter -- http://mail.python.org/mailman/listinfo/python-list