Files
ruff/docs/tutorial.md
T
Brent WestbrookandAlex Waygood 755d3aff4c Always show unsafe and display-only fixes in the CLI (#27810)
Summary
--

This is the CLI accompaniment to #27807. The main change here is showing
display-only fix diffs in
the CLI. However, display-only fixes don't have a corresponding flag
like `--unsafe-fixes`, and I
thought it would be weird to show them unconditionally when we don't do
the same for unsafe fixes,
so this PR also unconditionally renders unsafe fix diffs, even when that
flag isn't passed. We
already emit a note about the fix being unsafe, so I think it makes
sense always to show you the
fix, and make `--unsafe-fixes` enable actually applying the fix. We also
don't want to apply
display-only fixes, so enabling rendering of the fixes with
`--display-only-fixes` or similar would
also disagree with the semantics of the unsafe flag. I'm open to other
ideas here, though.

The sub-diagnostic for display-only fixes uses a higher severity than
the note for unsafe fixes and
renders in red, as shown below.

The change here also affects ty, which now has both unsafe and
display-only fixes.

I again checked what clippy and rustc do in these cases, and they don't
include any additional note or warning about the fix being unsafe:

<details><summary>Rust diagnostics</summary>
<p>

Here's a
[`clippy::needless_pass_by_value`](https://rust-lang.github.io/rust-clippy/rust-1.97.0/index.html#needless_pass_by_value)
diagnostic, which is `MaybeIncorrect` ( similar to our `Unsafe`):

```
warning: this argument is passed by value, but not consumed in the function body
 --> src/main.rs:3:15
  |
3 | fn size(data: Data) -> usize {
  |               ^^^^
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.97.0/index.html#needless_pass_by_value
  = note: requested on the command line with `-W clippy::needless-pass-by-value`
help: consider taking a reference instead
  |
3 | fn size(data: &Data) -> usize {
  |               +
```

and here's a rustc
[`LetLike`](https://github.com/rust-lang/rust/blob/8bab26f4f68e0e26f0bb7960be334d5b520ea452/compiler/rustc_trait_selection/src/errors.rs#L268-L288)
diagnostic, which is `has-placeholders` (similar to our `DisplayOnly`
but definitely produces invalid code in this case):

```
error[E0282]: type annotations needed for `Vec<_>`
 --> placeholder.rs:2:9
  |
2 |     let values = Vec::new();
  |         ^^^^^^   ---------- type must be known at this point
  |
help: consider giving `values` an explicit type, where the type for type parameter `T` is specified
  |
2 |     let values: Vec<T> = Vec::new();
  |               ++++++++
```

</p>
</details>

Fixes https://github.com/astral-sh/ty/issues/1679

Test Plan
--

Updated existing snapshots, and some manual testing in the CLI:

<img width="965" height="400" alt="image"
src="https://github.com/user-attachments/assets/888ad79a-6853-48d4-8344-48da4af47d74"
/>

---------

Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
2026-10-09 12:26:57 -04:00

11 KiB

Tutorial

This tutorial will walk you through the process of integrating Ruff's linter and formatter into your project. For a more detailed overview, see Configuring Ruff.

Getting Started

To start, we'll initialize a project using uv:

$ uv init --lib numbers

This command creates a Python project with the following structure:

numbers
  ├── README.md
  ├── pyproject.toml
  └── src
      └── numbers
          ├── __init__.py
          └── py.typed

We'll then clear out the auto-generated content in src/numbers/__init__.py and create src/numbers/calculate.py with the following code:

from typing import Iterable

import os


def sum_even_numbers(numbers: Iterable[int]) -> int:
    """Given an iterable of integers, return the sum of all even numbers in the iterable."""
    return sum(
        num for num in numbers
        if num % 2 == 0
    )

Next, we'll add Ruff to our project:

$ uv add --dev ruff

We can then run the Ruff linter over our project via uv run ruff check:

$ uv run ruff check
src/numbers/calculate.py:3:8: F401 [*] `os` imported but unused
Found 1 error.
[*] 1 fixable with `--fix`.

!!! note

As an alternative to `uv run`, you can also run Ruff by activating the project's virtual
environment (`source .venv/bin/activate` on Linux and macOS, or `.venv\Scripts\activate` on
Windows) and running `ruff check` directly.

Ruff identified an unused import, which is a common error in Python code. Ruff considers this a "fixable" error, so we can resolve the issue automatically by running ruff check --fix:

$ uv run ruff check --fix
Found 1 error (1 fixed, 0 remaining).

Running git diff shows the following:

--- a/src/numbers/calculate.py
+++ b/src/numbers/calculate.py
@@ -1,7 +1,5 @@
 from typing import Iterable

-import os
-

def sum_even_numbers(numbers: Iterable[int]) -> int:
    """Given an iterable of integers, return the sum of all even numbers in the iterable."""
    return sum(
        num for num in numbers
        if num % 2 == 0
    )

Note Ruff runs in the current directory by default, but you can pass specific paths to check:

$ uv run ruff check src/numbers/calculate.py

Now that our project is passing ruff check, we can run the Ruff formatter via ruff format:

$ uv run ruff format
1 file reformatted

Running git diff shows that the sum call was reformatted to fit within the default 88-character line length limit:

--- a/src/numbers/calculate.py
+++ b/src/numbers/calculate.py
@@ -3,7 +3,4 @@ from typing import Iterable

 def sum_even_numbers(numbers: Iterable[int]) -> int:
     """Given an iterable of integers, return the sum of all even numbers in the iterable."""
-    return sum(
-        num for num in numbers
-        if num % 2 == 0
-    )
+    return sum(num for num in numbers if num % 2 == 0)

Thus far, we've been using Ruff's default configuration. Let's take a look at how we can customize Ruff's behavior.

Configuration

To determine the appropriate settings for each Python file, Ruff looks for the first pyproject.toml, ruff.toml, or .ruff.toml file in the file's directory or any parent directory.

To configure Ruff, we'll add the following to the configuration file in our project's root directory:

=== "pyproject.toml"

 ```toml
 [tool.ruff]
 # Set the maximum line length to 79.
 line-length = 79

 [tool.ruff.lint]
 # Add the `line-too-long` rule to the enforced rule set. By default, Ruff omits rules that
 # overlap with the use of a formatter, like Black, but we can override this behavior by
 # explicitly adding the rule.
 extend-select = ["E501"]
 ```

=== "ruff.toml"

 ```toml
 # Set the maximum line length to 79.
 line-length = 79

 [lint]
 # Add the `line-too-long` rule to the enforced rule set. By default, Ruff omits rules that
 # overlap with the use of a formatter, like Black, but we can override this behavior by
 # explicitly adding the rule.
 extend-select = ["E501"]
 ```

Running Ruff again, we see that it now enforces a maximum line width, with a limit of 79:

$ uv run ruff check
src/numbers/calculate.py:5:80: E501 Line too long (90 > 79)
Found 1 error.

For a full enumeration of the supported settings, see Settings. For our project specifically, we'll want to make note of the minimum supported Python version:

=== "pyproject.toml"

 ```toml
 [project]
 # Support Python 3.10+.
 requires-python = ">=3.10"

 [tool.ruff]
 # Set the maximum line length to 79.
 line-length = 79

 [tool.ruff.lint]
 # Add the `line-too-long` rule to the enforced rule set.
 extend-select = ["E501"]
 ```

=== "ruff.toml"

 ```toml
 # Support Python 3.10+.
 target-version = "py310"
 # Set the maximum line length to 79.
 line-length = 79

 [lint]
 # Add the `line-too-long` rule to the enforced rule set.
 extend-select = ["E501"]
 ```

Rule Selection

Ruff supports over 900 lint rules split across over 50 built-in plugins, but determining the right set of rules will depend on your project's needs: some rules may be too strict, some are framework-specific, and so on.

By default, Ruff enables rules from the F, E, B, UP, and RUF categories, as well as many more, omitting any stylistic rules that overlap with the use of a formatter, like ruff format or Black.

If you're introducing a linter for the first time, the default rule set is a great place to start: it catches a wide variety of common errors (like unused imports) with zero configuration. See Default Rules for the complete list.

If you're migrating to Ruff from another linter, you can enable rules that are equivalent to those enforced in your previous configuration. For example, if we want to enforce the pyupgrade rules, we can set our configuration file to the following:

=== "pyproject.toml"

 ```toml
 [project]
 requires-python = ">=3.10"

 [tool.ruff.lint]
 extend-select = [
   "UP",  # pyupgrade
 ]
 ```

=== "ruff.toml"

 ```toml
 target-version = "py310"

 [lint]
 extend-select = [
   "UP",  # pyupgrade
 ]
 ```

If we run Ruff again, we'll see that it now enforces the pyupgrade rules. In particular, Ruff flags the use of the deprecated typing.Iterable instead of collections.abc.Iterable:

$ uv run ruff check
src/numbers/calculate.py:1:1: UP035 [*] Import from `collections.abc` instead: `Iterable`
Found 1 error.
[*] 1 fixable with `--fix`.

Over time, we may choose to enforce additional rules. For example, we may want to enforce that all functions have docstrings:

=== "pyproject.toml"

 ```toml
 [project]
 requires-python = ">=3.10"

 [tool.ruff.lint]
 extend-select = [
   "UP",  # pyupgrade
   "D",   # pydocstyle
 ]

 [tool.ruff.lint.pydocstyle]
 convention = "google"
 ```

=== "ruff.toml"

 ```toml
 target-version = "py310"

 [lint]
 extend-select = [
   "UP",  # pyupgrade
   "D",   # pydocstyle
 ]

 [lint.pydocstyle]
 convention = "google"
 ```

If we run Ruff again, we'll see that it now enforces the pydocstyle rules:

$ uv run ruff check
src/numbers/__init__.py:1:1: D104 Missing docstring in public package
src/numbers/calculate.py:1:1: UP035 [*] Import from `collections.abc` instead: `Iterable`
  |
1 | from typing import Iterable
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ UP035
  |
  = help: Import from `collections.abc`

src/numbers/calculate.py:1:1: D100 Missing docstring in public module
Found 3 errors.
[*] 1 fixable with `--fix`.

Ignoring Errors

Any lint rule can be ignored by adding a # noqa comment to the line in question. For example, let's ignore the UP035 rule for the Iterable import:

from typing import Iterable  # noqa: UP035


def sum_even_numbers(numbers: Iterable[int]) -> int:
    """Given an iterable of integers, return the sum of all even numbers in the iterable."""
    return sum(num for num in numbers if num % 2 == 0)

Running ruff check again, we'll see that it no longer flags the Iterable import:

$ uv run ruff check
src/numbers/__init__.py:1:1: D104 Missing docstring in public package
src/numbers/calculate.py:1:1: D100 Missing docstring in public module
Found 2 errors.

If we want to ignore a rule for an entire file, we can add the line # ruff: noqa: {code} anywhere in the file, preferably towards the top, like so:

# ruff: noqa: UP035
from typing import Iterable


def sum_even_numbers(numbers: Iterable[int]) -> int:
    """Given an iterable of integers, return the sum of all even numbers in the iterable."""
    return sum(num for num in numbers if num % 2 == 0)

For more in-depth instructions on ignoring errors, please see Error suppression.

Adding Rules

When enabling a new rule on an existing codebase, you may want to ignore all existing violations of that rule and instead focus on enforcing it going forward.

Ruff enables this workflow via the --add-noqa flag, which will add a # noqa directive to each line based on its existing violations. We can combine --add-noqa with the --select command-line flag to add # noqa directives to all existing UP035 violations:

$ uv run ruff check --select UP035 --add-noqa .
Added 1 noqa directive.

Running git diff shows the following:

diff --git a/numbers/src/numbers/calculate.py b/numbers/src/numbers/calculate.py
index 71fca60c8d..e92d839f1b 100644
--- a/numbers/src/numbers/calculate.py
+++ b/numbers/src/numbers/calculate.py
@@ -1,4 +1,4 @@
-from typing import Iterable
+from typing import Iterable  # noqa: UP035

To add # ruff: ignore[...] comments instead, use the --add-ignore flag. In preview mode, --add-ignore uses human-readable rule names in place of rule codes.

Integrations

This tutorial has focused on Ruff's command-line interface, but Ruff can also be used as a pre-commit hook via ruff-pre-commit:

- repo: https://github.com/astral-sh/ruff-pre-commit
  # Ruff version.
  rev: v0.16.10
  hooks:
    # Run the linter.
    - id: ruff-check
    # Run the formatter.
    - id: ruff-format

Ruff can also be integrated into your editor of choice. Refer to the Editors section for more information.

For other integrations, see the Integrations section.