New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
consider-combining-ifs
checker to suggest simplification of code with imbricated ifs
#5414
Comments
Some details to be aware of. I noticed them while review some code.
def func():
for i in range(5):
if some_condition():
if some_other_condition():
return # same for 'break' and 'continue'
do_something_else()
if name in some_list:
if some_function() or not (
some_condition
and some_other_condition
):
pass
# "new"
if name in some_list and (
some_function() or not (
some_condition
and some_other_condition
)
):
pass
|
There is also the issue that someone might explicitly want to use separate The more I think about this check, the more I lean towards it being an optional one. There are just too many caveats (unfortunately). |
Just a note that Pierre's rewriting of the second example with def initial():
# Here we call `as_string()` on each item, and call `isinstance` only
# on items for which the first check is true.
return any(
isinstance(a, nodes.If)
for a in ancestors
if a.test.as_string() in TYPING_TYPE
)
def transformed_wrong(): # Pierre's rewriting
# Here it's different: we call `isinstance()` on each item, and call
# `as_string()` only on items for which the first check is true.
return any(
isinstance(a, nodes.If) and a.test.as_string() in TYPING_TYPE
for a in ancestors
)
def transformed_right():
# Like above, but invert `and` operands to mimic the initial behaviour.
return any(
a.test.as_string() in TYPING_TYPE and isinstance(a, nodes.If)
for a in ancestors
) It's probably harmless here with (For what it's worth, I agree with cdce8p's comment above. It looks like it's not obvious that we can always simplify these conditions.) |
Closing as it seems there's a lot of use case where it's not self evident it's better. |
Current problem
The following code:
Can be simplified to:
The following code:
Can be simplified to:
Desired solution
A new checker suggesting to combine the ifs to simplify the code.
Additional context
Original proposition by @DanielNoord
The text was updated successfully, but these errors were encountered: