473,796 Members | 2,599 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

converting a nested try/except statement into try/except/else

I'm starting out with this:

try:
if int(text) 0:
return True
else:
self.error_mess age()
return False
except ValueError:
self.error_mess age()
return False

I rewrote it as this:

try:
int(text)
except ValueError:
self.error_mess age()
return False
else:
return True

I think it's much cleaner, but obviously I lost the test in the original
if statement.

So my question is, can I still retain this second structure and still
test for 0, but not have any extra nesting?

Thanks.
Aug 9 '06
20 3930
Slawomir Nowaczyk wrote:
>
try:
if int(text) 0:
return True
except ValueError:
pass
self.error_mess age()
return False
Nicely DRY. To make it even more compact, it may be noticed that the default
return value None is false in a boolean context - so that the last line is
superfluous if the return value is only wanted to test it in such a context.
Aug 10 '06 #11
On Thu, 10 Aug 2006 14:32:49 +0000 (GMT)
John Salerno <jo******@NOSPA Mgmail.comwrote :

#Bruno Desthuilliers wrote:
#>
# try:
# if int(text) <= 0: raise ValueError
#>
#Hmm, I'm actually not so sure about this line now. It doesn't seem right
#to raise a ValueError when the result of the expression is negative,
#because even though it's a problem for my program, it isn't really a
#"ValueError ," right?

Well, you could always do something like
try:
int("-"+text)
Now, this *will* be a real ValueError for negative integers ;-) ;-) ;-)

But no, I am not suggesting that... especially since "-0" is valid.

--
Best wishes,
Slawomir Nowaczyk
( Sl************* **@cs.lth.se )

COMMAND: A suggestion made to a computer.

Aug 10 '06 #12
Boris Borcic a écrit :
Slawomir Nowaczyk wrote:
>>
try:
if int(text) 0:
return True
except ValueError:
pass
self.error_mes sage()
return False

Nicely DRY. To make it even more compact, it may be noticed that the
default return value None is false in a boolean context - so that the
last line is superfluous if the return value is only wanted to test it
in such a context.
While it's technically true - and I while I have a taste for compactness
- skipping the explicit 'return False' somehow hurts my sense of
esthethic... Unless you propose to return object or type instead of
True - but then it begins to look very strange !-)
Aug 10 '06 #13
Boris Borcic wrote:
Slawomir Nowaczyk wrote:
>>
try:
if int(text) 0:
return True
except ValueError:
pass
self.error_mes sage()
return False

Nicely DRY. To make it even more compact, it may be noticed that the
default return value None is false in a boolean context - so that the
last line is superfluous if the return value is only wanted to test it
in such a context.
In this case the method must return False, because it's a wxPython
method that needs a True or False value. If it doesn't, the program will
continue even after the error message.

What I did to make it compact was have the error_message() method return
False, so I can just call

return self.error_mess age()
Aug 10 '06 #14
Bruno Desthuilliers wrote:
Boris Borcic a écrit :
>Slawomir Nowaczyk wrote:
>>>
try:
if int(text) 0:
return True
except ValueError:
pass
self.error_me ssage()
return False

Nicely DRY. To make it even more compact, it may be noticed that the
default return value None is false in a boolean context - so that the
last line is superfluous if the return value is only wanted to test it
in such a context.
While it's technically true - and I while I have a taste for compactness
- skipping the explicit 'return False' somehow hurts my sense of
esthethic... Unless you propose to return object or type instead of
True - but then it begins to look very strange !-)
so what about simplifying your solution 1 to

try :
return int(text)>0 or int('garbage')
except ValueError :
self.error_mess age()
it still returns True on success, but hides it well :) and while perhaps a bit
too clever I feel it competes well on readability, precisely because it is
compact and because int('garbage') mimics int(text) while standing just before
'except ValueError'. That mimicry kind of encapsulates your and infidel'sanswer
to the OP's objection to raising ValueError if int(text)<=0.

Aug 10 '06 #15
John Salerno wrote:
In this case the method must return False, because it's a wxPython
method that needs a True or False value. If it doesn't, the program will
continue even after the error message.
Just as it should do if the method returns True and no error message is produced
if I understand you well... Are you sure ? I don't know wxPython, but this
strikes me as surprisingly unpythonic behavior.
Aug 10 '06 #16
Boris Borcic wrote:
John Salerno wrote:
>In this case the method must return False, because it's a wxPython
method that needs a True or False value. If it doesn't, the program
will continue even after the error message.

Just as it should do if the method returns True and no error message is
produced if I understand you well... Are you sure ? I don't know
wxPython, but this strikes me as surprisingly unpythonic behavior.
I just verified on the wxWindows demo I had somehow installed on my box, that
indeed returning None appears to produce the same behavior as returning True,
distinct from the behavior obtained by returning False. Ugh...
Aug 10 '06 #17
John Salerno wrote:
Simon Forman wrote:
What about the version I gave you 8 days ago? ;-)

http://groups.google.ca/group/comp.l...0fcd8932b0733a

It's clean, does the job, and doesn't have any extra nesting.

Peace,
~Simon

I remember that version, but I found it a little hard to follow. It
seems like the kind of code that if I look at it again in another month
or so, I'll have to trace through it again to figure out what's what.
I'm sorry to hear that. I thought it was cleaner and more
understandable than that. May I indulge in explaining it a bit? I
can, perhaps, make it clearer.

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

# Detect whether the text is a valid int.
try:
# Do the integer conversion.
T = int(text)

except ValueError:
# It did not convert, the test is False.
result = False

else:
# It converted. T is an integer.
# The result of the test is the Boolean
# expression (T 0)
result = T 0

# At this point our testing is done.
# Var result is a Boolean indicating, um,
# the result of the test.. :-)

# Orthogonal to the test itself, report the
# (possible) failure of the test.
if not result: self.error_mess age()

# Return the result.
return result

There are several good (IMHO) points to this version.

1.) The least code possible occurs in the try..except statement.

I feel that you should strive to put the least possible code between
"try" and "except". A try..except block basically means, "I expect
this error, and I know exactly what to do about it." Otherwise you
would leave out the error check and let exceptions propagate up to
either a higher level error handler or the user/coders themselves.

That's kind of why exceptions exist in the first place: to indicate
when something exceptional happened. You put a try..except statement
in your code when an exception *wouldn't* be exceptional, i.e. when you
know what to do about it.

This is the flipside of "bare except: is bad".

When you start cramming a bunch of extra statements into a try..except
block you run the risk of catching exceptions other than the one you
actually know what to do with. It's a source of subtle bugs, and, IMO,
a Bad Idea.

2.) The except clause does almost nothing.

If a ValueError occured, the result is False. You're done. Simple, easy
to understand, unlikely to fail or have obscure errors.

3.) The else clause does almost nothing.

If your control flow arrives in the else clause, you know you have a
int T that contains the value of the integer your user entered. All
that remains is to test T is greater than zero. Since you need that
information twice more in your method (once to trigger error reporting
and once more to return it) you simply assign it to a variable, reusing
the same name that would have been assigned in the except clause.
Because of that...

4.) At the end of the try..except..el se statement you have a result
variable that contains the Boolean result of the test. It's pretty
much guaranteed.

There's no linkage between the previous part of your code and the rest
except for that Boolean variable. Less linkage is generally a Good
Thing. It makes your code easier to modify and debug.

5.) The error reporting statement is completely "orthogonal " to the
rest of the method. You could change it or comment it out or remove it
without affecting (or having to edit) the rest of your method.

6.) There's a single return statement.

I forget now where I picked this up, but it's served me well for many
years: Procedures, functions, methods, etc... should have one exit
point. Something about having fewer "code paths" to test or something.
Also, it makes your code easier to read and understand. Sometimes
it's useful to violate this, but often when I think that's the case I
find that rewriting a function to avoid it results in better code.

7.) Last but not least, the method is made up of tiny pieces that do
only one thing and do it well. To quote C. A. R. Hoare, "There are two
ways of constructing a software design: One way is to make it so simple
that there are obviously no deficiencies, and the other way is to make
it so complicated that there are no obvious deficiencies."

Not counting the "text = self.GetWindow( ).GetValue()" statement there
are just five tiny pieces of code, each only one or two lines, and each
doing just one step of the overall processing. Written this way, there
are unlikely to be hidden deficiencies.

In "if int(text) <= 0: raise ValueError", there are four things going
on in the line: an integer conversion, a comparison, an if..then
statement, and an "Exception raising". Not the worst code by any
means, but more dense than it needs to be.

Given that people can (supposedly) only handle 7+|-2 pieces of
information at a time, having four pieces in one line is quite a few.
Now this isn't really fair, that line is simple enough for most
programmers to understand at a glance, but the principal still holds.
You're not really gaining much from putting all that stuff in there
anyway, at least in terms of length of code.

Consider:

import dis

def val0(text):
try:
T = int(text)

except ValueError:
result = False

else:
result = T 0

if not result: error_message()

return result

def val1(text):
try:
if int(text) <= 0: raise ValueError

except ValueError:
error_message()
return False

else:
return True

dis.dis(val0)
print '############## '
dis.dis(val1)
Not counting blank lines, val0 is only one line longer than val1. And
if your run the code and examine the disassembly you'll find that val1
only saves a couple of bytecodes.
Well anyway, this post has gone on way longer than I wanted it to. I'd
better get back to work.

I hope the code is a little clearer to you. :-)

Peace,
~Simon

(I think, if you count this post, that's the second most extensively
documented function I've ever written. LOL)
But I think it was your code that made me think of using an else
statement in the first place! :)
Yeah, I forget about else's too sometimes. :-) for statements can
have an else.. that slips my mind all the time hahaha

Aug 10 '06 #18
On Thu, 10 Aug 2006 16:42:47 -0700
Simon Forman <ro*********@ya hoo.comwrote:

#6.) There's a single return statement.
#>
#I forget now where I picked this up, but it's served me well for
#many years: Procedures, functions, methods, etc... should have one
#exit point. Something about having fewer "code paths" to test or
#something.

Number of return statements has absolutely *nothing* to do with number
of code paths to test.

--
Best wishes,
Slawomir Nowaczyk
( Sl************* **@cs.lth.se )

Only drug dealers and software companies call their customers 'users.'

Aug 11 '06 #19
Boris Borcic wrote:
Boris Borcic wrote:
>John Salerno wrote:
>>In this case the method must return False, because it's a wxPython
method that needs a True or False value. If it doesn't, the program
will continue even after the error message.

Just as it should do if the method returns True and no error message
is produced if I understand you well... Are you sure ? I don't know
wxPython, but this strikes me as surprisingly unpythonic behavior.

I just verified on the wxWindows demo I had somehow installed on my box,
that indeed returning None appears to produce the same behavior as
returning True, distinct from the behavior obtained by returning False.
Ugh...
But since None == False is false, isn't it right that returning None
wouldn't necessarily behave like returning False?
Aug 11 '06 #20

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

Similar topics

0
1887
by: Francis Avila | last post by:
A few days ago (see the 'itertools.flatten()?' thread from October 28) I became obsessed with refactoring a recursive generator that yielded the leaves of nested iterables. When the dust settled, I had many flatten functions at hand. So I had to time them. Results below. History of the functions (from flattrial.py): # There are three basic features:
9
2292
by: wiredog | last post by:
I am struggling rewriting my query from MS Access' IIF, Then to SQL Servers TSQL language. I am hoping some one can give me some guidance. I believe I have the first portion of the query correct but do believe this requires a "NESTED" argument. This is where I am lost. My Original MS ACCESS Query reads-- SELECT DISTINCTROW REGION_TRAFIC.*, IIf(Mid(,5,2)=,
3
6473
by: Tcs | last post by:
My backend is DB2 on our AS/400. While I do HAVE DB2 PE for my PC, I haven't loaded it yet. I'm still using MS Access. And no, I don't believe this is an Access question. (But who knows? I COULD be wrong... :) I've tried the access group...twice...and all I get is "Access doesn't like ".", which I know, or that my query names are too long, as there's a limit to the length of the SQL statement(s). But this works when I don't try to...
2
5753
by: Asbjørn Ulsberg | last post by:
Hi. I'm trying to convert Brady Hegberg's great RTF2HTML VB 6.0 module to C#. I've managed to convert the VB code to VB.NET, which gave me the following code: Option Strict On Option Explicit On Option Compare Binary
4
2524
by: ECathell | last post by:
I had read an article at one time that suggested a pattern to get around deeply nested if..then..else hell... Can anyone point me in that direction? select case statements wont work for me in this instance -- --Eric Cathell, MCSA
2
2693
LonelyBunny
by: LonelyBunny | last post by:
The most unprobable issue will just pop-up when last expected..even as 'innocent' as a nested IF statement ! I am experiencing Nested IF statements problem chen coding. e.g: IF (meets a major condition) then if (another condition) then : : else : :
0
1088
by: Joeyeti | last post by:
Hi fellow VB knowers (I am but a learner still). I have a question for you which I struggle with. I need to convert nested Lists in MS WORD (whether numbered or bulleted or mixed) from their original format to a tag-formatted text (as used for instance for Wiki articles or phpBB Forums and such). In my particular case I need the text to have basic HTML tags for the basic formatting - e.g. <strong>text</strong> or <em>italics</em> - and this...
12
2584
by: desktop | last post by:
Are there any performance issues between: bool run = true; while(run) { if (bob1 &&){ //dothing break; }
13
2126
by: JRough | last post by:
I got lost on formatting the nested if/else's on the bottom of the file right up the last else/if there seems to be a stray bracket. I'm trying to line up the brackets so I can read it. Is it okay to split a long line setting a variable on two lines at the equals sign? That is so you can read it in google groups. <? //Send payement advices $TPL_auction_id = $auction_id; $user_id=$userrec;
0
9531
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10459
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
10237
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...
1
10187
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10018
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
7553
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
5578
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4120
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
3
2928
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.