Warn on Unassigned `==` Expression as Statement
Affects | Status | Importance | Assigned to | Milestone | |
---|---|---|---|---|---|
Pyflakes |
New
|
Undecided
|
Unassigned |
Bug Description
Working with some NumPy code recently, I accidentally wrote this:
<build output array>
<build mask array>
out[mask] == NaN # This should have been a single `=`, not a ==.
return out
After a few minutes of debugging my NaN-less array, I realized that I had accidentally written `==` instead of `=`, turning my assignment statement into no-op comparison operator.
I'd be nice if PyFlakes gave a warning for a statement that's just an expression performing an equality comparison. There are very few cases where I'd expect that something like this is doing what the author intended.
A more aggressive version of this check would be to warn on any expression that's just a binary operator. The assumption there would be that the "statement" `a + b` is at best dead code, and at worst an operator with a highly non-obvious side-effect.
I'd be happy to work on either version of this if there's support for it.
description: | updated |
A minimal fix detecting ast.Compare within ast.Expr is simple.
After a little playing, I think the best vector to approach this is to add checking of ast.Expr children nodes.
Expr is a fallback node type, only occurring when Assign, If, etc are not present. Generally speaking, Expr means an unused expression.
There are a few cases where it is needed, such as docstrings (Str), yield, Call being the main one, some dubious cases like Attribute and Name which should have side effects but often do, and then all binary, bool and compare ops which should ever be found in an Expr context.
One significant problem is the pyflakes test suite extensively uses code snippets that include unused expressions so the snippet is simple, so a good fix will need to alter lots of tests so the code tested is more like real code.