Calmcode - ruff: configuration

Configuring Ruff

1 2 3 4 5

Let's have a look at our script again.

def fibonachi(s1, s2, n):
    result = [s1 , s2]
    for i in range(n):
        s1, s2 = s2, s1 + s2
        result.append(s2)
    return result 

if __name__ == "__main__":
    print(fibonachi(1, 1, 10))

It's certainly better compared to what we started with, but you could also argue that it is not exactly perfect either. Just to mention a few things:

  • The function does not have a docstring, so documentation is missing.
  • The input arguments do not have types attached.
  • The i variable in our for-loop isn't being used, so it shouldn't be declared as a variable.

The reason why ruff isn't complaining about these is because ruff isn't configured to check for any of these just yet. It defaults to a limited set of rules to check and if we want to check for more we need to configure it. So lets start by configuring the docstring warnings. To configure that, it may help to look at the docs about rules.

Configure Ruff

So let's create a ruff.toml file. Here's one:

[lint]
select = ["D"]

This configures ruff to use all the linting rules against your code. You may not be interested in running all the checks, but it would be good to see what happens to our code now.

ruff check script.py

This gives the following output:

warning: `one-blank-line-before-class` (D203) and `no-blank-line-before-class` (D211) are incompatible. Ignoring `one-blank-line-before-class`.
warning: `multi-line-summary-first-line` (D212) and `multi-line-summary-second-line` (D213) are incompatible. Ignoring `multi-line-summary-second-line`.
demo.py:1:1: D100 Missing docstring in public module
demo.py:1:5: D103 Missing docstring in public function
  |
1 | def fibonachi(s1, s2, n):
  |     ^^^^^^^^^ D103
2 |     result = [s1 , s2]
3 |     for i in range(n):
  |

Found 2 errors.

Notice how we turned on so enough checks that we also get incompatability warnings? This is one of the main reasons why you might want to be picky about which checks you add. We can, however, easily turn off some of the checks manually if we do not want to see these warning messages.

[lint]
select = ["D"]
ignore = ["D211", "D213"]

Now when we run ruff, we don't see the warnings anymore and we see valid items to fix.

demo.py:1:1: D100 Missing docstring in public module
demo.py:1:5: D103 Missing docstring in public function
  |
1 | def fibonachi(s1, s2, n):
  |     ^^^^^^^^^ D103
2 |     result = [s1 , s2]
3 |     for i in range(n):
  |

Found 2 errors.