sourcery icon indicating copy to clipboard operation
sourcery copied to clipboard

Refactoring idea/request: move condition into assertion.

Open MinekPo1 opened this issue 3 years ago • 5 comments

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:

  • there used to be code before the assert (cleanup code or message generating the message for example)
  • some metaprogramming with assertions (tests or custom errors as an example)

MinekPo1 avatar Jul 17 '22 23:07 MinekPo1

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

if cond:
    raise AssertionError("msg")
# ==>
assert not cond, msg

MinekPo1 avatar Jul 17 '22 23:07 MinekPo1

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

MinekPo1 avatar Jul 17 '22 23:07 MinekPo1

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..

bm424 avatar Jul 18 '22 09:07 bm424

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 avatar Jul 19 '22 16:07 MinekPo1

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}

MinekPo1 avatar Jul 19 '22 16:07 MinekPo1