473,394 Members | 1,774 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

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 1976
On 8/28/06, tobiah <st@tobiah.orgwrote:
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.comwrites:
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

Sybren Stuvel wrote:
Tal Einat enlightened us with:
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.

I think it's not readable at all. It's confusing - you create a
singleton list, only to extract the first element from it and discard
the list again. I'd rather read a proper if-statement.
I agree that an "if" statement is by far more readble; I was referring
only to the dicussion of the "and-or trick", not the entire issue.

I meant to say that:

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

is more readable (IMO) than:

thing != -1 and (thing and thing+1 or -1) or 0

- Tal

Aug 30 '06 #11
At Wednesday 30/8/2006 04:47, Tal Einat wrote:
>I meant to say that:

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

is more readable (IMO) than:

thing != -1 and (thing and thing+1 or -1) or 0
Interesting to find how different persons feel "readability" - for
me, the later is rather clear (but definitively I prefer an if
statement), and the former simply sucks.
Gabriel Genellina
Softlab SRL

__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Aug 30 '06 #12
Tal Einat wrote:
I meant to say that:

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

is more readable (IMO) than:

thing != -1 and (thing and thing+1 or -1) or 0
Neither is particularly readable, though I agree that the latter is
worse since it has to have the third option ("0") on the end. But I'd
go with an if statement unless I had a real reason to use something so
unreadable. If you are enamored of such constructs, 2.5 will allow
conditional expressions:

(thing + 1) if thing else -1

Aug 30 '06 #13

Ben Finney wrote:
"Carl Banks" <pa************@gmail.comwrites:
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
For this example, yes. Actually I'd probably never do it in this
particular case. What I mean in general is some rare times (especially
when logic is complex) I prefer to use a redundant control statement
that renders something non-reachable; then I use assert False there.
Carl Banks

Aug 30 '06 #14

Steve Holden wrote:
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.
1. The "assert False" is more for documenting than error checking.
2. The right way to be defensive here is not to have redundant logic.
The above is really something I do rarely only when some other factor
makes the redundant logic a lesser of evils.
Carl Banks

Aug 30 '06 #15
"Carl Banks" <pa************@gmail.comwrites:
Ben Finney wrote:
"Carl Banks" <pa************@gmail.comwrites:
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

For this example, yes. Actually I'd probably never do it in this
particular case. What I mean in general is some rare times
(especially when logic is complex) I prefer to use a redundant
control statement that renders something non-reachable; then I use
assert False there.
That's the readability problem I'm referring to. Why not ensure that
there is one return point from the function, so the reader doesn't
have to remind themselves to look for hidden return points?

--
\ "Dyslexia means never having to say that you're ysror." -- |
`\ Anonymous |
_o__) |
Ben Finney

Aug 30 '06 #16
Ben Finney <bi****************@benfinney.id.auwrites:
Why not ensure that there is one return point from the function, so
the reader doesn't have to remind themselves to look for hidden
return points?
There will always be more potential return points in languages that
support exceptions.
--
Pete Forman -./\.- Disclaimer: This post is originated
WesternGeco -./\.- by myself and does not represent
pe*********@westerngeco.com -./\.- the opinion of Schlumberger or
http://petef.port5.com -./\.- WesternGeco.
Aug 31 '06 #17
Pete Forman <pe*********@westerngeco.comwrites:
Ben Finney <bi****************@benfinney.id.auwrites:
Why not ensure that there is one return point from the function,
so the reader doesn't have to remind themselves to look for hidden
return points?

There will always be more potential return points in languages that
support exceptions.
I was specifically referring to 'return' points, i.e. points in the
function where a 'return' statement appears.

In the example to which I responded, the function had multiple
'return' statements, and an 'assert' to aid in finding out when none
of the return statements was hit. I'm making the point that if that
effort is being taken anyway, it's more readable to allow the reader
to see only *one* explicit return at the end, and not write any more
in the first place.

--
\ "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 31 '06 #18
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
I wouldn't discount:

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

especially if "thing" is the less expected case. This
puts the "more likely" result first, followed by checks
that might modify that result.

But, I also try to avoid adding 1 to things that I test
for Truth:
>>x = 8
foo(x)
9
>>foo(x>1)
2
>>foo(x and 1)
2
>>foo(x or 1)
9

--Matt

Sep 1 '06 #19
ma***********@gmail.com writes:
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
I chose this to more clearly contrast with the example to which I was
responding; same number of statements but clearer control flow.
I wouldn't discount:

def foo(thing):
result = -1
if thing:
result = thing+1
return result
Yes, that would be my preferred form in most cases.

If I'm writing a function that returns a value, I like to make it
clear by the symmetry of 'result = DefaultValue' and 'return result'
that that's the main gist of the function; the rest of the function is
then geared around changing 'result' before the 'return result'
statement.

My way of being friendly to the reader (admittedly, assuming the
reader will read code similar to the way I read it).

--
\ "Sittin' on the fence, that's a dangerous course / You can even |
`\ catch a bullet from the peace-keeping force" -- Dire Straits, |
_o__) _Once Upon A Time In The West_ |
Ben Finney

Sep 1 '06 #20

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

Similar topics

5
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('/',...
9
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...
15
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...
18
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
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
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...
144
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...
52
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...
19
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....
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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...
0
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...
0
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...

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.