sourcery-ai / sourcery

Instant AI code reviews
https://sourcery.ai
MIT License
1.53k stars 66 forks source link

Refactoring idea/request: move condition into assertion. #255

Open MinekPo1 opened 2 years ago

MinekPo1 commented 2 years ago

The applicable code snippet is as follows:

if cond:
    assert False, "msg"
# ==>
assert not cond, "msg"

I have encountered this in one of my codebases and while I found it on my own, I feel like it would feel at home in the library of refactorings, removing some branching and, in general, make the code more readable.

Some reasons this can occur:

MinekPo1 commented 2 years ago

Oh, another variation I though off, that's essentially the same thing:

if cond:
    raise AssertionError("msg")
# ==>
assert not cond, msg
MinekPo1 commented 2 years ago

Here is an example (in my code >-<) I found. Not the original one, but I'll have tp fix that one too.

bm424 commented 2 years ago

Hi @MinekPo1, thanks for the suggestion! I'll add it to our refactoring pipeline.

By the way, check out our documentation for Custom Rules. Although I think your suggestion is a good one to include in core Sourcery, until then you can enforce this on your own code base using custom rules..

MinekPo1 commented 2 years ago

you can enforce this on your own code base using custom rules

Oh I assumed custom rules were a teams only feature. Good to know!

Edit: It is stated as a teams only feature on your pricing page

MinekPo1 commented 2 years ago

Also for anyone who wants to use this before this goes through the pipeline, here is the custom rule:

- id: move-condition-into-assertion
  description: Move condition into assertion.
  pattern: |
    if ${condition}:
      assert False, ${message?}
  replacement: assert not ${condition}, ${message}