16

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"
5
  • 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.
    – user166390
    Feb 13, 2013 at 0: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, 2013 at 0: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, 2013 at 0:49
  • possible duplicate of If-Else-Return or just if-Return? Feb 13, 2013 at 1: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, 2013 at 1:44

5 Answers 5

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        
5

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.

1
  • Sorry for the duplicate, I had not seen it even if I had search before to post.
    – vildric
    Feb 13, 2013 at 1:41
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

6
  • The PEP 8 Style guide has examples that lean towards that method as well.
    – Bill Lynch
    Feb 13, 2013 at 0: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.
    – user166390
    Feb 13, 2013 at 0: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, 2013 at 0: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
    – user166390
    Feb 13, 2013 at 0: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, 2013 at 0:51
1

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.

3
  • 1
    I would contend that the 2nd example is "bad" - it is a mild form of But.. Anything Can Happen! I have seen situations where redundant[-seeming] checks cause incorrect results if one is updated while others are not.
    – user166390
    Feb 13, 2013 at 3: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?
    – user2015601
    Feb 13, 2013 at 3: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.
    – user166390
    Feb 13, 2013 at 3:21
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;

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.