cleaner way to write this try/except statement?

Simon Forman rogue_pedro at yahoo.com
Tue Aug 1 20:09:47 EDT 2006


John Salerno wrote:
> 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)

If you're not really interested in methods, static or otherwise, and
actually just want a cleaner Validate() method, I would code it as
follows (note that calling int() on an empty string will raise
ValueError):


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

    try:
        T = int(text)
    except ValueError:
        result = False
    else:
        result = T > 0

    if not result:
        wx.MessageBox('Enter a valid time.', 'Invalid time entered',
                   wx.OK | wx.ICON_ERROR)

    return result

Peace,
~Simon




More information about the Python-list mailing list