15

I actually use Python and Flask for my devblog. I know that depending of the language, it is advisable to use a explicit else when it is not obligatory, but I don't know how it's work in Python.

By example, I have a a function with a if that return something if the statement is true. So, The else is not necessary because with or without it, the execution continue normally.

def foo(bar):
    if not isinstance(foo, list):
        return "an error"
    else: # not necessary 
        return "something"

So, I should use it like this, or like :

def foo(bar):
    if not isinstance(foo, list):
        return "an error"

    return "something"
vildric
  • 910
  • 1
  • 8
  • 22
  • 1
    I [almost] always "mirror" the execution paths - the exception is quickly throwing an exception :D (Which is different from returning a value.) This is mostly a styling choice (i.e. *Not Constructive*), but I contend that it makes "the actual paths" more distinguished and can prevent some silly mistakes. –  Feb 13 '13 at 00:39
  • 1
    I don't think it's a matter of the language but of coding style. So the answer could be: whatever you find more readable. – madth3 Feb 13 '13 at 00:40
  • 1
    Personally I prefer the first for symmetry or a third way which would be to assign a return value in each branch and then have a single `return retvalue` at the end. One slight advantage of _not_ using an `else` or `elif` besides it being an extra line to type, is when you have more than two, it's easier to delete or add one anywhere you want in the chain. Generally I don't believe there's much difference performance-wise. – martineau Feb 13 '13 at 00:49
  • possible duplicate of [If-Else-Return or just if-Return?](http://stackoverflow.com/questions/9191388/if-else-return-or-just-if-return) – Andy Hayden Feb 13 '13 at 01:29
  • Thank you for your answer, I will use `if... return...return` instead of `if...return...else...return` because I am lazy. :D – vildric Feb 13 '13 at 01:44

5 Answers5

7

In the first case, Python will add an explicit return None to the end of the function - even though we can see it's not really needed. In the second case it doesn't.

I don't see any advantage to having the else: there

>>> import dis
>>> def f():
...  if 1>2:
...   return 2
...  return 3
... 
>>> def g():
...  if 1>2:
...   return 2
...  else:
...   return 3
... 
>>> dis.dis(f)
  2           0 LOAD_CONST               1 (1)
              3 LOAD_CONST               2 (2)
              6 COMPARE_OP               4 (>)
              9 POP_JUMP_IF_FALSE       16

  3          12 LOAD_CONST               2 (2)
             15 RETURN_VALUE        

  4     >>   16 LOAD_CONST               3 (3)
             19 RETURN_VALUE        
>>> dis.dis(g)
  2           0 LOAD_CONST               1 (1)
              3 LOAD_CONST               2 (2)
              6 COMPARE_OP               4 (>)
              9 POP_JUMP_IF_FALSE       16

  3          12 LOAD_CONST               2 (2)
             15 RETURN_VALUE        

  5     >>   16 LOAD_CONST               3 (3)
             19 RETURN_VALUE        
             20 LOAD_CONST               0 (None)
             23 RETURN_VALUE        
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
4

This has already been discussed here: If-Else-Return or just if-Return?

Essentially, the two forms are equivalent in terms of efficiency because the machine has to make a jump anyway. So it boils down to coding style and you'll have to decide that on your own (or with your team).

Personally, I prefer with the else statement for readability.

Community
  • 1
  • 1
WLin
  • 1,394
  • 10
  • 14
1

It really makes no difference. Either way will do the same thing.

I prefer the latter, because it's one less line of code.

Je préfère cette dernière

jgritty
  • 11,660
  • 3
  • 38
  • 60
  • The [PEP 8 Style guide](http://www.python.org/dev/peps/pep-0008/) has examples that lean towards that method as well. – Bill Lynch Feb 13 '13 at 00:41
  • @sharth However, PEP 8 "example" shows throwing an exception, not returning. In addition, it is not drawn out, and thus I would hate to consider it part of the "canon" in PEP 8. –  Feb 13 '13 at 00:42
  • 1
    I also lean towards the latter and phrase a lot of my conditionals like that to cut back on excess indentation. – Kiirani Feb 13 '13 at 00:44
  • @Kiirani I "fix" that by avoiding functions that are too complex. I have prefer branches (in every language I use, with the occasional exception exception) and I can't recall the last time I was overrun with indentation .. maybe if using 8-space indents .. but *ick!* :D –  Feb 13 '13 at 00:46
  • @pst Restructuring is not always possible, and I probably have a lower tolerance for indentation levels than you :P (not everyone peruses code in an 80x24 terminal window on a semi regular basis..) – Kiirani Feb 13 '13 at 00:51
  • @Kiirani 3 levels deep (inside a function) is about my "max happy" number. –  Feb 13 '13 at 00:52
1

From Chromium's style guide:

Don't use else after return:

# Bad
if (foo)
  return 1;
else
   return 2;

# Good
if (foo)
  return 1;
return 2;

return foo ? 1 : 2;
skeller88
  • 4,276
  • 1
  • 32
  • 34
0

I am quite new to programming, and in the context of this question I was reminded that there is often the case where I am not sure if I should use an "else" or "elif", e.g., in a scenario like that.

1)

if numA < numB:
    print('numA is smaller')
elif numB < numA:
    print('numB is smaller')
else:
    print('both numbers are equal')

2)

 if numA < numB:
        print('numA is smaller')
 elif numB < numA:
        print('numB is smaller')
 elif numA == numB:
        print('both numbers are equal')

I think it would not make a huge difference, or am I wrong? In other examples the second variant might be more "robust" in general, I think.

  • 1
    I would contend that the 2nd example is "bad" - it is a mild form of [But.. Anything Can Happen!](http://thedailywtf.com/Articles/ButAnything-Can-Happen!.aspx) I have seen situations where redundant[-seeming] checks cause incorrect results if one is updated while others are not. –  Feb 13 '13 at 03:01
  • Thanks, that's a nice article. However, I am just wondering what the mistake is, maybe I am too tired, but is it the `else if (a > 10` which is wrong, and something like `a >= 10` should be used? Since nothing would happen if a == 10? –  Feb 13 '13 at 03:17
  • Given sane ordering: `x < y || y < x`, more clearly written as `x < y || x > y`, is true *except* when `x == y`. This makes the last equality redundant. Consider the simpler case of `if a: .. elif !a: ..`; why write in `!a` instead of the much more clear `if a: .. else: ..`? In the latter case, with the `else` it's very easy to see that *at least one* branch will execute. Otherwise, we have to manually consider an additional expression and then *reason* that it will always hold if the previous did not. –  Feb 13 '13 at 03:21