Is it preferable to use "else" in Python when it is not needed?

I am using Python and Flask for my devblog. I know that depending on the language, it is recommended to use explicit elsewhen it is not necessary, but I do not know how it works in Python.

For example, I have a function c ifthat returns something if the statement is true. Therefore, elseit is not required since execution with it or without it is performed normally.

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

So, I have to use it like this: or

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

    return "something"
+5
source share
5 answers

In the first case, Python will add an explicit return Nonefunction to the end - even if we see that it really is not necessary. In the second case, this is not so.

else:

>>> 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        
+3

: If-Else-Return if-Return?

, , . , , ( ).

else .

+2

. .

, .

Je préfère cette dernière

+1

, , , , "else" "elif", , , .

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 will not matter much, or am I mistaken? In other examples, I think the second option may be more "reliable."

0
source

From the Chromium Style Guide :

Do not use else after returning:

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

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

return foo ? 1 : 2;
0
source

All Articles