Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should i always use 'else:' even it is not necessary? [closed]

Tags:

python

Am i must to use here else: or i have opportunity to remove it and just type return True

def some_function(x):
  if another_function(x) == -1:
    return False
  else:
    return True

EDIT: I know how to make this code compact with just one return. The main question is about else:.

like image 943
glmn Avatar asked Dec 31 '22 17:12

glmn


1 Answers

Should i always use 'else:' even it is not necessary?

I myself believe that they are not necessary. Returning at the beginning of the function in case of edge cases is something that allows you to skip sometimes lots of indentations caused by elses:

def some_function(x):
    if edge_case_1:
        return []
    if edge_case_2:
        return None

    #a
    #lot
    #of
    #code
    #here

    return result

looks better than

def some_function(x):
    if edge_case_1:
        return []
    elif edge_case_2:
        return None
    else:
        #a
        #lot
        #of
        #code
        #here

        return result

right?

But it's not only about the looks:

  • Elses like that make you easily confuse the indentation levels.
  • The line width becomes smaller because the indentation takes those few character, you might need to format your code more to fit PEP8.
  • Sometimes you write the main part of the code first, only to discover the edge cases later. Version control systems such as git would mark all indented lines as changed (depending on the configuration), while the only thing you did was add those ifs at the beginning!
like image 191
h4z3 Avatar answered Feb 01 '23 12:02

h4z3