473,698 Members | 2,615 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Coding style and else statements

def foo(thing):

if thing:
return thing + 1
else:
return -1

def foo(thing):

if thing:
return thing + 1
return -1

Obviously both do the same thing. The first is
possibly clearer, while the second is more concise.

Comments?

--
Posted via a free Usenet account from http://www.teranews.com

Aug 28 '06 #1
19 1999
On 8/28/06, tobiah <st@tobiah.orgw rote:
def foo(thing):

if thing:
return thing + 1
else:
return -1

def foo(thing):

if thing:
return thing + 1
return -1

Obviously both do the same thing. The first is
possibly clearer, while the second is more concise.

Comments?
if there is nothing the else will check why put it there?
>
--
Posted via a free Usenet account from http://www.teranews.com

--
http://mail.python.org/mailman/listinfo/python-list
Aug 28 '06 #2
tobiah a écrit :
def foo(thing):

if thing:
return thing + 1
else:
return -1

def foo(thing):

if thing:
return thing + 1
return -1

Obviously both do the same thing. The first is
possibly clearer, while the second is more concise.

Comments?
What about:

def foo(thing):
if thing:
result = thing + 1
else:
result = -1
return result

and:

foo = lambda thing: thing and thing + 1 or -1
Aug 28 '06 #3
Bruno Desthuilliers wrote:
foo = lambda thing: thing and thing + 1 or -1
The and ... or trick is buggy (what if thing == -1?) and bad style. If
you -do- want a conditional expression, 2.5 provides one:

thing + 1 if thing else -1

No subtle logical bugs, and a good deal more obvious.

On the topic of the original posting, I personally prefer the latter
(no else clause), because too deep a level of indentation is not a Good
Thing. However, if a redundant else: would make the code clearer
somehow, by all means use one, because this is more a matter of
personal taste than anything.

Aug 28 '06 #4
tobiah wrote:
def foo(thing):

if thing:
return thing + 1
else:
return -1

def foo(thing):

if thing:
return thing + 1
return -1

Obviously both do the same thing. The first is
possibly clearer, while the second is more concise.

Comments?
I usually prefer the second option because it is more scalable - it is
possible to later add code to the function to return other values
elsewhere in its code, and still have -1 returned by default, without
changing the original code.

As for structure, in the second example there is a clear point at which
the function return a value, unless some other value is return
elsewhere. In the first one you have to comprehend the entire if-else
statement to understand that a value will always be returned at this
point.

Another worthy alternative mentioned is:

def foo(thing):
if thing:
result = thing + 1
else:
result = -1
return result

This is scalable as described above, and also has only one exit point,
which makes it a much simpler function. However, it forces someone
reading the code to backtrack from the return statement and search for
places where "result" could be set.

I usually start with your second example, and if I need more control
over the returned value I change the code to use this last method.
("More control" could be many things - checking the value for
debugging, applying some transformation on the returned value before
returning it...)

- Tal

Aug 28 '06 #5
Sam Pointon a écrit :
Bruno Desthuilliers wrote:
>>foo = lambda thing: thing and thing + 1 or -1


The and ... or trick is buggy (what if thing == -1?)
Yes, true - Should be:
foo2 = lambda t: t != -1 and (t and t+1 or -1) or 0

and bad style.
Lol. Well, so what about:
foo = lambda t: (lambda t: -1, lambda t: t+1)[bool(t)](t)

?-)

(NB: don't bother answering)

If
you -do- want a conditional expression, 2.5 provides one:
Yes, at last, and I'm glad it finally made it into the language. But 2.5
is not here yet. The 'and/or' trick can be, well, tricky, (notably in
this case) but it at least work with most Python versions.

No subtle logical bugs, and a good deal more obvious.
Indeed.
Aug 28 '06 #6

Bruno Desthuilliers wrote:
Sam Pointon a écrit :
Bruno Desthuilliers wrote:
>foo = lambda thing: thing and thing + 1 or -1

The and ... or trick is buggy (what if thing == -1?)

Yes, true - Should be:
foo2 = lambda t: t != -1 and (t and t+1 or -1) or 0
Actually, the common work-around for this is:

(thing and [thing+1] or [-1])[0]

This works since non-empty lists are always considered true in
conditional context. This is more generic, and IMO more readable.

Aug 29 '06 #7
tobiah wrote:
def foo(thing):
if thing:
return thing + 1
else:
return -1

def foo(thing):
if thing:
return thing + 1
return -1

Obviously both do the same thing. The first is
possibly clearer, while the second is more concise.

I almost always go with #2. The else clause is redundant and
potentially misleading in the first one. (A casual programmer might
not notice that it always returns and so add code beneath it, or a
casual code checker might not notice that the end is unreachable, and
flag the function as both returning a value and returning the default.)

However, I have rare cases where I do choose to use the else (ususally
in the midst of a complicated piece of logic, where it's be more
distracting than concise). In that case, I'd do something like this:

def foo(thing):
if thing:
return thing+1
else:
return -1
assert False
Carl Banks

Aug 30 '06 #8
Carl Banks wrote:
[...]
However, I have rare cases where I do choose to use the else (ususally
in the midst of a complicated piece of logic, where it's be more
distracting than concise). In that case, I'd do something like this:

def foo(thing):
if thing:
return thing+1
else:
return -1
assert False
I think that's about the most extreme defensive programming I've seen in
a while! I can imaging it's saved your ass a couple of times when you've
edited the code a while after writing it.

Of course, optimising will remove the assertions ...

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

Aug 30 '06 #9
"Carl Banks" <pa************ @gmail.comwrite s:
However, I have rare cases where I do choose to use the else
(ususally in the midst of a complicated piece of logic, where it's
be more distracting than concise). In that case, I'd do something
like this:

def foo(thing):
if thing:
return thing+1
else:
return -1
assert False
To my eyes, that's less readable than, and has no benefit over, the
following:

def foo(thing):
if thing:
result = thing+1
else:
result = -1
return result

--
\ "Ours is a world where people don't know what they want and are |
`\ willing to go through hell to get it." -- Donald Robert Perry |
_o__) Marquis |
Ben Finney

Aug 30 '06 #10

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

Similar topics

5
1398
by: Zhang Weiwu | last post by:
Hello. I have a question that spining around my head for a long time. I prefer to make this kind of if statement: if (!$GLOBALS) Header( 'Location: '.$GLOBALS-> link('/', 'menuaction=forum.uiforum.index') ); But almost all the 'good' php code I saw write it this way:
9
11107
by: Marco Aschwanden | last post by:
Hi I checked the other day a module of mine with pylint. And for some function it told me, that I was using too many return-statements in my code... there were about 5 or 7 of them in my function. Through books I learned, that there should be only 1 return statement in a function. This makes for clear code - they said. I tried to stick to this principle for a very long time... ending up with deeper and deeper nested...
15
3233
by: lawrence | last post by:
Sorry for the dumb question but I'm new to Javascript. I wrote this script hoping to animate some div blocks on a page. You can see the page here: http://www.keymedia.biz/demo.htm Can anyone tell me why these DIVs don't drift to the left as they are supposed to? <script language="javascript">
18
2543
by: craig | last post by:
I am curious about how many of you prefer style 1 vs. style 2, and why. Are there names for these style? style 1: method { }
63
3505
by: Papadopoulos Giannis | last post by:
Which do you think is best? 1. a) type* p; b) type *p; 2. a) return (var); b) return(var); c) return var;
60
3170
by: Eric | last post by:
I thought it might be fun to run a simple vote to discover the most preferred spacing style for a simple if statement with a single, simple boolean test. By my count, there are 32 possible variations for this case. Here is a complete list. AA: if ( a > b ) AB: if ( a > b) AC: if ( a >b ) AD: if ( a >b) AE: if ( a> b )
144
6861
by: Natt Serrasalmus | last post by:
After years of operating without any coding standards whatsoever, the company that I recently started working for has decided that it might be a good idea to have some. I'm involved in this initiative. Typically I find that coding standards are written by some guy in the company who has a way of coding that he likes and then tries to force everybody else to write code the way he likes it, not for any rational reason, but simply for the...
52
2976
by: Sergey Zuyev | last post by:
Hello All I work at software company and we are having a really big discussion about coding styles and it seems that more people prefer statement 1 to statement2 , which was a big surprise to me. Please help us with your comments. Thanks Which way is better way 1 or 2? 1. 'set enable status on CheckboxPrimaryYN
19
3966
by: auratius | last post by:
http://www.auratius.co.za/CSharpCodingStandards.html Complete CSharp Coding Standards 1. Naming Conventions and Styles 2. Coding Practices 3. Project Settings and Project Structure 4. Framework-Specific Guidelines Naming Conventions and Styles
0
8612
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
9032
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
8905
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
7743
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6532
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
5869
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();...
1
3053
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
2342
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2008
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.