Skip to content

Commit

Permalink
Update tutorial to match revised Ruff defaults (#8066)
Browse files Browse the repository at this point in the history
## Summary

We don't enable E501 by default, but `line-length` is a useful example
for configuration, so we now set `--extend-select` in the tutorial with
a note to that effect.

I've also updated all the outputs to match the latest CLI behavior, and
changed the example from `List` to `Sequence` because `List` now spits
out two diagnostics (one for the import, one for the usage), which IMO
is confusing for beginners.
  • Loading branch information
charliermarsh authored Oct 19, 2023
1 parent b5d3caf commit cdc5e2f
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 54 deletions.
5 changes: 2 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -237,9 +237,8 @@ linting command.
isort, pyupgrade, and others. Regardless of the rule's origin, Ruff re-implements every rule in
Rust as a first-party feature.

By default, Ruff enables Flake8's `E` and `F` rules. Ruff supports all rules from the `F` category,
and a [subset](https://docs.astral.sh/ruff/rules/#error-e) of the `E` category, omitting those
stylistic rules made obsolete by the use of a formatter, like
By default, Ruff enables Flake8's `F` rules, along with a subset of the `E` rules, omitting any
stylistic rules that overlap with the use of a formatter, like
[Black](https://github.com/psf/black).

If you're just getting started with Ruff, **the default rule set is a great place to start**: it
Expand Down
102 changes: 52 additions & 50 deletions docs/tutorial.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ numbers
Where `numbers.py` contains the following code:

```py
from typing import List
from typing import Iterable

import os


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

Expand All @@ -32,17 +32,17 @@ To start, we'll install Ruff through PyPI (or with your [preferred package manag
> pip install ruff
```

We can then run Ruff over our project via:
We can then run Ruff over our project via `ruff check`:

```shell
❯ ruff check .
numbers/numbers.py:3:8: F401 [*] `os` imported but unused
Found 1 error.
[*] 1 potentially fixable with the --fix option.
[*] 1 fixable with the `--fix` option.
```

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:
"fixable" error, so we can resolve the issue automatically by running `ruff check --fix`:

```shell
❯ ruff check --fix .
Expand All @@ -55,13 +55,13 @@ Running `git diff` shows the following:
--- a/numbers/numbers.py
+++ b/numbers/numbers.py
@@ -1,7 +1,5 @@
from typing import List
from typing import Iterable

-import os
-

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

Expand All @@ -77,15 +77,19 @@ Let's create a `pyproject.toml` file in our project's root directory:

```toml
[tool.ruff]
# Decrease the maximum line length to 79 characters.
# 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"]
# Set the maximum line length to 79 characters.
line-length = 79
```

Running Ruff again, we can see that it now enforces a line length of 79 characters:

```shell
❯ ruff check .
numbers/numbers.py:6:80: E501 Line too long (83 > 79 characters)
numbers/numbers.py:5:80: E501 Line too long (90 > 79 characters)
Found 1 error.
```

Expand All @@ -98,9 +102,10 @@ specifically, we'll want to make note of the minimum supported Python version:
requires-python = ">=3.10"

[tool.ruff]
# Decrease the maximum line length to 79 characters.
# Add the `line-too-long` rule to the enforced rule set.
extend-select = ["E501"]
# Set the maximum line length to 79 characters.
line-length = 79
src = ["src"]
```

### Rule Selection
Expand All @@ -109,45 +114,47 @@ Ruff supports [over 700 lint rules](rules.md) split across over 50 built-in plug
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 enforces the `E`- and `F`-prefixed rules, which correspond to those derived from
pycodestyle and Pyflakes, respectively.
By default, Ruff enables Flake8's `F` rules, along with a subset of the `E` rules, omitting any
stylistic rules that overlap with the use of a formatter, like
[Black](https://github.com/psf/black).

If you're introducing a linter for the first time, **the default rule set is a great place to
start**: it's narrow and focused while catching a wide variety of common errors (like unused
imports) with zero configuration.

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 add the following to our `pyproject.toml`:
rules, we can set our `pyproject.toml` to the following:

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

[tool.ruff]
select = [
"E", # pycodestyle
"F", # pyflakes
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 `List` instead of its standard-library variant:
the use of the deprecated `typing.Iterable` instead of `collections.abc.Iterable`:

```shell
❯ ruff check .
numbers/numbers.py:5:31: UP006 [*] Use `list` instead of `List` for type annotations
numbers/numbers.py:6:80: E501 Line too long (83 > 79 characters)
Found 2 errors.
[*] 1 potentially fixable with the --fix option.
numbers/numbers.py:1:1: UP035 [*] Import from `collections.abc` instead: `Iterable`
Found 1 error.
[*] 1 fixable with the `--fix` option.
```

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

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

[tool.ruff]
select = [
"E", # pycodestyle
"F", # pyflakes
extend-select = [
"UP", # pyupgrade
"D", # pydocstyle
]
Expand All @@ -161,52 +168,49 @@ If we run Ruff again, we'll see that it now enforces the pydocstyle rules:
```shell
❯ ruff check .
numbers/__init__.py:1:1: D104 Missing docstring in public package
numbers/numbers.py:1:1: UP035 [*] Import from `collections.abc` instead: `Iterable`
numbers/numbers.py:1:1: D100 Missing docstring in public module
numbers/numbers.py:5:31: UP006 [*] Use `list` instead of `List` for type annotations
numbers/numbers.py:5:80: E501 Line too long (83 > 79 characters)
Found 3 errors.
[*] 1 potentially fixable with the --fix option.
[*] 1 fixable with the `--fix` option.
```

### Ignoring Errors

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

```py
from typing import List
from typing import Iterable # noqa: UP035


def sum_even_numbers(numbers: List[int]) -> int: # noqa: UP006
"""Given a list of integers, return the sum of all even numbers in the list."""
def sum_even_numbers(numbers: Iterable[int]) -> int:
"""Given a sequence of integers, return the sum of all even numbers in the sequence."""
return sum(num for num in numbers if num % 2 == 0)
```

Running Ruff again, we'll see that it no longer flags the `List` import:
Running Ruff again, we'll see that it no longer flags the `Iterable` import:

```shell
❯ ruff check .
numbers/__init__.py:1:1: D104 Missing docstring in public package
numbers/numbers.py:1:1: D100 Missing docstring in public module
numbers/numbers.py:5:80: E501 Line too long (83 > 79 characters)
Found 3 errors.
```

If we want to ignore a rule for an entire file, we can add a `# ruff: noqa` comment to the top of
the file:

```py
# ruff: noqa: UP006
from typing import List
# ruff: noqa: UP035
from typing import Iterable


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

For more in-depth instructions on ignoring errors,
please see [_Configuration_](configuration.md#error-suppression).
For more in-depth instructions on ignoring errors, see [_Configuration_](configuration.md#error-suppression).

### Adding Rules

Expand All @@ -215,10 +219,10 @@ violations of that rule and instead focus on enforcing it going forward.

Ruff enables this workflow via the `--add-noqa` flag, which will adds 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 `UP006` violations:
flag to add `# noqa` directives to all existing `UP035` violations:

```shell
❯ ruff check --select UP006 --add-noqa .
❯ ruff check --select UP035 --add-noqa .
Added 1 noqa directive.
```

Expand All @@ -229,14 +233,12 @@ diff --git a/tutorial/src/main.py b/tutorial/src/main.py
index b9291c5ca..b9f15b8c1 100644
--- a/numbers/numbers.py
+++ b/numbers/numbers.py
@@ -1,6 +1,6 @@
from typing import List
@@ -1,4 +1,4 @@
-from typing import Iterable
+from typing import Iterable # noqa: UP035


-def sum_even_numbers(numbers: List[int]) -> int:
+def sum_even_numbers(numbers: List[int]) -> int: # noqa: UP006
"""Given a list of integers, return the sum of all even numbers in the list."""
return sum(num for num in numbers if num % 2 == 0)
def sum_even_numbers(numbers: Iterable[int]) -> int:
```

## Continuous Integration
Expand Down
1 change: 0 additions & 1 deletion scripts/generate_mkdocs.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ class Section(NamedTuple):
),
"https://docs.astral.sh/ruff/installation/": "installation.md",
"https://docs.astral.sh/ruff/rules/": "rules.md",
"https://docs.astral.sh/ruff/rules/#error-e": "rules.md#error-e",
"https://docs.astral.sh/ruff/settings/": "settings.md",
}

Expand Down

0 comments on commit cdc5e2f

Please sign in to comment.