Unnecessary "else" after "return", remove the "else" and de-indent the code inside it
305def get_conf(request):
306 request_conf = get_request_conf(request)
307
308 if request_conf:309 return request_conf
310 else:
311 return get_settings_conf()
Unnecessary "elif" after "return", remove the leading "el" from "elif"
158 raise Exception('Database configuration is not set')
159
160 def get_engine():
161 if conf.get('engine') == 'sqlite':162 return create_engine(engine_url)
163 elif conf.get('engine') == 'bigquery':
164 return create_engine(
Unnecessary "else" after "return", remove the "else" and de-indent the code inside it
146 connection_params_id = get_connection_params_id(conf)
147
148 if connection_id in connections:
149 if connections[connection_id]['params_id'] == connection_params_id:150 return connections[connection_id]
151 else:
152 disconnect_database(conf)
Description
The use of else
or elif
becomes redundant and can be dropped if the last statement under the leading if
/ elif
block is a return
statement.
In the case of an elif
after return
, it can be written as a separate if
block.
For else
blocks after return
, the statements can be shifted out of else
. Please refer to the examples below for reference.
Refactoring the code this way can improve code-readability and make it easier to maintain.
Bad practice
def classify_number(x):
if x % 2 == 0:
return 'Even'
else:
return 'Odd'
def what_is_this_number(x):
if x % 2 == 0 and x >= 0:
return 'Even'
elif x % 2 == 0 and x < 0:
return 'Even and Negative'
elif x % 2 != 0 and x < 0:
return 'Odd and Negative.'
else:
return 'Odd'
Preferred:
def classify_number(x):
if x % 2 == 0:
return 'Even'
return 'Odd'
def what_is_this_number(x):
if x % 2 == 0 and x >= 0:
return 'Even'
if x % 2 == 0 and x < 0:
return 'Even and Negative'
if x % 2 != 0 and x < 0:
return 'Odd and Negative'
return 'Odd'