Unnecessary "else" after "return", remove the "else" and de-indent the code inside it
148 """Enable the auto merge"""
149 sub_run.update(title="Enabling auto-merge", status=CheckRunStatus.IN_PROGRESS)
150 default_branch = repository.get_branch(repository.default_branch)
151 if default_branch.protected:152 if pull_request := pull_request_helper.get_existing_pull_request(
153 repository, branch_name
154 ):
Unnecessary "else" after "return", remove the "else" and de-indent the code inside it
127) -> bool:
128 """Enable the auto merge if is enabled and is not the default branch"""
129 if Config.pull_request_manager.enable_auto_merge:
130 if branch == repository.default_branch:131 ignoring_title = f"In the default branch '{branch}', ignoring."
132 sub_run.update(
133 title=ignoring_title,
Unnecessary "else" after "return", remove the "else" and de-indent the code inside it
67) -> bool:
68 """Try to create a Pull Request if is enabled and is not the default branch"""
69 if Config.pull_request_manager.create_pull_request:
70 if branch == repository.default_branch: 71 ignoring_title = f"In the default branch '{branch}', ignoring."
72 sub_run.update(
73 title=ignoring_title,
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'