ホーム 暮らし Ruff | Usage: Linter Guide

Ruff | Usage: Linter Guide

藤崎 健人 藤崎 健人 • 更新: • 公開: • 読了約 26 分
目次

Knowledge is like a weapon, and solving it is like Lego blocks—what is the answer?
Welcome back to Knowledge Oasis today
Your guide is ko-fumi
Today's theme is 'The Complete Guide to Using Ruff Linter'

Introduction

n5603622dbd39

“I often hear about 'Linter' for Python code checks, but what is it anyway?”When I first started programming, I didn't really understand it either. A Linter is a tool that automatically reads the code you've written and acts like a “Linter”
to point out problems, telling you, “You should fix this part.” There were many different Linters for Python, but honestly, using a combination of several tools was a hassle. “kind teacher” Ruff solves those problems in one go. In this guide, I will walk you through everything clearly, from the “super basics” like “What is a Linter anyway?” and “How do I use Ruff?” to tips for using it conveniently in real-world projects.
Ruff.

Target Audience

  • Beginner to intermediate Python programmers

  • Those considering implementing code checks (static analysis) or a Linter

  • Those who are already using existing Linters or auto-formatting tools but are interested in switching or improving efficiency

Overview

First, what is a “Linter”?
As the name “Lint” (fluff) suggests, a Linter is a tool that finds and cleans up “trash” or “dust” in your program. Specifically, it automatically checks:

  • Whether your writing style is incorrect

  • Whether you are following coding rules (e.g., “write function names in lowercase”).

Ruff is currently receiving a lot of attention as a Linter for Python. The reason is that while you previously had to use multiple tools like Flake8, isort, and pydocstyle, Ruff combines them all into one and runs at super-high speed (it's written in Rust!). This alone solves the problem of “my Lint settings are a mess...” in one shot.

Basic Command: ruff check

The most basic command in Ruff is

ruff check [パス]

ruff check
[path]. You can specify a file name or directory name for
. With this single command, it will thoroughly perform a “health check” on the entire specified file.

Further convenient options include

  • --fix : Automatically fixes what it can

  • --watch : Monitors file changes and automatically re-checks if anything changes
    , and so on.

Rule Selection

“So, what exactly is it looking at during that “health check”?”
This is the interesting part about Ruff; you can choose only the rules you need to check.

Clean code according to PEP8 with pycodestyle (E)

"pycodestyle" checks whether your code follows the "official Python coding rules (PEP8)." In Ruff, these are grouped under the E prefix. If you want to "write clean code that follows PEP8!", selecting
E will help you quickly identify minor formatting mistakes. It is also useful when you want to properly detect code style violations.

Pyflakes (F) is a "bug detector"

Pyflakes is a tool that excels at finding "potential bugs" in your code, such as "unused variables" or "undefined variables." In Ruff, the F prefix corresponds to Pyflakes. It is very valuable in real-world projects because it prevents unexpected bugs caused by simple typos (variable name errors).

Clean imports with isort (I)

isort is a tool that automatically sorts import statements. In Ruff, it is specified with I. Have you ever struggled with the "messy import order problem"? It also reduces unnecessary noise during code reviews.

Improve documentation quality with pydocstyle (D)

pydocstyle checks whether the descriptions (docstrings) added to Python functions and classes "follow official rules." When you decide that "this project needs to ensure documentation quality," you can simply add the
D rule in Ruff.

Modernize Python with pyupgrade (UP)

pyupgrade is a tool that automatically rewrites old syntax into "modern Python." By selecting UP in Ruff, you can update "outdated coding styles" to the latest specifications all at once.

autoflake (cleaning up unused code)

autoflake is a "cleaner" that removes unused imports and variables. It is very useful when you want to sweep away the "dust" in your project.

Strict best practices with flake8-bugbear (B)

flake8-bugbear is a tool that provides performance and safety advice, such as "you should write this code this way!" In Ruff, it is specified with B.

Keep it simpler with flake8-simplify (SIM)

flake8-simplify suggests ways to simplify redundant code. It is perfect when you want to "eliminate waste!"

Enforce type annotations with flake8-annotations (ANN)

You can also verify Type Annotations available in Python 3 and later. This is effective for large-scale projects where you want to strictly check "types" as well.

Enforce import guidelines with flake8-tidy-imports (TID)

You can also cover detailed guidelines such as organizing import statements and prohibiting relative imports.

Others (PIE, TRY, RUF, PL, etc.)
  • PIE: Optimizes redundant dictionary expansions, etc.

  • TRY: Promotes best practices for exception handling

  • RUF: Ruff-specific auxiliary rules (e.g., detecting unused noqa)

Tips for actual selection

It is recommended to start by narrowing it down to just E (pycodestyle) and F (Pyflakes), and as you get used to it, add B, I, or UP. You can also specify
ALL if you want to check everything at once, but the key to continuing without stress is to add them gradually as needed until you are comfortable.

Automatic Fixes

A wonderful thing about Ruff is that it can automatically fix many of the problems it finds.
However, there are "safe" fixes and "unsafe" fixes for automatic correction.

Safety of fixes
  • Safe fixes automatically correct issues where it can be said that "the behavior will definitely not change even if fixed," such as reordering imports or deleting unused imports.

  • Unsafe fixes are those that "can be fixed visually but might change the behavior." For example, a fix like list(...)[0] to next(iter(...)) (RUF015) requires caution because the behavior for an empty list will change.
    By default, Ruff only applies "safe fixes," so you can use it with peace of mind. If you want to apply "unsafe fixes" as well, explicitly specify the "only safe fixes" option, or rather, use the --unsafe-fixes option.

Disabling fixes and fine-tuning

You can also flexibly adjust settings if you want to change how a specific rule is applied on a per-project basis.

  • lint.extend-safe-fixes: Treats fixes that are normally considered unsafe as safe.

  • lint.extend-unsafe-fixes: Conversely, treats safe fixes as unsafe to apply them more cautiously.

For example,

  • "I want to always automatically apply 'unused import deletion (F401)' as safe"

  • "I want to explicitly reflect pyupgrade-style automatic conversions (UP) only in CI"
    —you can adjust the safety level yourself according to your team's rules.

Error suppression (noqa, ignore, etc.)

For those times when you absolutely must ignore a warning for "just this line," Ruff provides various ways to suppress errors.

  • Writing # noqa at the end of a line ignores all warnings on that line.

  • # noqa: F401, E741 You can also suppress specific rules like this.

  • If you want to ignore it for the entire file, use # ruff: noqa. It is effective if written as an independent line anywhere in the file, but it is best to write it at the top of the file if possible.

  • File-level suppression via per-file-ignores in pyproject.toml is also possible.

Furthermore, you can even automatically detect and remove unnecessary noqa comments. For example, if you "temporarily suppressed an error with noqa, but that error no longer occurs," you can find and remove unused noqa comments using the
RUF100 rule.

Also, if you want to "automatically add noqa to all current errors in an existing codebase," you can insert them in bulk using --add-noqa. This feature is very useful during the initial migration or large-scale refactoring.

Action Comments (isort compatible)

You can also use isort action comments (such as # isort: skip_file), which are famous for organizing import statements, as they are. Furthermore, Ruff-specific comments like
# ruff: isort: skip_file are also fine. However, please note that content inside docstrings (descriptions enclosed in """) is ignored by Ruff.

Specific examples:

  • To suppress import sorting for the entire file → # isort: skip_file

  • To avoid organizing only a part of the file, enclose it between # isort: off and # isort: on .

  • To separate multiple import blocks, use # isort: split

Exit Codes

When combining Ruff checks with CI or automated tests, the "Exit Code" is very important.

  • 0: No violations found, or all have been automatically fixed.

  • 1: Violations remain.

  • 2: Abnormal termination such as configuration errors or internal errors

Furthermore,

  • --exit-zero option allows you to "always exit with 0 even if there are violations"

  • --exit-non-zero-on-fix option means "exit with 1 if there are fixes, even if violations are gone after auto-fixing"

This behavior can be flexibly controlled to match your team's rules, such as checking "how many issues remain to be fixed" in a CI pipeline or "automatically fixing what can be fixed mechanically."

Summary

Those who felt like "I've been avoiding linters because I don't really understand them" or "detailed configuration and maintenance are a hassle" will be surprised by Ruff's simplicity, flexibility, and speed.
Start simply with just "E" and "F," and expand features as needed. By appropriately utilizing suppression comments and auto-fixes, you will find yourself writing "clean code" before you know it."clean code" that will surprise even you.

This is a tool I especially want those who ask "Python linter? What is Ruff?" to try at least once.

Each piece of knowledge is like a small Lego block.
But when combined, they become a weapon to give shape to ideas that can change the world!

See you again at Knowledge Oasis.
Your guide was ko-fumi.

同じカテゴリの記事

藤崎 健人

芸能取材歴10年のデスク。所属事務所の公式リリース、番組公式サイト、配信サービスの告知を一次情報として採用し、裏付けの取れない内容は記事にしていません。

おすすめの関連記事