cleaner way to write this try/except statement?

Simon Forman rogue_pedro at yahoo.com
Tue Aug 1 17:44:39 EDT 2006


Simon Forman wrote:
> 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)
>
> Your indentation looks off.  Your error_message() function should be at
> the same indentation as the rest of the body of the Validate() method
> (i.e. same as the try statement, "text_ctrl = ..." statements.)
>
> If that's not an artifact of posting it here then you'll need to
> correct that.
>
> Also, there's no need to declare the function a staticmethod, since it
> isn't.
>
> Other than that it looks ok to me, but I might have missed something.


Maybe I did miss something:  Are you actually trying to make a static
method?  Say, to be able to call it elsewhere than just the Validate()
method?

In that case, your indentation is still (apparently) off, but the
error_message() method (a staticmethod is still a method I think, but I
could be wrong) should be at the same indentation level as any other
method, and you have to prepend the instance object ('self.' if you're
calling it from inside another method) to it when you call it.

class A(object):
    def meth(self, arg):
        self.func(arg)

    @staticmethod
    def func(arg):
        print arg

a = A()

a.func("hi")
a.meth("world.")


# prints
hi
world.

HTH,
~Simon




More information about the Python-list mailing list