473,725 Members | 2,197 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

cleaner way to write this try/except statement?

The code to look at is the try statement in the NumbersValidato r 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 NumbersValidato r(wx.PyValidato r):

def __init__(self):
wx.PyValidator. __init__(self)

def Clone(self):
return NumbersValidato r()

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

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 TransferToWindo w(self):
return True

def TransferFromWin dow(self):
return True
class Timer(wx.Frame) :

def __init__(self):
wx.Frame.__init __(self, None, wx.ID_ANY, 'Timer',
style=wx.DEFAUL T_FRAME_STYLE ^ wx.RESIZE_BORDE R
^ wx.MAXIMIZE_BOX )
self.panel = wx.Panel(self)

mainSizer = wx.BoxSizer(wx. VERTICAL)
inputSizer = wx.BoxSizer(wx. HORIZONTAL)

self.progress = wx.Gauge(self.p anel, wx.ID_ANY, 100, size=(300,
20))
self.status = wx.StaticText(s elf.panel, wx.ID_ANY, 'Enter a time.')
prompt = wx.StaticText(s elf.panel, wx.ID_ANY, 'Time to wait:')
self.input = wx.TextCtrl(sel f.panel, wx.ID_ANY, size=(20, 20),
validator=Numbe rsValidator())
self.start = wx.Button(self. panel, wx.ID_ANY, 'Start')
self.reset = wx.Button(self. panel, wx.ID_ANY, 'Reset')
self.reset.Disa ble()
self.sound = wx.Sound(r'C:\W indows\Media\no tify.wav')
self.timer = wx.Timer(self)

mainSizer.Add(s elf.progress, flag=wx.ALIGN_C ENTER | wx.ALL ^
wx.BOTTOM,
border=10)
mainSizer.Add(s elf.status, flag=wx.ALIGN_C ENTER | wx.ALL,
border=10)
mainSizer.Add(i nputSizer, flag=wx.ALIGN_C ENTER | wx.BOTTOM,
border=10)
inputSizer.Add( prompt, flag=wx.ALIGN_C ENTER)
inputSizer.Add( self.input, flag=wx.ALIGN_C ENTER | wx.LEFT |
wx.RIGHT,
border=5)
inputSizer.Add( self.start, flag=wx.ALIGN_C ENTER)
inputSizer.Add( self.reset, flag=wx.ALIGN_C ENTER)

self.Bind(wx.EV T_TEXT_ENTER, self.OnStart, self.input)
self.Bind(wx.EV T_BUTTON, self.OnStart, self.start)
self.Bind(wx.EV T_TIMER, self.OnTimer, self.timer)
self.Bind(wx.EV T_BUTTON, self.OnReset, self.reset)

self.panel.SetS izer(mainSizer)
mainSizer.Fit(s elf)

def OnStart(self, event):
if self.panel.Vali date():
self.time = int(self.input. GetValue())
self.minutes_pa ssed = 1
self.minutes_re maining = self.time - 1
self.start.Disa ble()
self.input.Disa ble()
self.reset.Enab le()
self.status.Set Label('%s minute(s) remaining.' % self.time)
self.timer.Star t(1000)

def OnReset(self, event):
if self.timer.IsRu nning():
self.timer.Stop ()
self.input.Clea r()
self.input.Enab le()
self.start.Enab le()
self.reset.Disa ble()
self.status.Set Label('Enter a new time.')
self.progress.S etValue(0)
self.minutes_pa ssed = 1

def OnTimer(self, event):
if self.minutes_re maining != 0:
self.progress.S etValue(self.mi nutes_passed * 100 / self.time)
self.status.Set Label('%s minute(s) remaining.' %
self.minutes_re maining)
self.minutes_pa ssed += 1
self.minutes_re maining -= 1
else:
self.timer.Stop ()
self.progress.S etValue(self.mi nutes_passed * 100 / self.time)
self.status.Set Label('%s minute(s) have elapsed.' % self.time)
wx.Sound.Play(s elf.sound)
class MyApp(wx.App):

def OnInit(self):
frame = Timer()
self.SetTopWind ow(frame)
frame.Show()
return True
if __name__ == '__main__':
app = MyApp(False)
app.MainLoop()
Aug 1 '06 #1
13 1750
John Salerno wrote:
The code to look at is the try statement in the NumbersValidato r 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.GetVa lue()

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)
Aug 1 '06 #2
John Salerno wrote:
John Salerno wrote:
The code to look at is the try statement in the NumbersValidato r 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.GetVa lue()

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.

Peace,
~Simon

Aug 1 '06 #3
Simon Forman wrote:
John Salerno wrote:
John Salerno wrote:
The code to look at is the try statement in the NumbersValidato r 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.GetVa lue()

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

Aug 1 '06 #4
Here's how I would do it:

def Validate(self, parent):
try:
text_ctrl = self.GetWindow( )
text = text_ctrl.GetVa lue()
if not text: raise ValueError
if int(text) <= 0: raise ValueError
return True
except ValueError, error:
wx.MessageBox(' Enter a valid time.', 'Invalid time
entered', wx.OK | wx.ICON_ERROR)
return False

Aug 1 '06 #5
John Salerno wrote:
The code to look at is the try statement in the NumbersValidato r 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 NumbersValidato r(wx.PyValidato r):

def __init__(self):
wx.PyValidator. __init__(self)

def Clone(self):
return NumbersValidato r()

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

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.GetVa lue()
try :
assert int(text)>0
return True
except (ValueError,Ass ertionError) :
wx.MessageBox(' Enter a valid time.', 'Invalid time entered',
wx.OK | wx.ICON_ERROR)
return False

hth, BB
Aug 1 '06 #6
John Salerno wrote:
John Salerno wrote:
The code to look at is the try statement in the NumbersValidato r 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.GetVa lue()

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

Aug 2 '06 #7
Boris Borcic wrote:
John Salerno wrote:
The code to look at is the try statement in the NumbersValidato r 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 NumbersValidato r(wx.PyValidato r):

def __init__(self):
wx.PyValidator. __init__(self)

def Clone(self):
return NumbersValidato r()

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

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.GetVa lue()
try :
assert int(text)>0
return True
except (ValueError,Ass ertionError) :
wx.MessageBox(' Enter a valid time.', 'Invalid time entered',
wx.OK | wx.ICON_ERROR)
return False

hth, BB
Assertion statements "go away" when you run python with the '-O' or
'-OO' options. They're only meant for debugging and shouldn't be used
as part of your actual program logic.

You run the risk of introducing hard-to-find bugs if you use them like
this and somebody, somewhere, sometime runs your code in "optimized"
mode.

Peace,
~Simon

Aug 2 '06 #8
John Salerno wrote:
The code to look at is the try statement in the NumbersValidato r 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 NumbersValidato r(wx.PyValidato r):

def __init__(self):
wx.PyValidator. __init__(self)

def Clone(self):
return NumbersValidato r()

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

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 TransferToWindo w(self):
return True

def TransferFromWin dow(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 PositiveInteger Validator(wx.Py Validator):
# ...
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

Aug 2 '06 #9
Peter Otten wrote:
John Salerno wrote:
>The code to look at is the try statement in the NumbersValidato r 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 NumbersValidato r(wx.PyValidato r):

def __init__(self):
wx.PyValidator. __init__(self)

def Clone(self):
return NumbersValidato r()

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

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 TransferToWindo w(self):
return True

def TransferFromWin dow(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 PositiveInteger Validator(wx.Py Validator):
# ...
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
Thanks for all the help guys! I'm going to rework it a little and see
what happens. Luckily, I'm also reading the chapter on exceptions in
Python in a Nutshell, so maybe that will help solidify my understanding
of how to construct them in this situation.
Aug 2 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
1478
by: Michael Ellis | last post by:
Hi, I have some data files with lines in space-delimited <name> <value> format. There are multiple name-value pairs per line. Is there a cleaner idiom than the following for reading each line into an associative array for the purpose of accessing values by name? for line in infile: tokens = line.split() dict = {}
20
7351
by: Al Moritz | last post by:
Hi all, I was always told that the conversion of Word files to HTML as done by Word itself sucks - you get a lot of unnecessary code that can influence the design on web browsers other than Internet Explorer. Our computer expert in my company had told me already a while ago that I should learn HTML and encode myself. I was never inclined to do so (I am no computer expert), and when upon his suggestion I looked how my pages (converted to...
4
2950
by: Prowler | last post by:
In the application we are currently building, we need to write positioning code on-the-fly, based upon the screen offset of the element in the AS/400 application which drives the Web app. The 400, like DOS, uses memory-mapped display, two bytes per character (one char byte and one attribute byte). We can get the screen offset allright, and I've written a javascript which does the math to convert the offset into row/col (i.e. left, top)...
0
297
by: Bennett Haselton | last post by:
I've noticed that if you enter the following code in the codebehind page for an .aspx page, it won't compile because the call to Trace.Write() is not valid except in methods of a class derived from System.Web.UI.Page. Two questions: 1) I don't know much about C# but I was under the impression that if certain classes and functions were available in a namespace (as the result of a "using" statement at the top of a file), then they were...
88
8059
by: Peter Olcott | last post by:
Cab you write code directly in the Common Intermediate language? I need to optimize a critical real-time function.
29
1422
by: John Salerno | last post by:
Hi guys. I'm looking for a nicer, more compact way of writing this code. It doesn't have to be anything fancy, just something without the duplication and preferably only one return statement. def create_db_name(self): dlg = wx.TextEntryDialog(self.frame, 'Enter a database name:', 'Create New Database') if dlg.ShowModal() == wx.ID_OK: db_name = dlg.GetValue() dlg.Destroy()
4
1233
by: Chris Allen | last post by:
I am confused on one aspect of exception handling. If you specify the exception object type to match in an except statement it is possible to also obtain the exception object itself, but I can't figure out how to get the exception object when I don't specify a match. for example: this works and I can do what I like with the exception object (msg). but I can't do this with a simple except statment.
9
1221
by: =?Utf-8?B?cm9kY2hhcg==?= | last post by:
hey all, please reference: http://pastebin.com/mef78b3d As shown in the reference I am dynamically building my controls in my class. I'd like to be able to attach javascript calls as attributes to each of my controls if applies. for example, String varString = "alert('i'm a textbox')";
0
9401
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9257
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9113
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6702
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6011
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4519
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4784
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3221
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2635
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.