Ruff Python Tutorial: Lint and Format in Milliseconds

Quick answer

Ruff is a fast Python linter and formatter written in Rust. It checks your code for errors and unused imports, then rewrites it into a consistent style, and it does both in milliseconds. This post installs Ruff 0.17.6, runs it over a real shop orders script, and fixes the two errors it refuses to fix on its own.

A Python file starts clean and gets messy like a desk: one import added for an experiment and never removed, a variable left behind after a rewrite, a line that grows past the edge of the screen. None of it breaks the program, so nobody fixes it, and the next person to read the file pays for it in confusion. A linter is the tool that catches this drift, and the usual complaint is that linters are slow and noisy. Ruff answers the first complaint directly: the check on the script in this post took 0.010 seconds. The second complaint is fairer, and it is the reason this post shows the run, including the errors Ruff leaves for you.

What I would check before using it

My first check is what Ruff replaces. Most Python projects already run two tools: a linter such as Flake8 and a formatter such as Black. Ruff does both jobs in one binary, fast enough to run on every save. The ESLint Explained: Catching Bugs Before They Run post covers the same idea for JavaScript, and the Prettier: Formatting Code So Nobody Argues About It post covers the formatting half. If your project already runs Flake8 and Black happily, Ruff is a speed upgrade, not a new capability.

My second check is how the team will run it. A linter only helps when it runs before code is merged, not when someone remembers it by hand. Ruff fits the usual places: an editor extension, a pre-commit hook, and a CI step that fails the build on a dirty check. The VS Code Explained: The Editor That Ate the World post covers the editor side, and the GitHub Actions Explained: Automation That Runs on Every Push post covers the CI side. Agree the commands first, then wire them in everywhere at once.

My third check is the rule set. Ruff ships with a small default set; this post switches on the full E and F groups in pyproject.toml. Switching on every rule at once on an old codebase produces hundreds of findings nobody reads, so start with the defaults and add one group at a time.

My verdict, as judgement: adopt Ruff for any Python project you touch weekly. The recommendation flips if the project already passes Flake8 and Black in CI and nobody complains about speed, because then the switch is churn, or if the team will not run it in CI, because then it is decoration.

Six orders, one linter, and the line Ruff would not fix

The demo is a small shop orders script with six orders: Sana and Hamza in Karachi, Daniyal and Ayesha in Lahore, Mahnoor and Bilal in Islamabad. It totals orders by city, prints a grand total, and runs fine, which is the point: Ruff is for code that works but reads badly. The totals use a plain loop; the Python List Comprehensions Explained With Real Examples post shows the shorter way to write the same grouping.

First the install, where the first thing went wrong. The system pip refused outright: the system Python belongs to the operating system, and it will not let pip install packages into it. The fix is a virtual environment with Ruff installed inside it. The config file sits next to the script and switches on the full E and F rule groups, so line length is checked too:

$ pip install ruff
error: externally-managed-environment

× This environment is externally managed
╰─> To install Python packages system-wide, try apt install
    python3-xyz, where xyz is the package you are trying to
    install.

    If you wish to install a non-Debian-packaged Python package,
    create a virtual environment using python3 -m venv path/to/venv.
    Then use path/to/venv/bin/python and path/to/venv/bin/pip. Make
    sure you have python3-full installed.

    If you wish to install a non-Debian packaged Python application,
    it may be easiest to use pipx install xyz, which will manage a
    virtual environment for you. Make sure you have pipx installed.

    See /usr/share/doc/python3.12/README.venv for more information.

note: If you believe this is a mistake, please contact your Python installation or OS distribution provider. You can override this, at the risk of breaking your Python installation or OS, by passing --break-system-packages.
hint: See PEP 668 for the detailed specification.
$ python3 -m venv venv
$ ./venv/bin/pip install ruff
Installing collected packages: ruff
Successfully installed ruff-0.17.6
$ ./venv/bin/ruff --version
ruff 0.17.6
$ ./venv/bin/python --version
Python 3.12.3
[tool.ruff]
line-length = 88

[tool.ruff.lint]
select = ["E", "F"]

Here is the messy file, exactly as written before any linting:

import json
import os


orders = [
    {"city": "Karachi", "customer": "Sana", "total": 9800},
    {"city": "Lahore", "customer": "Daniyal", "total": 13400},
    {"city": "Islamabad", "customer": "Mahnoor", "total": 11200},
    {"city": "Karachi", "customer": "Hamza", "total": 6750},
    {"city": "Lahore", "customer": "Ayesha", "total": 8900},
    {"city": "Islamabad", "customer": "Bilal", "total": 7200},
]
def totals_by_city(orders):
    totals={}
    for order in orders:
        city=order["city"]
        if city not in totals:
            totals[city]=0
        totals[city]+=order["total"]
    return totals


def main():
    discount_rate = 0.1
    city_totals = totals_by_city(orders)
    grand_total = sum(city_totals.values())
    print("Shop orders by city (Rs):")
    for city, total in sorted(city_totals.items()):
        print(f"  {city}: Rs {total:,}")
    print(f"Grand total: Rs {grand_total:,} across {len(orders)} orders, and the shop also ships to Karachi, Lahore and Islamabad every weekday")
    print("Done. ")


if __name__ == "__main__":
    main()

The file runs and the totals are right. Now the check:

$ ./venv/bin/python shop_orders.py
Shop orders by city (Rs):
  Islamabad: Rs 18,400
  Karachi: Rs 16,550
  Lahore: Rs 22,300
Grand total: Rs 57,250 across 6 orders, and the shop also ships to Karachi, Lahore and Islamabad every weekday
Done.
$ ./venv/bin/ruff check shop_orders.py
shop_orders.py:1:8: F401 [*] `json` imported but unused
shop_orders.py:2:8: F401 [*] `os` imported but unused
shop_orders.py:24:5: F841 Local variable `discount_rate` is assigned to but never used
shop_orders.py:30:89: E501 Line too long (145 > 88)
Found 4 errors.
[*] 2 fixable with `--fix` (1 unsafe fix available with `--fix --unsafe-fixes`).

Two unused imports, one unused variable, and one line of 145 characters against a limit of 88. The fix flag handles the easy half:

$ ./venv/bin/ruff check --fix shop_orders.py
Found 4 errors (2 fixed, 2 remaining).
1 unsafe fix available with `--fix --unsafe-fixes`.

$ ./venv/bin/ruff check --output-format=concise shop_orders.py
shop_orders.py:22:5: F841 Local variable `discount_rate` is assigned to but never used
shop_orders.py:28:89: E501 Line too long (145 > 88)
Found 2 errors.
1 unsafe fix available with `--fix --unsafe-fixes`.

The unused variable needs the unsafe flag, because deleting an assignment can change behaviour:

$ ./venv/bin/ruff check --fix --unsafe-fixes shop_orders.py
Found 2 errors (1 fixed, 1 remaining).

$ ./venv/bin/ruff check --output-format=concise shop_orders.py
shop_orders.py:27:89: E501 Line too long (145 > 88)
Found 1 error.

One error left: the long line. Formatting should handle it:

$ ./venv/bin/ruff format --check shop_orders.py
unformatted: File would be reformatted
  --> shop_orders.py:1:1
   -
   -
1  | orders = [
--------------------------------------------------------------------------------
8  | ]
9  +
10 +
11 | def totals_by_city(orders):
   -     totals={}
12 +     totals = {}
13 |     for order in orders:
   -         city=order["city"]
14 +         city = order["city"]
15 |         if city not in totals:
   -             totals[city]=0
   -         totals[city]+=order["total"]
16 +             totals[city] = 0
17 +         totals[city] += order["total"]
18 |     return totals
--------------------------------------------------------------------------------
26 |         print(f"  {city}: Rs {total:,}")
   -     print(f"Grand total: Rs {grand_total:,} across {len(orders)} orders, and the shop also ships to Karachi, Lahore and Islamabad every weekday")
27 +     print(
28 +         f"Grand total: Rs {grand_total:,} across {len(orders)} orders, and the shop also ships to Karachi, Lahore and Islamabad every weekday"
29 +     )
30 |     print("Done. ")
   |

1 file would be reformatted

And here is the surprise: running ruff format wrapped the print call, but the string inside is still 142 characters long, so the check still fails. A formatter moves code around; it does not rewrite your words. The fix is by hand: split the message into two shorter prints.

$ ./venv/bin/ruff format shop_orders.py
1 file reformatted

$ ./venv/bin/ruff check shop_orders.py
E501 Line too long (142 > 88)
  --> shop_orders.py:28:89
   |
26 | …
27 | …
28 | …{len(orders)} orders, and the shop also ships to Karachi, Lahore and Islamabad every weekday"
   |                                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
29 | …
30 | …
   |

Found 1 error.
$ ./venv/bin/ruff check shop_orders.py
All checks passed!

$ ./venv/bin/ruff format --check shop_orders.py
1 file already formatted

$ ./venv/bin/python shop_orders.py
Shop orders by city (Rs):
  Islamabad: Rs 18,400
  Karachi: Rs 16,550
  Lahore: Rs 22,300
Grand total: Rs 57,250 across 6 orders
The shop ships to Karachi, Lahore and Islamabad every weekday
Done.

The totals are unchanged: Karachi Rs 16,550, Lahore Rs 22,300, Islamabad Rs 18,400, a grand total of Rs 57,250. Ruff changed the shape of the file, not the numbers in it.

Terminal output showing pip refusing the system install, Ruff 0.17.6 installed in a virtual environment, ruff check finding 4 errors, and the final run printing All checks passed with shop totals of Rs 57,250.

Common mistakes and how to fix them

First, installing Ruff with the system pip. The symptom is error: externally-managed-environment and a note pointing at PEP 668. The fix is a virtual environment: python3 -m venv venv, then install Ruff inside it.

Second, expecting ruff check --fix to fix everything. The symptom is two errors still standing after the fix run, F841 and E501. The fix is to run ruff check --fix --unsafe-fixes for the unused variable, then fix long lines by hand, because Ruff never rewrites a string for you.

Third, expecting ruff format to clear a line-too-long error. The symptom is E501 still firing after 1 file reformatted. The fix is to shorten the line yourself, by splitting the string or the message, as the demo does.

Fourth, wondering why line length is never flagged. The symptom is a 200 character line passing the check. The fix is a config file: the default rule set does not include E501, so select the E group in pyproject.toml, as this post does.

Frequently Asked Questions

Is Ruff a replacement for Flake8 and Black?

Yes, for most projects. Ruff covers the lint rules Flake8 checks and formats code the way Black does.

Is Ruff free?

Yes. Ruff is free and open source, and the binary runs on Linux, macOS, and Windows.

Why does ruff check pass but ruff format --check fail?

They check different things: ruff check looks for errors such as unused imports, while ruff format --check looks at spacing and layout.

How fast is Ruff in practice?

The check on the script in this post took 0.010 seconds. Ruff is written in Rust and checks files in parallel, so teams run it on every save.

What to remember

  • Ruff lints and formats Python in one binary; the check here took 0.010 seconds.
  • Install it in a virtual environment; the system pip refuses with an externally managed environment error.
  • ruff check --fix handles safe fixes only; F841 needs --unsafe-fixes and E501 needs a fix by hand.
  • ruff format moves code around but never splits a long string.
  • Run both ruff check and ruff format --check in the editor and in CI.

Where this leaves you

Ruff earns its place the first time it catches an unused import before a reviewer does. The demo showed the whole arc: a refused system install, four real errors, two fixed automatically, one removed with an explicit unsafe flag, and one long line that only a human could shorten. The numbers never changed, which is the point: the linter tidies the file without touching what it computes. Install it in a virtual environment, turn on the rules you want, and let it run on every save.

Further reading

Waqas Shahid is a software engineer from Karachi with more than 12 years of experience, including 6+ years in engineering leadership. He writes The Practical Developer.

Comments

Popular posts from this blog

Swift Explained: Apple's Language for iPhone, Mac, and More

LangChain Tutorial: Build Your First LLM App in Python

Rust Explained: Memory Safety Without a Garbage Collector