Ruff: The Blazing Fast Python Linter and Formatter That Replaces Many Tools

# Ruff: Linter dan Formatter Python Super Cepat yang Menggantikan Banyak Tool Halo temen-temen, kali ini kita bahas tool yang bikin hidup developer Python jauh lebih enak, namanya Ruff. Kalau proyek...

By Ruby Abdullah · · tutorial
ruffpythonlintingcode-qualitydeveloper-tools

Ruff: The Blazing Fast Python Linter and Formatter That Replaces Many Tools

Hey everyone, today we cover a tool that makes Python development noticeably more pleasant: Ruff. If your project currently uses Flake8 for linting, Black for formatting, isort for import ordering, pyupgrade for syntax modernization, and a handful of other plugins, Ruff can replace all of them with one tool that runs hundreds of times faster.

The speed claim is not marketing. Ruff is written in Rust, and on a large codebase with tens of thousands of lines it finishes in tens of milliseconds where Flake8 takes tens of seconds. A difference that large changes how you work: linting that used to run occasionally in CI can now run every time you save a file.

We will cover installation, sensible configuration, choosing rules, formatting, editor and pre-commit integration, migration from older tools, and finally how to adopt it gradually in a large messy codebase.

Introduction

Why Speed Matters

This is not merely about saving time. Speed changes behavior.

If your linter takes thirty seconds, you will not run it every minute. You run it before committing, or only in CI. That means you find problems long after writing them, when the context has left your head.

If your linter takes fifty milliseconds, your editor can run it on every keystroke. You see problems as you create them and fix them in seconds. That difference is felt daily.

What Ruff Replaces

Ruff reimplements hundreds of rules from popular tools: Flake8 and dozens of its plugins, isort, pydocstyle, pyupgrade, autoflake, eradicate, flake8-bugbear, flake8-comprehensions, flake8-simplify, and many more. Its formatter is Black compatible, so the output is nearly identical.

What Ruff does not replace is a type checker such as mypy or pyright. Ruff is a linter, analyzing code without deep type inference. You still need a type checker alongside it.

Installation

pip install ruff

Or with uv, which I recommend since it comes from the same team:

uv tool install ruff

Verify:

ruff --version

Basic Usage

There are two commands you need to know.

# Linting: find problems

ruff check .

Linting with automatic fixes

ruff check --fix .

Formatting: clean up layout

ruff format .

See what would change without changing it

ruff format --diff .

Note the separation of responsibilities. ruff check finds logic and style issues that can be analyzed, while ruff format handles layout such as line length and bracket placement. The two are designed to cooperate rather than fight.

Try it on your project right now. If this is your first run, brace yourself, the output can be long.

Configuration

Ruff is configured through pyproject.toml or a dedicated ruff.toml. I recommend pyproject.toml so all project configuration lives in one place.

[tool.ruff]

Target Python version, affects syntax modernization rules

target-version = "py311"

line-length = 100

indent-width = 4

Directories that do not need checking

exclude = [

".venv",

"venv",

"migrations",

"build",

"dist",

"pycache",

]

[tool.ruff.lint]

select = [

"E", # pycodestyle errors

"W", # pycodestyle warnings

"F", # pyflakes, the most important group

"I", # isort, import ordering

"B", # flake8-bugbear, common bugs

"C4", # flake8-comprehensions

"UP", # pyupgrade, syntax modernization

"SIM", # flake8-simplify

"RUF", # Ruff specific rules

]

ignore = [

"E501", # line length, let the formatter handle it

"B008", # function call in default argument, common in FastAPI

]

Rules allowed to be auto-fixed

fixable = ["ALL"]

unfixable = ["F401"] # do not auto-remove imports, sometimes intentional

[tool.ruff.lint.per-file-ignores]

"init.py" = ["F401"] # re-exports are legitimate here

"tests/*/.py" = ["S101"] # assert is fine in tests

"scripts/*.py" = ["T201"] # print is fine in scripts

[tool.ruff.lint.isort]

known-first-party = ["myapp"]

combine-as-imports = true

[tool.ruff.format]

quote-style = "double"

indent-style = "space"

skip-magic-trailing-comma = false

line-ending = "auto"

Let me explain the important choices above.

select decides which rule groups are active. Ruff has more than 800 rules, and enabling all of them will drown you. The list above is my starting point on nearly every project: F catches real bugs like undefined names, B catches subtle common mistakes, UP modernizes old syntax automatically, and I sorts imports.

I disable E501 deliberately because line length is the formatter's job. With both active you get frequent warnings on lines the formatter genuinely cannot shorten, such as long URLs in comments.

per-file-ignores is very useful. An init.py legitimately contains imports that are never used locally because their purpose is re-export. Declaring the exception here beats scattering noqa comments throughout the code.

Understanding Rule Codes

Every rule has a code like F401 or B008. The letter prefix indicates its origin.

E and W come from pycodestyle, covering basic style. F comes from pyflakes, the most important group because it catches real errors such as undefined variables, unused imports, and f-strings without placeholders. B comes from flake8-bugbear, catching patterns that are technically valid but almost always bugs. My favorite is B006, warning about mutable default arguments, a classic Python trap that has claimed many victims. UP comes from pyupgrade, rewriting old syntax into modern form. For instance Dict[str, int] becomes dict[str, int], and % formatting becomes f-strings. SIM comes from flake8-simplify, suggesting simplifications such as turning if x == True into if x.

To read the explanation of a rule:

ruff rule F401

ruff rule B006

This prints a full explanation with wrong and right code examples. I often use it to teach new team members why a pattern is problematic.

Formatting

Ruff's formatter is designed to be Black compatible, so if your team already uses Black the transition is seamless.

ruff format .

ruff format --check . # for CI, fails if anything is unformatted

One meaningful difference from Black: Ruff format is far faster, and it integrates import sorting when the I rules are enabled. So the complete flow is usually:

ruff check --fix . && ruff format .

The order matters. Run check --fix first so automatic fixes are applied, then format for final layout.

Editor Integration

For VS Code, install the official "Ruff" extension from Astral, then add to settings.json:

{

"[python]": {

"editor.defaultFormatter": "charliermarsh.ruff",

"editor.formatOnSave": true,

"editor.codeActionsOnSave": {

"source.fixAll.ruff": "explicit",

"source.organizeImports.ruff": "explicit"

}

}

}

With this, every save fixes auto-fixable issues, sorts imports, and formats the file. Given the speed, you will not even notice the pause.

For PyCharm there is a Ruff plugin in the marketplace. For Neovim, Ruff ships a language server you can wire up through nvim-lspconfig.

Pre-commit Hook

To keep messy code out of the repository:

# .pre-commit-config.yaml

repos:

  • repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.8.0

hooks:

  • id: ruff
args: [--fix]

  • id: ruff-format

Install it with:

pip install pre-commit

pre-commit install

Now every git commit runs Ruff automatically. If it fixes something, the commit aborts and you simply git add again and re-commit.

CI Integration

# .github/workflows/lint.yml

name: Lint

on: [push, pull_request]

jobs:

ruff:

runs-on: ubuntu-latest

steps:

  • uses: actions/checkout@v4
  • uses: astral-sh/ruff-action@v3
with:

args: check --output-format=github

  • uses: astral-sh/ruff-action@v3
with:

args: format --check

--output-format=github makes errors appear as inline annotations on the exact lines in a pull request rather than plain log text. That makes review much more pleasant.

Migrating From Older Tools

If you have a long-standing Flake8 configuration, Ruff can help you convert:

ruff check --show-settings    # inspect the effective configuration

To convert a .flake8 or setup.cfg:

pip install flake8-to-ruff

flake8-to-ruff .flake8 > ruff-converted.toml

After migrating, drop the old dependencies from your dev requirements: flake8, black, isort, pyupgrade, and their plugins. Your dev dependency list shrinks noticeably and CI install time drops with it.

Adopting It in a Large Messy Codebase

This is the most frequently asked question. You have a three year old project, ruff check . reports 4000 errors, and your team has no time to fix them all.

Do not panic, and above all do not try to fix everything in one giant pull request. A PR touching 500 files will never be reviewed properly.

Here is the gradual strategy I use.

Step one, enable the formatter only, in a separate commit. Formatting is a safe mechanical change, and afterwards every subsequent diff is cleaner. Add that commit hash to .git-blame-ignore-revs so git blame stays useful.

ruff format .

git add -A

git commit -m "chore: format entire codebase with ruff"

git rev-parse HEAD >> .git-blame-ignore-revs

Step two, enable only the F rules. These catch real bugs and there are usually few of them.

[tool.ruff.lint]

select = ["F"]

Fix them all, commit, and run your tests.

Step three, use a baseline. Ruff can add noqa comments to all existing violations, letting you enable new rules without blocking ongoing work.

ruff check --select E,W,B,UP,SIM --add-noqa .

Now all legacy violations are marked, while new code you write is checked immediately. Your team can clean up those noqa comments incrementally as they touch each file.

Step four, raise the bar periodically. Each sprint, adopt one new rule group, fix it, and add it to the permanent configuration.

This gradual approach is far more likely to succeed than forcing perfection at once.

Rules I Recommend for Serious Projects

Once you are comfortable with the basics, these additions are high value.

[tool.ruff.lint]

select = [

"E", "W", "F", "I", "B", "C4", "UP", "SIM", "RUF",

"N", # pep8-naming, naming consistency

"S", # bandit, security issues

"A", # builtin shadowing

"T20", # forbid leftover print statements

"PT", # good pytest style

"RET", # return statement simplification

"ARG", # unused arguments

"PTH", # prefer pathlib over os.path

"ERA", # commented-out code

]

The S group from bandit is especially valuable because it catches security issues such as eval usage, subprocess with shell=True, or hardcoded credentials. For production code this is essential.

T20 forbids stray print calls in production code, something that slips into main branches surprisingly often. ERA flags commented-out code. Dead commented code is clutter, because you have git for that.

Tips and Best Practices

Start with a few rules and add gradually. Enabling ALL on an existing project is the fastest way to make your team hate linting.

Never write a bare # noqa. Write # noqa: F401 so it is clear what is being suppressed and why. You can even enforce this with rule PGH004.

Run ruff check --fix and ruff format as one command in your development script, and make sure the order is right.

Keep formatting commits separate from logic commits. A diff mixing both cannot be reviewed.

Prefer per-file-ignores over scattering noqa comments. It is tidier and easier to audit.

Remember Ruff is not a type checker. Keep mypy or pyright for type checking, the two complement rather than replace each other.

Pin the Ruff version in your configuration. New rules are added fairly often, and an unplanned upgrade can suddenly turn CI red.

Conclusion

Ruff is one of the biggest quality-of-life improvements for Python developers in recent years. The summary:

One tool replaces Flake8, Black, isort, pyupgrade, and dozens of plugins, at hundreds of times the speed.

That speed changes behavior, because linting can run on every file save rather than only in CI.

ruff check handles logic and style issues, ruff format handles layout, and the two are designed to work together.

Configuration lives in pyproject.toml, and per-file-ignores is far cleaner than sprinkling noqa comments.

For legacy codebases, adopt gradually: format first, then the F rules, then use --add-noqa as a baseline, then raise the bar each sprint.

Ruff is not a type checker replacement, so keep mypy or pyright alongside it.

Run ruff check . on your project right now. It takes under a second, and the results are usually an eye-opener about what has been slipping past unnoticed. Then wire it into pre-commit and let tooling enforce the standard rather than exhausting manual review. Happy linting.

Related Articles

Complete Neo4j Tutorial: Graph Database for Knowledge Graphs and AI

Tutorial Lengkap Neo4j: Graph Database untuk Knowledge Graphs dan AI Graph database telah menjadi komponen penting dalam...

CatBoost Tutorial: Gradient Boosting for Tabular Data with Automatic Categorical Feature Handling

Tutorial CatBoost: Gradient Boosting untuk Data Tabular dengan Penanganan Fitur Kategorikal Otomatis CatBoost (Categoric...

LiveKit Agents Tutorial: Building Real-Time AI Voice Agents with Python

Tutorial LiveKit Agents: Membangun AI Voice Agent Real-Time dengan Python Pengantar LiveKit Agents adalah framework open...

Complete Jupyter AI Tutorial: Integrate LLMs Directly Into Your Notebooks

Tutorial Lengkap Jupyter AI: Integrasikan LLM Langsung ke Notebook Anda Jupyter Notebook telah menjadi alat utama bagi d...