-
Notifications
You must be signed in to change notification settings - Fork 1.2k
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
needless bool for needless-bool #15323
Comments
We need to be careful here! If we can say for sure that both the left-hand side and the right-hand side is of type >>> 5 and 42
42 Perhaps you might say that we can say for sure that equality comparisons will always evaluate to a >>> class Foo:
... def __eq__(self, other):
... return 42
...
>>> Foo() == Foo() and Foo() == Foo()
42 |
Excellent point! We can at least add in the cases where ruff's semantic model can infer the type as bool (which will be fairly limited, and I think will not include the example in this issue due to the function call). |
In fact, here is a case where the autofix is wrong because it doesn't cast to bool: import numpy as np
def f(x:np.ndarray,y:np.ndarray):
if x<y:
return True
else:
return False gets fixed to import numpy as np
def f(x:np.ndarray,y:np.ndarray):
return x < y Arguably comparison operators are more likely to produce false positives than boolean operators like In any event the fix is marked as unsafe... so there's a question of whether we should be restricting the fix behavior further, extending it (as in the OP), or some mixture (eg avoiding comparison operators but allowing boolean operators). I'm gonna push a few different versions and see what the ecosystem check reveals and then maybe we can discuss further. (Assuming the ecosystem check will tell me anything... I remember we made a change recently around what it does with fix behavior...) |
Right. We could also take whether or not the function is explicitly annotated into consideration, possibly? In untyped code, there's maybe not much of a difference between returning something truthy and something that is the literal |
Python's boolean handling never ceases to surprise! I see what you mean about being careful. Feel free to close this. |
Function to check random numbers:
Raises warning
SIM103 Return the condition directly
. Good. Fix with--unsafe-fixes --fix
:Multi-return
if
/else
expression replaced with boolean expression. Good. But also wrapped withbool
cast. Bad!bool
cast of a boolean expression is unnecessary.The text was updated successfully, but these errors were encountered: