Add B044: assert <generator_expression>#535
Conversation
d7cefd1 to
8823634
Compare
There was a problem hiding this comment.
Pull request overview
This PR adds a new flake8-bugbear check B044 to detect assert <generator_expression> patterns, which are always truthy and likely indicate a bug where the developer forgot to wrap the generator in all() or any().
Key Changes:
- Adds check B044 to detect generator expressions used directly in assert statements
- Includes test cases covering generator expressions and other comprehension types
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
| tests/eval_files/b044.py | Adds test cases for B044 check, including positive case (generator expression) and negative cases (list/set/dict comprehensions) |
| bugbear.py | Implements check_for_b044() method, integrates it into visit_Assert(), and defines the B044 error message |
| README.rst | Documents the new B044 check and adds changelog entry |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| assert (x for x in a) # B044: 0 | ||
| assert [x for x in a] | ||
| assert {x for x in a} | ||
| assert {x: y for x, y in a} |
There was a problem hiding this comment.
The test file should include a test case for assert <generator_expression>, "message" to ensure the check works correctly when the assert statement includes an error message. This is a common pattern in assertions and should be tested, similar to how B011 tests both assert False and assert False, "message".
| assert (x for x in a) # B044: 0 | ||
| assert [x for x in a] | ||
| assert {x for x in a} | ||
| assert {x: y for x, y in a} |
There was a problem hiding this comment.
Consider adding test cases for edge cases such as:
- Nested generator expressions:
assert (x for x in (y for y in a)) - Generator expressions in boolean context with 'and'/'or':
assert some_condition and (x for x in a) - Generator expressions with conditions:
assert (x for x in a if x > 0)
These scenarios would help ensure the check correctly identifies all problematic patterns.
|
I wonder if it would make sense to broaden this into asserts with other constructs that we can statically detect will always be true, such as nonempty list literals. |
Closes #534.