Skip to content

Commit

Permalink
refactor: refactor unnecessary else / elif when if block has a …
Browse files Browse the repository at this point in the history
…`raise` statement (#1485)

`raise` causes control flow to be disrupted, as it will exit the block.
It is recommended to check other conditions using another `if` statement, and get rid of `else` statements as they are unnecessary.

Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com>
  • Loading branch information
deepsource-autofix[bot] authored Dec 15, 2024
1 parent a555d59 commit f80baff
Show file tree
Hide file tree
Showing 10 changed files with 36 additions and 46 deletions.
17 changes: 8 additions & 9 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,15 +183,14 @@ def restart_process(bot_name: str):
f"{p.pid} ({p.name}) exited with code 233, restart all bots."
)
raise RestartBot
else:
Logger.critical(
f"Process {p.pid} ({p.name}) exited with code {p.exitcode}, please check the log."
)
processes.remove(p)
p.terminate()
p.join()
p.close()
restart_process(p.name)
Logger.critical(
f"Process {p.pid} ({p.name}) exited with code {p.exitcode}, please check the log."
)
processes.remove(p)
p.terminate()
p.join()
p.close()
restart_process(p.name)
break

if not processes:
Expand Down
17 changes: 8 additions & 9 deletions core/builtins/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,16 +78,15 @@ async def trigger(module_or_hook_name: str, args):
return

raise ValueError(f"Invalid module name {module_or_hook_name}")
else:
if module_or_hook_name:
if module_or_hook_name in ModulesManager.modules_hooks:
await asyncio.create_task(
ModulesManager.modules_hooks[module_or_hook_name](
Bot.FetchTarget, ModuleHookContext(args)
)
if module_or_hook_name:
if module_or_hook_name in ModulesManager.modules_hooks:
await asyncio.create_task(
ModulesManager.modules_hooks[module_or_hook_name](
Bot.FetchTarget, ModuleHookContext(args)
)
return
raise ValueError(f"Invalid hook name {module_or_hook_name}")
)
return
raise ValueError(f"Invalid hook name {module_or_hook_name}")


class FetchedSession(FetchedSession):
Expand Down
3 changes: 1 addition & 2 deletions core/parser/args.py
Original file line number Diff line number Diff line change
Expand Up @@ -361,5 +361,4 @@ def parse_argv(argv: List[str], templates: List["Template"]) -> MatchedResult:
return priority_result[max_][0]
if len_filtered_result == 0:
raise InvalidCommandFormatError
else:
return filtered_result[0]
return filtered_result[0]
15 changes: 7 additions & 8 deletions core/parser/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,14 +105,13 @@ def parse(self, command):
if len(arg.args) == 1 and isinstance(arg.args[0], DescPattern):
return self.args[arg]["meta"], None
raise InvalidCommandFormatError
else:
base_match = parse_argv(
split_command[1:], [args for args in self.args if args != ""]
)
return (
self.args[base_match.original_template]["meta"],
base_match.args,
)
base_match = parse_argv(
split_command[1:], [args for args in self.args if args != ""]
)
return (
self.args[base_match.original_template]["meta"],
base_match.args,
)

except InvalidCommandFormatError:
traceback.print_exc()
Expand Down
10 changes: 4 additions & 6 deletions core/utils/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,9 +109,8 @@ async def get_():
if hasattr(req, fmt):
return await getattr(req, fmt)()
raise ValueError(f"NoSuchMethod: {fmt}")
else:
text = await req.text()
return text
text = await req.text()
return text
except asyncio.exceptions.TimeoutError:
raise ValueError("Request timeout")
except Exception as e:
Expand Down Expand Up @@ -185,9 +184,8 @@ async def _post():
if hasattr(req, fmt):
return await getattr(req, fmt)()
raise ValueError(f"NoSuchMethod: {fmt}")
else:
text = await req.text()
return text
text = await req.text()
return text
except asyncio.exceptions.TimeoutError:
raise ValueError("Request timeout")
except Exception as e:
Expand Down
2 changes: 1 addition & 1 deletion modules/coin/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ async def flip_coins(count: int, msg: Bot.MessageSession):
]
):
raise ConfigValueError(msg.locale.t("error.config.invalid"))
elif count > MAX_COIN_NUM:
if count > MAX_COIN_NUM:
return msg.locale.t("coin.message.invalid.out_of_range", max=MAX_COIN_NUM)
elif count < 0:
return msg.locale.t("coin.message.invalid.amount")
Expand Down
3 changes: 1 addition & 2 deletions modules/maimai/libraries/maimaidx_apidata.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,8 +204,7 @@ async def get_song_record(
except Exception as e:
if str(e).startswith("400"):
raise ConfigValueError(msg.locale.t("error.config.invalid"))
else:
Logger.error(traceback.format_exc())
Logger.error(traceback.format_exc())
if use_cache and os.path.exists(cache_dir):
try:
with open(cache_dir, "r", encoding="utf-8") as f:
Expand Down
7 changes: 3 additions & 4 deletions modules/mkey/generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ def _detect_algorithm(self, device, inquiry):
if "v0" in algorithms:
return "v0"
raise ValueError("v0 algorithm not supported by %s." % device)
elif len(inquiry) == 10:
if len(inquiry) == 10:
version = int((int(inquiry) / 10000000) % 100)

if "v1" in algorithms and version < 10:
Expand All @@ -176,12 +176,11 @@ def _detect_algorithm(self, device, inquiry):
if "v3" in algorithms:
return "v3"
raise ValueError("v1/v2/v3 algorithms not supported by %s." % device)
elif len(inquiry) == 6:
if len(inquiry) == 6:
if "v4" in algorithms:
return "v4"
raise ValueError("v4 algorithm not supported by %s." % device)
else:
raise ValueError("Inquiry number must be 6, 8 or 10 digits.")
raise ValueError("Inquiry number must be 6, 8 or 10 digits.")

# CRC-32 implementation (v0).
@staticmethod
Expand Down
3 changes: 1 addition & 2 deletions modules/osu/profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,7 @@ async def osu_profile(msg: Bot.MessageSession, uid, mode):
except ValueError as e:
if str(e).startswith('401'):
raise ConfigValueError(msg.locale.t("error.config.invalid"))
else:
raise e
raise e
except Exception:
Logger.error(traceback.format_exc())
await msg.finish(msg.locale.t('osu.message.not_found'))
Expand Down
5 changes: 2 additions & 3 deletions modules/osu/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,8 @@ async def get_profile_name(msg: Bot.MessageSession, uid):
except ValueError as e:
if str(e).startswith("401"):
raise ConfigValueError(msg.locale.t("error.config.invalid"))
else:
Logger.error(traceback.format_exc())
return False
Logger.error(traceback.format_exc())
return False
except BaseException:
return False

Expand Down

0 comments on commit f80baff

Please sign in to comment.