Calmcode - ruff: base usage

Using Ruff

1 2 3 4 5

Install

If you haven't done so already, making sure that ruff in installed.

python -m pip install ruff

Give ruff a spin

So let's give Ruff a quick spin just to get started. Suppose that we have this script.

import itertools as it
from numpy import *

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

This code will generate and print some fibonachi numbers for us on the command line. But it also does some extra things that are a bad practice like importing packages that we're not using and importing with a *.

So let's see what Ruff makes of this. You can do that by calling

ruff check script.py

When you run this, you'll see the following errors.

script.py:1:1: I001 [*] Import block is un-sorted or un-formatted
script.py:1:21: F401 [*] `itertools` imported but unused
script.py:2:1: F403 `from numpy import *` used; unable to detect undefined names
script.py:9:18: W291 [*] Trailing whitespace
Found 4 errors.
[*] 3 fixable with the `--fix` option.

Notice that message at the end? We can also ask ruff to attempt a fix by passing the --fix flag.

ruff check --fix script.py

When we run this, the output is different.

script.py:1:1: F403 `from numpy import *` used; unable to detect undefined names
Found 4 errors (3 fixed, 1 remaining).

It was able to fix three of the errors, but one error requires manual intervention. So we can remove the from numpy import * line such that the final output looks like this:

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

When you now run the ruff script, you'll see no message which indicates that no issues were found.