Commit Graph
817 Commits
Author SHA1 Message Date
Micha Reiser b40d1b036a Store interpolation debug text in the shared AST buffers
Keep the original spelling in text and the boundaries around the expression in extra. This removes a vector from every tree while keeping the check for a self-documenting interpolation local to its row.
2026-11-22 13:56:05 +00:00
Brent Westbrook efb8728d0f Rename 17 rules for expressions and control flow (#30479)
| Code | Old name | New name |
|---|---|---|
| [`B026`](https://docs.astral.sh/ruff/rules/B026/) |
`star-arg-unpacking-after-keyword-arg` | `star-arg-after-keyword` |
| [`FURB110`](https://docs.astral.sh/ruff/rules/FURB110/) |
`if-exp-instead-of-or-operator` | `if-expr-with-body-as-condition` |
| [`FURB154`](https://docs.astral.sh/ruff/rules/FURB154/) |
`repeated-global` | `consecutive-global-or-nonlocal-statements` |
| [`PLR1708`](https://docs.astral.sh/ruff/rules/PLR1708/) |
`stop-iteration-return` | `raise-stop-iteration-in-generator` |
| [`PLW0129`](https://docs.astral.sh/ruff/rules/PLW0129/) |
`assert-on-string-literal` | `assert-string-literal` |
| [`PLW2901`](https://docs.astral.sh/ruff/rules/PLW2901/) |
`redefined-loop-name` | `redefined-for-or-with-target` |
| [`RET505`](https://docs.astral.sh/ruff/rules/RET505/) |
`superfluous-else-return` | `unnecessary-else-after-return` |
| [`RET506`](https://docs.astral.sh/ruff/rules/RET506/) |
`superfluous-else-raise` | `unnecessary-else-after-raise` |
| [`RET507`](https://docs.astral.sh/ruff/rules/RET507/) |
`superfluous-else-continue` | `unnecessary-else-after-continue` |
| [`RET508`](https://docs.astral.sh/ruff/rules/RET508/) |
`superfluous-else-break` | `unnecessary-else-after-break` |
| [`RUF021`](https://docs.astral.sh/ruff/rules/RUF021/) |
`parenthesize-chained-operators` | `unclear-boolean-precedence` |
| [`RUF027`](https://docs.astral.sh/ruff/rules/RUF027/) |
`missing-f-string-syntax` | `possibly-missing-f-string-prefix` |
| [`RUF034`](https://docs.astral.sh/ruff/rules/RUF034/) |
`useless-if-else` | `if-expr-with-identical-branches` |
| [`SIM108`](https://docs.astral.sh/ruff/rules/SIM108/) |
`if-else-block-instead-of-if-exp` |
`if-else-assignment-to-same-variable` |
| [`SIM113`](https://docs.astral.sh/ruff/rules/SIM113/) |
`enumerate-for-loop` | `manual-loop-counter` |
| [`SIM114`](https://docs.astral.sh/ruff/rules/SIM114/) |
`if-with-same-arms` | `if-with-identical-branches` |
| [`SIM212`](https://docs.astral.sh/ruff/rules/SIM212/) |
`if-expr-with-twisted-arms` | `if-expr-with-negated-else-as-condition` |
2026-11-20 11:08:10 -05:00
Brent Westbrook d936a5566e Rename 17 rules for source layout, imports, and directives (#30477)
| Code | Old name | New name |
|---|---|---|
| [`COM819`](https://docs.astral.sh/ruff/rules/COM819/) |
`prohibited-trailing-comma` | `unnecessary-trailing-comma` |
| [`E301`](https://docs.astral.sh/ruff/rules/E301/) |
`blank-line-between-methods` | `missing-blank-line-before-method` |
| [`E302`](https://docs.astral.sh/ruff/rules/E302/) |
`blank-lines-top-level` |
`missing-blank-lines-before-top-level-definition` |
| [`E305`](https://docs.astral.sh/ruff/rules/E305/) |
`blank-lines-after-function-or-class` |
`missing-blank-lines-after-top-level-definition` |
| [`E306`](https://docs.astral.sh/ruff/rules/E306/) |
`blank-lines-before-nested-definition` |
`missing-blank-line-before-nested-definition` |
| [`EXE001`](https://docs.astral.sh/ruff/rules/EXE001/) |
`shebang-not-executable` | `non-executable-file-with-shebang` |
| [`EXE002`](https://docs.astral.sh/ruff/rules/EXE002/) |
`shebang-missing-executable-file` | `executable-file-without-shebang` |
| [`F403`](https://docs.astral.sh/ruff/rules/F403/) |
`undefined-local-with-import-star` | `star-import` |
| [`F405`](https://docs.astral.sh/ruff/rules/F405/) |
`undefined-local-with-import-star-usage` |
`possibly-undefined-name-with-star-import` |
| [`F406`](https://docs.astral.sh/ruff/rules/F406/) |
`undefined-local-with-nested-import-star-usage` |
`non-module-level-star-import` |
| [`PLE2510`](https://docs.astral.sh/ruff/rules/PLE2510/) |
`invalid-character-backspace` | `unescaped-backspace-character` |
| [`PLE2512`](https://docs.astral.sh/ruff/rules/PLE2512/) |
`invalid-character-sub` | `unescaped-substitute-character` |
| [`PLE2513`](https://docs.astral.sh/ruff/rules/PLE2513/) |
`invalid-character-esc` | `unescaped-escape-character` |
| [`PLE2514`](https://docs.astral.sh/ruff/rules/PLE2514/) |
`invalid-character-nul` | `unescaped-null-character` |
| [`PLE2515`](https://docs.astral.sh/ruff/rules/PLE2515/) |
`invalid-character-zero-width-space` |
`unescaped-zero-width-space-character` |
| [`RUF100`](https://docs.astral.sh/ruff/rules/RUF100/) | `unused-noqa`
| `unused-suppression-comment` |
| [`RUF101`](https://docs.astral.sh/ruff/rules/RUF101/) |
`redirected-noqa` | `renamed-rule-in-suppression-comment` |
2026-11-19 19:12:57 -05:00
Brent Westbrook af3adfd58b Rename 25 rules for definitions, naming, and typing (#30476)
| Code | Old name | New name |

|---------------------------------------------------------|------------------------------------------------|-----------------------------------------------------|
| [`FBT001`](https://docs.astral.sh/ruff/rules/FBT001/) |
`boolean-type-hint-positional-argument` |
`boolean-annotated-positional-parameter` |
| [`FBT002`](https://docs.astral.sh/ruff/rules/FBT002/) |
`boolean-default-value-positional-argument` |
`boolean-default-value-positional-parameter` |
| [`N801`](https://docs.astral.sh/ruff/rules/N801/) |
`invalid-class-name` | `non-camel-case-class-name` |
| [`N802`](https://docs.astral.sh/ruff/rules/N802/) |
`invalid-function-name` | `non-lowercase-function-name` |
| [`N803`](https://docs.astral.sh/ruff/rules/N803/) |
`invalid-argument-name` | `non-lowercase-parameter-name` |
| [`N804`](https://docs.astral.sh/ruff/rules/N804/) |
`invalid-first-argument-name-for-class-method` |
`class-method-receiver-not-named-cls` |
| [`N805`](https://docs.astral.sh/ruff/rules/N805/) |
`invalid-first-argument-name-for-method` |
`instance-method-receiver-not-named-self` |
| [`N813`](https://docs.astral.sh/ruff/rules/N813/) |
`camelcase-imported-as-lowercase` | `camel-case-imported-as-lowercase` |
| [`N814`](https://docs.astral.sh/ruff/rules/N814/) |
`camelcase-imported-as-constant` | `camel-case-imported-as-constant` |
| [`N817`](https://docs.astral.sh/ruff/rules/N817/) |
`camelcase-imported-as-acronym` | `camel-case-imported-as-acronym` |
| [`N818`](https://docs.astral.sh/ruff/rules/N818/) |
`error-suffix-on-exception-name` |
`exception-class-without-error-suffix` |
| [`PLR0202`](https://docs.astral.sh/ruff/rules/PLR0202/) |
`no-classmethod-decorator` | `non-decorator-classmethod` |
| [`PLR0203`](https://docs.astral.sh/ruff/rules/PLR0203/) |
`no-staticmethod-decorator` | `non-decorator-staticmethod` |
| [`PLR6301`](https://docs.astral.sh/ruff/rules/PLR6301/) |
`no-self-use` | `unused-self` |
| [`PYI011`](https://docs.astral.sh/ruff/rules/PYI011/) |
`typed-argument-default-in-stub` |
`complex-default-for-annotated-parameter-in-stub` |
| [`PYI014`](https://docs.astral.sh/ruff/rules/PYI014/) |
`argument-default-in-stub` |
`complex-default-for-unannotated-parameter-in-stub` |
| [`PYI026`](https://docs.astral.sh/ruff/rules/PYI026/) |
`type-alias-without-annotation` | `unannotated-type-alias-in-stub` |
| [`PYI050`](https://docs.astral.sh/ruff/rules/PYI050/) |
`no-return-argument-annotation-in-stub` |
`parameter-annotated-with-no-return` |
| [`PYI051`](https://docs.astral.sh/ruff/rules/PYI051/) |
`redundant-literal-union` | `literal-union-with-supertype` |
| [`PYI057`](https://docs.astral.sh/ruff/rules/PYI057/) |
`byte-string-usage` | `deprecated-byte-string-type` |
| [`PYI058`](https://docs.astral.sh/ruff/rules/PYI058/) |
`generator-return-from-iter-method` |
`iter-method-with-generator-return-annotation` |
| [`TC006`](https://docs.astral.sh/ruff/rules/TC006/) |
`runtime-cast-value` | `cast-with-unquoted-type` |
| [`UP013`](https://docs.astral.sh/ruff/rules/UP013/) |
`convert-typed-dict-functional-to-class` | `functional-typed-dict` |
| [`UP014`](https://docs.astral.sh/ruff/rules/UP014/) |
`convert-named-tuple-functional-to-class` | `functional-named-tuple` |
| [`UP042`](https://docs.astral.sh/ruff/rules/UP042/) |
`replace-str-enum` | `manual-str-enum` |
2026-11-19 15:07:50 -05:00
Brent Westbrook 912ba68f54 Rename 12 exception and logging rules (#30475)
| Code | Old name | New name |
|---|---|---|
| [`EM101`](https://docs.astral.sh/ruff/rules/EM101/) |
`raw-string-in-exception` | `string-literal-in-exception` |
| [`EM103`](https://docs.astral.sh/ruff/rules/EM103/) |
`dot-format-in-exception` | `str-format-in-exception` |
| [`G201`](https://docs.astral.sh/ruff/rules/G201/) | `logging-exc-info`
| `logging-error-with-exc-info` |
| [`LOG002`](https://docs.astral.sh/ruff/rules/LOG002/) |
`invalid-get-logger-argument` | `file-path-as-logger-name` |
| [`LOG004`](https://docs.astral.sh/ruff/rules/LOG004/) |
`log-exception-outside-except-handler` |
`logging-exception-outside-except-handler` |
| [`LOG007`](https://docs.astral.sh/ruff/rules/LOG007/) |
`exception-without-exc-info` | `logging-exception-with-falsy-exc-info` |
| [`LOG009`](https://docs.astral.sh/ruff/rules/LOG009/) |
`undocumented-warn` | `logging-warn-constant` |
| [`LOG014`](https://docs.astral.sh/ruff/rules/LOG014/) |
`exc-info-outside-except-handler` |
`logging-exc-info-outside-except-handler` |
| [`TRY002`](https://docs.astral.sh/ruff/rules/TRY002/) |
`raise-vanilla-class` | `raise-exception-or-base-exception` |
| [`TRY003`](https://docs.astral.sh/ruff/rules/TRY003/) |
`raise-vanilla-args` | `raise-exception-with-message` |
| [`TRY400`](https://docs.astral.sh/ruff/rules/TRY400/) |
`error-instead-of-exception` | `logging-error-instead-of-exception` |
| [`TRY401`](https://docs.astral.sh/ruff/rules/TRY401/) |
`verbose-log-message` | `redundant-exception-in-logging-message` |
2026-11-19 12:52:01 -05:00
Brent Westbrook fd21232a4e Use Python API spellings in 11 rule names (#30471)
Summary
--

These renames are pretty minor, just standardizing on the hyphenation of
the names from the Python
stdlib. The one wrinkle is `eval`, which was previously the name of the
removed [`eval` (`PGH001`)]
rule. Codex renamed this to `pygrep-hooks-eval` to free up `eval` for
`S307`. That seems kind of
gross, but the rule is removed after all. Hopefully nobody is actively
using both a rule selector
that has been removed since v0.2.0 and the preview human-readable names
feature.

I also dropped `func` from the `gettext` rules since `func-call` seemed
rather redundant.

[`eval` (`PGH001`)]: https://docs.astral.sh/ruff/rules/eval/

|Code |Old name |New name |

|-----------------------------------------------------|--------------------------------|--------------------------|
|[`B009`](https://docs.astral.sh/ruff/rules/B009/)
|`get-attr-with-constant` |`getattr-with-constant` |
|[`B010`](https://docs.astral.sh/ruff/rules/B010/)
|`set-attr-with-constant` |`setattr-with-constant` |
|[`B043`](https://docs.astral.sh/ruff/rules/B043/)
|`del-attr-with-constant` |`delattr-with-constant` |

|[`INT001`](https://docs.astral.sh/ruff/rules/INT001/)|`f-string-in-get-text-func-call`|`f-string-in-gettext-call`|

|[`INT002`](https://docs.astral.sh/ruff/rules/INT002/)|`format-in-get-text-func-call`
|`format-in-gettext-call` |

|[`INT003`](https://docs.astral.sh/ruff/rules/INT003/)|`printf-in-get-text-func-call`
|`printf-in-gettext-call` |
|[`S102`](https://docs.astral.sh/ruff/rules/S102/) |`exec-builtin`
|`exec` |
|[`S307`](https://docs.astral.sh/ruff/rules/S307/)
|`suspicious-eval-usage` |`eval` |
|[`S312`](https://docs.astral.sh/ruff/rules/S312/) |
`suspicious-telnet-usage` | `suspicious-telnetlib-usage` |
|[`S321`](https://docs.astral.sh/ruff/rules/S321/)
|`suspicious-ftp-lib-usage` |`suspicious-ftplib-usage` |
|[`T203`](https://docs.astral.sh/ruff/rules/T203/) |`p-print` |`pprint`
|
2026-11-19 12:20:03 -05:00
Brent Westbrook b444480b79 Rename 20 pydocstyle rules (#30465)
Summary
--

This is the first in a series of rule rename PRs. I started here because
the renames are fairly straightforward and are within a single linter
group. Most of these rules were missing some mention of docstrings in
their names or were missing or misusing something like `missing` or
`incorrect`. For example, many of the rules that start with `missing-`
actually enforce a single line somewhere, so they flag 2+ lines as well
as zero.

The first commit contains the changes in `codes.rs`, which I thought was
probably easiest to review
and comment on if any of the names need further refinement. The second
commit contains the rest of
the downstream changes.

| Code | Old name | New name |

|---------------------------------------------------|-----------------------------------------|---------------------------------------------------|
| [`D201`](https://docs.astral.sh/ruff/rules/D201/) |
`blank-line-before-function` | `blank-line-before-function-docstring` |
| [`D202`](https://docs.astral.sh/ruff/rules/D202/) |
`blank-line-after-function` | `blank-line-after-function-docstring` |
| [`D203`](https://docs.astral.sh/ruff/rules/D203/) |
`incorrect-blank-line-before-class` |
`incorrect-blank-line-before-class-docstring` |
| [`D204`](https://docs.astral.sh/ruff/rules/D204/) |
`incorrect-blank-line-after-class` |
`incorrect-blank-line-after-class-docstring` |
| [`D205`](https://docs.astral.sh/ruff/rules/D205/) |
`missing-blank-line-after-summary` |
`incorrect-blank-line-after-docstring-summary` |
| [`D207`](https://docs.astral.sh/ruff/rules/D207/) |
`under-indentation` | `under-indented-docstring-line` |
| [`D208`](https://docs.astral.sh/ruff/rules/D208/) | `over-indentation`
| `over-indented-docstring-line` |
| [`D209`](https://docs.astral.sh/ruff/rules/D209/) |
`new-line-after-last-paragraph` |
`missing-new-line-after-last-docstring-paragraph` |
| [`D210`](https://docs.astral.sh/ruff/rules/D210/) |
`surrounding-whitespace` | `whitespace-around-docstring-text` |
| [`D211`](https://docs.astral.sh/ruff/rules/D211/) |
`blank-line-before-class` | `blank-line-before-class-docstring` |
| [`D212`](https://docs.astral.sh/ruff/rules/D212/) |
`multi-line-summary-first-line` |
`multiline-docstring-summary-on-separate-line` |
| [`D213`](https://docs.astral.sh/ruff/rules/D213/) |
`multi-line-summary-second-line` |
`multiline-docstring-summary-on-first-line` |
| [`D214`](https://docs.astral.sh/ruff/rules/D214/) |
`overindented-section` | `over-indented-docstring-section` |
| [`D215`](https://docs.astral.sh/ruff/rules/D215/) |
`overindented-section-underline` |
`over-indented-docstring-section-underline` |
| [`D300`](https://docs.astral.sh/ruff/rules/D300/) |
`triple-single-quotes` | `unconventional-docstring-quotes` |
| [`D408`](https://docs.astral.sh/ruff/rules/D408/) |
`missing-section-underline-after-name` |
`blank-line-before-docstring-section-underline` |
| [`D410`](https://docs.astral.sh/ruff/rules/D410/) |
`no-blank-line-after-section` |
`missing-blank-line-after-docstring-section` |
| [`D411`](https://docs.astral.sh/ruff/rules/D411/) |
`no-blank-line-before-section` |
`missing-blank-line-before-docstring-section` |
| [`D413`](https://docs.astral.sh/ruff/rules/D413/) |
`missing-blank-line-after-last-section` |
`missing-blank-line-after-last-docstring-section` |
| [`D417`](https://docs.astral.sh/ruff/rules/D417/) |
`undocumented-param` | `undocumented-parameter` |
2026-11-19 11:59:53 -05:00
Brent Westbrook 259397be2a Redirect renamed rules (#30081)
Summary
--

This PR extends our infrastructure for redirecting rule codes to
redirect rule names too, in
preparation for the many renames we have planned before stabilizing
human-readable names. As a proof
of concept, I also renamed
[`missing-return-type-undocumented-public-function` (`ANN201`)], which
seemed like a very clear rename target, having been accidentally renamed
in #3283.

The first commit contains the redirect changes, and the second commit
contains the `ANN201` rename,
along with the tests it allows us to exercise.

[`missing-return-type-undocumented-public-function` (`ANN201`)]:
https://docs.astral.sh/ruff/rules/missing-return-type-undocumented-public-function/

Test Plan
--

New CLI tests
2026-11-10 10:02:17 -05:00
Brent Westbrook d777c9a542 [ruff] Add renamed-rule (RUF202) (#30079)
Summary
--

This PR is another step toward renaming many of our rules. It adds the
`renamed-rule`
rule, currently applying to rule codes, to migrate redirected rule
selectors in configuration files.

The first commit factors out some shared infrastructure from `RUF201`,
and the second adds the new
rule and its tests.

I also removed the warning for using a redirected code in configuration
selectors even in stable but preserved
the warning in the CLI, which the rule does not cover. Removing the
warning allows deleting a lot of code that apparently existed only to
support emitting the warning and resolved an attached TODO about where
the warning belonged.

Test Plan
--

New mdtests that are pretty minimal since we rely on much of the same
code as `RUF201` and a CLI
test exercising the combination of the two TOML rules
2026-11-09 16:37:45 -05:00
stuandBrent Westbrook 4cec5d2d87 [pylint] Implement no-method-argument (PLE0211) (#29748)
## Summary

We use Ruff for linting in our browser based IDE and supplement it with
a few checks that are helpful for our users, particularly novice
programmers. Forgetting to include `self` in a method is common enough
that we already have our own check for it.

N805 partially covers this: it catches methods whose first parameter
isn't named `self`, but it doesn't report methods with no parameters at
all. This is an easy mistake when a method needs no arguments beyond the
instance: the user writes `def refresh():` instead of `def
refresh(self):`.

This PR adds Pylint's [`no-method-argument` /
E0211](https://pylint.readthedocs.io/en/latest/user_guide/messages/error/no-method-argument.html)
as `PLE0211`, in preview. It's tracked in
[#970](https://github.com/astral-sh/ruff/issues/970). Following the
discussion in [#11605](https://github.com/astral-sh/ruff/pull/11605),
this is a separate rule; N804 and N805 keep their existing scope.

I've classified it as Suspicious because a zero-argument function
defined in a class can still be called directly through the class.
Calling it through an instance fails, so the definition is often a
mistake, but it can be intentional. The documentation explains this
limitation and the `**kwargs` exemption retained from Pylint E0211.

There is no automatic fix: adding a receiver and making the function
static express different intentions.

## Test Plan

- All nine Pylint mdtest files pass, including the new rule's examples
and diagnostic snapshot. These cover instance/class methods, static
methods, keyword-only and variadic signatures, special methods, custom
decorators, suppressions and independent N804/N805 selection.
- Generated documentation and schema checked with `cargo dev
generate-all --mode check`.
- Applicable `prek` checks pass for all six changed files.
- CLI smoke test reports empty instance/class methods and accepts an
empty static method.

---------

Co-authored-by: Brent Westbrook <brentrwestbrook@gmail.com>
2026-11-06 21:48:52 +00:00
Tom Kuson ff1770df69 [flake8-async] Implement pytest-raises-exception-group (ASYNC401) (#28772)
## Summary

Implements ASYNC401 as pytest-raises-exception-group to recommend
`pytest.RaisesGroup` for explicit checks of expected exceptions and
group structure.

`pytest.raises(ExceptionGroup)` can be used legitimately, however, so I
tentatively picked the pedantic category.

Didn't implement an autofix as there is no way to infer what exceptions
the user intended to catch.

This checks more than the upstream rule, but that's by design:
https://github.com/python-trio/flake8-async/issues/475

Relates to #8451

## Test Plan

`cargo nextest run`
2026-11-06 15:52:07 -05:00
Saber OueslatiandBrent Westbrook 19c01a6639 [security] Implement tarfile-ignore-zeros-true (#28680)
## Summary

Adds the preview rule `tarfile-ignore-zeros-true` for statically truthy
`ignore_zeros` in `tarfile` openers. This setting skips empty and
invalid blocks, so an archive may yield members that a parser stopping
at those blocks would not see. The rule covers `tarfile.open`,
`TarFile(...)`, and `TarFile` opening class methods.

Closes #27310

## Test Plan

The new mdtest covers flagged and unflagged calls. The targeted mdtest
passes.

---------

Co-authored-by: Brent Westbrook <brentrwestbrook@gmail.com>
2026-11-03 14:38:42 -05:00
Charlie Marsh 9525a0c4e8 [suspicious] Add shared-clock-mock (#29074)
## Summary

This PR adds a `shared-clock-mock` rule in preview. Patching a clock or
sleep function on a shared module can affect unrelated threads or tasks,
including when the target is qualified with the consuming module:

```python
from unittest.mock import Mock, patch

from example import worker

sleep = Mock()
with patch.object(worker.time, "sleep", sleep):
    worker.retry()
```

Instead, you should replace the consuming module's binding to keep the
fake local:

```python
from types import SimpleNamespace
from unittest.mock import Mock, patch

from example import worker

sleep = Mock()
with patch.object(worker, "time", SimpleNamespace(sleep=sleep)):
    worker.retry()
```

We also flag patches of wall-clock, monotonic, and performance-counter
readings, plus `asyncio.sleep`. The rule recognizes `patch`,
`patch.object`, pytest-mock fixtures, and `monkeypatch.setattr` /
`delattr`. (Nested `.time` and `.asyncio` targets use a naming
heuristic, so a fixture that already installed a private clock can
produce a false positive.)

## Case analysis

The ecosystem run adds 601 diagnostics across eight projects.

### Counting sleep calls in LangChain

This reduced version of LangChain’s device-login test records the
polling interval before and after the server asks the client to slow
down.

```python
sleeps = []
monkeypatch.setattr(oauth_module.time, "sleep", sleeps.append)
login_chatgpt_device(store_path=tmp_path / "x.json", poll_interval=2.0)
assert sleeps[:2] == [2.0, 7.0]
```

The OAuth module does `import time`, so `oauth_module.time` and `time`
are the same object. If another thread calls `time.sleep(1)` between the
two polls, the recorder sees `[2.0, 1, 7.0]`. Installing
`SimpleNamespace(sleep=sleeps.append)` on `oauth_module.time` keeps that
call out of the list.

### Running out of clock readings in Superset

Superset tests how long a screenshot request waits for a lock. It
patches `superset.dashboards.api.time.monotonic` with
`side_effect=[10.0, 10.5, 11.0]` and patches `time.sleep` on the same
module. An unrelated `time.monotonic()` can consume the next reading.
The request can then see the deadline early or exhaust the iterator and
raise `StopIteration`. A private clock for `superset.dashboards.api`
needs both `monotonic` and `sleep`.

### Retrying an async request in Prefect

Prefect simulates three failed SQS requests and expects one two-second
backoff. The test uses
`@patch("prefect_aws.observers.ecs.asyncio.sleep")`, but the observer
does `import asyncio`. A second task awaiting `asyncio.sleep(0)` would
also call the mock and break `assert_called_once_with(2)`.

### A fixture that already installed a private clock

Ruff can see the same patch in two tests even though only one reaches
the shared module. For example, an autouse fixture can replace
`worker.time` before the test starts.

```python
@pytest.fixture(autouse=True)
def private_clock(monkeypatch):
    monkeypatch.setattr(worker, "time", SimpleNamespace(sleep=lambda _: None))


def test_retry(monkeypatch):
    sleep = Mock()
    monkeypatch.setattr(worker.time, "sleep", sleep)  # shared-clock-mock
    worker.retry()
```

The warning in `test_retry` is a false positive. At runtime the receiver
is the fixture’s `SimpleNamespace`. If the fixture returns that
namespace, the test can use `monkeypatch.setattr(private_clock, "sleep",
sleep)` and Ruff accepts it.

### A package with its own `time` module

Gevent ships a `gevent.time` module with its own `sleep` binding. The
dotted string is enough for Ruff to flag this reduced example.

```python
import time
from unittest.mock import patch

original_sleep = time.sleep
with patch("gevent.time.sleep"):
    assert time.sleep is original_sleep
```

The assertion passes. Callers that look up `gevent.time.sleep` see the
patch. A caller of standard-library `time.sleep` still gets the original
function. Ruff infers the owner from the `.time.sleep` suffix in a
string target, so it reports the wrong module here.
2026-10-26 11:15:49 -07:00
Anish Giri 47a28e3a2e [complexity] Add unnecessary-regular-expression-compile (#25533)
## Summary

Adds `unnecessary-regular-expression-compile` in preview. It
flags `re.compile(p).match(s)` and similar, where the compiled pattern
is only ever used right there. In that case `re.match(p, s)` does the
same thing without the extra object. Patterns stored in a variable are
left alone, since that usually signals the pattern is meant to be
reused.

Closes #14691.

## Test Plan

`cargo test -p ruff_mdtest --test mdtest --
unnecessary-regular-expression-compile`
2026-10-20 12:51:26 -04:00
16bc1bc365 [pylint] Add a configurable allowlist for magic-value-comparison (PLR2004) (#18961)
## Summary

This PR allows users to specify a custom set of whitelisted values for
magic value comparisons in PLR2004. The setting is named
`pylint.allow_magic_values`, which is consistent with a similar setting
`pylint.allow_magic_value_types`
The previous hard-coded allow-list was moved to the default for
`pylint.allow_magic_values`, giving users full control over what is and
what is not a whitelisted value. This setting is added in addition to
the `pylint.allow_magic_value_types` and does not replace it. Any value
that is whitelisted due to either of these settings is not considered a
linting violation.

Note that as far as I could tell, no other setting allows floats or
complex numbers as inputs, so I created a few helper methods to deal
with these properly (mainly relating to floating point variation).


## Test Plan

I have tested the settings with a number of cases manually in a
repository I work on regularly. I have not added any extensive
(combinatorial) tests to the test suite.

## Note

I don't know whether you have any policy on using or disclosing the use
of code generators, but I definitely relied heavily on this to solve
some of the issues I ran into during development. Ultimately, all code
was reviewed by me before pushing.

fix: #10009

---------

Co-authored-by: DaniBodor <d.bodor@esciencecenter.nl>
Co-authored-by: Brent Westbrook <36778786+ntBre@users.noreply.github.com>
Co-authored-by: Brent Westbrook <brentrwestbrook@gmail.com>
2026-10-16 16:48:55 -04:00
Brent Westbrook ef23c9c39e Update default and latest Python versions for 3.15 (#28792)
Summary
--

This PR updates our default Python version to 3.11, in line with 3.10
reaching [EOL] next month, and
updates our latest Python version to 3.15. I followed last year's PR
(#20725) to find everywhere
that needed to change. Fortunately there were not as many test changes
needed as last year's
deferred annotation issues.

I also updated the language classifier in our pyproject.toml.

[EOL]: https://devguide.python.org/versions/#supported-versions

Test Plan
--

Existing tests with updated snapshots. Most of the updates were to
snapshots for TC001, TC002, and
TC003, which now default to the lazy-import fix.

After updating the snapshots, I tried to make sure we still had coverage
for whatever changed. That
meant adding a few more mdtests for the TC rules, and one small mdtest
for RUF017 to restore
coverage for the `functools.reduce` fix.
2026-10-09 12:26:57 -04:00
Micha Reiser 4776a20c73 [ruff] Support Unicode dummy variable names (#28722)
Fixes #28721
2026-10-09 12:26:57 -04:00
David Salvisberg 5409291eb1 [flake8-type-checking] Add the notion of runtime-ambiguous references (#26508)
This is a partial solution for #16412

I would still like to add something like
`runtime-evaluated-generic-subscripts`, but that will require further
consideration about how the presence of such subscripts should affect
the rest of the type expression, or in more extreme cases, the other
annotations in the function/class definition.

## Summary

For things like SQLAlchemy's `Mapped` the evaluation of the annotations
only requires a subset of all the symbols to be resolvable at runtime,
this is sometimes necessary to make forward references to other models
work without causing import cycles.

But this means we can neither assume that the annotations are
runtime-required, nor can we assume, that they are typing-only. So we
should assume the referenced binding is already in its correct execution
context, i.e. we should neither emit TC001-003, nor TC004 violations.

Instead of adding two additional settings now and potentially two more
settings later, the existing two settings for runtime-required
annotations now accept a table in addition to the list to flag
individual imports with individual runtime requirements.

For example:
```toml
[lint.flake8-type-checking.runtime-evaluated-base-classes]
"pydantic.BaseModel" = "required"
"sqlalchemy.orm.DeclarativeBase" = "ambiguous"

[lint.flake8-type-checking.runtime-evaluated-decorators]
"pydantic.validate_call" = "required"
"sqlalchemy.orm.declared_attr" = "ambiguous"
```

## Test Plan

`cargo nextest run`
2026-10-06 21:13:09 +00:00
Saber Oueslati 9c37f03910 [ruff] Allow docstrings in strict mode (RUF067) (#28679)
## Summary

Closes #27416.

With `lint.ruff.strictly-empty-init-modules = true`, RUF067 flagged
docstrings in `__init__.py`. Strict mode now allows module and attribute
docstrings, as non-strict mode already does. Other code remains flagged,
including bare strings that are not docstrings. The rule and option
documentation now reflect this behavior.

## Test Plan

Added a bare string that is not a docstring to the RUF067 fixture and
regenerated the snapshots. The snapshots confirm that strict mode
permits module and attribute docstrings while flagging the bare string.
The focused RUF067 tests pass. I also verified that a docstring-only
`__init__.py` passes in strict mode.
2026-10-01 16:25:26 -04:00
Charlie Marsh a4e7c20ca0 Add rule for context manager iterator annotations (UP052) (#29000)
## Summary

The `contextmanager` and `asynccontextmanager` decorators require
generators, which support methods not guaranteed by the `Iterator` and
`AsyncIterator` protocols. Typeshed deprecates the overloads that accept
these iterator annotations.

Add the preview rule `context-manager-iterator` (UP052) to identify
these annotations and offer a fix. For example:

```python
from collections.abc import Iterator
from contextlib import contextmanager

@contextmanager
def example() -> Iterator[int]:
    yield 1
```

The fix replaces `Iterator[int]` with `Generator[int, None, None]`. For
an async context manager, it replaces `AsyncIterator[int]` with
`AsyncGenerator[int, None]`. On Python 3.13 and later, it omits the
default type arguments and uses `Generator[int]` or
`AsyncGenerator[int]`. If a synchronous generator returns a value, the
fix uses `object` as its return type.

The fix is unsafe because it changes runtime annotations and may
introduce an import. The rule checks functions whose innermost decorator
is a context manager and whose body contains a `yield` or `yield from`.
2026-09-30 14:34:27 +00:00
Charlie Marsh fe9f065a50 [flake8-tidy-imports] Add extend-banned-api (#28644)
## Summary

Add `lint.flake8-tidy-imports.extend-banned-api` so we can add banned
APIs without repeating an inherited `banned-api` table. Entries in
`extend-banned-api` override entries with the same key in `banned-api`,
including their diagnostic messages.

For example, a child `ruff.toml` can add a ban while retaining the bans
from its base configuration:

```toml
extend = "../ruff.toml"

[lint.flake8-tidy-imports.extend-banned-api]
"typing.TypedDict".msg = "Use typing_extensions.TypedDict instead."
```

This follows the existing `extend-aliases` behavior: the base and
extension tables inherit independently, and we merge them after
resolving configuration inheritance. A child can replace either table,
or clear it with `{}`. The change includes option documentation, the
generated JSON schema, and CLI coverage for standalone bans,
inheritance, message overrides, and clearing either table.
2026-09-16 13:05:26 +00:00
JohnKagundaandBrent Westbrook 6748126256 [ruff] Add rule for default values on method receivers (RUF077) (#26700)
## Summary

Adds a new Ruff rule that flags method receiver parameters (`self` /
`cls`) when they are given a default value.

The rule targets functions defined directly inside a class body and uses
semantic context to ensure it only applies to methods, not standalone
functions. It determines the receiver kind, inspects the first
positional parameter, and reports a diagnostic when that receiver has a
default value.

Closes #25820

## Test Plan

Tested by adding a Ruff fixture and snapshot for RUF077, and verifying
the rule is triggered for methods whose receiver parameter has a default
value.

Files added/updated for testing include:

- `crates/ruff_linter/resources/test/fixtures/ruff/RUF077.py`
-
`crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF077_RUF077.py.snap`

I also validated the rule integration by building Ruff locally after
registering the rule and hooking it into AST statement analysis.

---------

Signed-off-by: John Kagunda <rafaeljohb@gmail.com>
Co-authored-by: Brent Westbrook <36778786+ntBre@users.noreply.github.com>
2026-09-09 10:47:24 -04:00
chiri 088b7b5f77 Add another example and glob reference for lint.per-file-ignores (#28106)
## Summary

I came across this syntax while exploring the `glob` crate and found it
quite useful. I think it would be worth adding a short example to the
documentation.

## Test Plan
2026-08-28 12:39:33 -04:00
Brent Westbrook aad0e909ef Allow rules without codes (#28049)
Summary
--

This PR allows adding rules that only belong to categories and only have
names rather than requiring
a linter group and code.

The first non-empty commit uses `Rule::name` instead of
`Rule::noqa_code` throughout the linter tests, causing a huge number of
file renames without changes.

The second commit updates `FixTable` from a mapping of `SecondaryCode ->
(name, fix_count)` to
`DiagnosticId -> (Option<SecondaryCode>, fix_count)`. This doesn't
really change its usage but
involves minor diffs to a substantial number of lines. It also allows us
to drop some of the special
`hashbrown` handling and the `hashbrown` dependency in `ruff_linter`,
which is nice.

The third commit contains the bulk of the change, including the macro
changes needed to support
`map_codes` entries like that for the `pytest-fixture-autouse` rule in
the fourth commit:

```rust
() => rules::ruff::rules::PytestFixtureAutouse,
```

These changes are pretty mechanical overall, just handling cases where
the linter or noqa code could
be missing, which fortunately seemed pretty straightforward in every
case.

The fourth commit takes advantage of these changes to reinstate `RUF076`
as our first purely
`pedantic` rule. I'm happy to drop that if it's too controversial or
opens too many questions about
the previously-removed rule and its code, but I thought it was nice to
have a motivating example. We
moved this rule from `preview` to `removed` because it was too pedantic
for the `RUF` category, even
in preview, so it's exactly the kind of rule we can support now with the
categories.

Finally, the fifth commit updates the contributing docs to reflect that
linters and codes are
optional. This may need to be adjusted if we back out the `RUF076`
change.

Test Plan
--

Existing tests, plus a few new ones for `pytest-fixture-autouse`
2026-08-27 11:26:35 -04:00
Brent WestbrookandMicha Reiser 50a4d7fd10 Document the new category selectors (#27906)
Summary
--

This includes the user-facing updates to our linter docs and selection
settings to accompany #27666.

Test Plan
--

A few existing snapshot updates but mostly users reading this

---------

Co-authored-by: Micha Reiser <micha@reiser.io>
2026-08-27 11:26:33 -04:00
Brent Westbrook ada87950ea Introduce category selectors (#27666)
## Summary

This PR introduces clippy-style rule categories that can be used
alongside existing linter-based categories in preview. The categories
have a lower `specificity` than linter groups, meaning that `select =
UP` and `ignore = correctness` will not ignore `UP` correctness rules.
In general this leads to more rules being enabled than the alternative
we considered where categories and linter groups had equal precedence,
which makes it seem like a safer default. We can revisit this if it
proves to be unintuitive, or we can add a Cargo-style `priority` field
in the worst case.

I've tried to organize the commits such that this can be reviewed
commit-by-commit and could also be split into multiple PRs. The first
two commits update the `ViolationMetadata` macro to allow providing a
`category` argument and add such arguments for all rules. This part
could be a standalone change without exposing the categories to users
but still depends on reaching consensus on all rule categories. The
second pair of commits allows using the new categories as selectors
alongside existing selectors, including some precedence tests with other
selector types.

This mostly addresses #1774, but there are some sub-issues there to
resolve before closing the issue.

## Test Plan

New CLI tests and a new mdtest suite around rule precedence
2026-08-27 11:26:33 -04:00
a9130f3381 [pyupgrade] Add rule to replace while 1 with while True (while-one, UP048) (#27190)
## Summary

A very simple pyupgrade-style rule to migrate Python-2 style infinite
while loops (`while 1`) into more idiomatic `while True`.

Deliberately kept this rule very simple and scoped to Python 2 code
migration as per discussion in linked issue.

Closes #21870

## Test Plan

1. Look at new mdtest
2. Look at ecosystem resulst
3. I ran `cargo run -p ruff -- check --no-cache --select=UP048
../pywin32` (with and without fix)

## Coding Agent disclaimer

Code was initially written by Claude Opus 5. Fully human reviewed.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Brent Westbrook <36778786+ntBre@users.noreply.github.com>
2026-08-12 17:48:45 -04:00
Brent Westbrook 231eb3389b Add an option to opt out of human-readable names (#27160)
Summary
--

This PR closes #26320 by adding the new
`lint.prefer-rule-codes-in-output` option that defaults to
`false` and disables the use of human-readable rule names in most output
formats, even in preview.
This does not affect formats like JSON that include the name and code as
separate fields.

Test Plan
--

New CLI test enabling the option, as well as manual testing in the
playground:

<img width="597" height="299" alt="image"
src="https://github.com/user-attachments/assets/e56e3681-5892-4dd6-ba66-1a91bc9529d3"
/>

and in VS Code:

<img width="738" height="396" alt="image"
src="https://github.com/user-attachments/assets/98ee3baa-c1fe-421c-a9a1-d63e5f4cc23b"
/>

Note the human-readable name in the `ruff: ignore` comment, which shows
that preview is enabled, while the `(F401)` in the output shows that the
setting is being used.
2026-07-28 14:04:20 -04:00
LHMQ878andClaude Opus 5 023b1db30e [flake8-import-conventions] Document that extend-aliases can override default aliases (#27191)
Closes #17097

## Summary

The `extend-aliases` documentation only stated that entries "will be
added to the `aliases`
mapping", which does not convey that an entry for a module that already
has a default alias
*replaces* that default. As noted in the issue, this makes it possible
to change or opt out
of a default alias without restating the whole `aliases` mapping.

This is a documentation-only change; the behaviour already works this
way because the
settings resolver applies `extend-aliases` on top of `aliases` via
`HashMap::extend`, so
matching keys are overwritten.

## Test Plan

Verified the documented behaviour against `ruff 0.12.4` using this
sample file:

```python
import numpy
import numpy as np
```

| Config | Result |
| --- | --- |
| default | `ICN001 `numpy` should be imported as `np`` on line 1 |
| `numpy = "numpy"` under `extend-aliases` | `ICN001 `numpy` should be
imported as `numpy`` on line 2, i.e. the aliased import is now the
violation |
| `numpy = "nmp"` under `extend-aliases` | both lines flagged, requiring
`nmp`, so the default `np` is fully replaced |

Also ran:

- `cargo fmt --check` - passes.
- `cargo dev generate-all` - regenerated `ruff.schema.json` so the new
description is
reflected there; confirmed the file is still valid JSON and contains the
updated text.

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-07-28 15:14:36 +00:00
Brent Westbrook b30f040232 Stabilize new default rules (#27035)
This PR stabilizes the expanded default rule set currently in preview
and adds a new generated `Default Rules` page to the docs to avoid
needing to include a lengthy selector block in multiple places.
2026-07-23 13:38:29 -04:00
Charlie Marsh 301b7ed4d6 [ty] Share heap-backed parser names with CharStr (#26594)
## Summary

This PR changes `ruff_python_ast::Name` from a 24-byte `CompactString`
to a 16-byte immutable `CharStr` from
[`astral-sh/char_str`](https://github.com/astral-sh/char_str).

`char_str` is an Astral-maintained fork of
[`lean_string`](https://github.com/ryota2357/lean_string) that provides
compact owned strings with mutable and immutable variants: growable
`CharString` for construction and immutable, exactly allocated `CharStr`
for storage. (It also provides Salsa and get-size features.)

Names up to 16 UTF-8 bytes remain inline, static names remain
allocation-free, and longer names use an exactly sized,
reference-counted allocation with no unused capacity.

Removing eight bytes from every `Name` also shrinks common AST nodes.
For example, `Identifier` and `ExprName` drop from 40 to 32 bytes, while
`ExprAttribute`, `StmtFunctionDef`, `StmtClassDef`, and several other
variants each drop by eight bytes.

The parser interns names that exceed the inline capacity, so repeated
longer names share one backing allocation within a parser invocation.

## Why 16 bytes?

Across the full `mypy_primer` corpus, there 20.8 million name
occurrences:

| UTF-8 length | Occurrences | Share | Unique name/file pairs | Share |
|---|---:|---:|---:|---:|
| 1–16 bytes | 18,955,757 | 91.02% | 3,192,424 | 79.42% |
| 17–24 bytes | 1,348,894 | 6.48% | 529,826 | 13.18% |
| 25+ bytes | 522,376 | 2.51% | 297,575 | 7.40% |
| Total | 20,827,027 | 100% | 4,019,825 | 100% |

The 16-byte cutoff keeps 91% of occurrences inline while saving eight
bytes for every occurrence. The 1–16-byte bucket alone removes 151.6 MB
of handle storage across the corpus.

The tradeoff is the 17–24-byte bucket: `CompactString` stored those
names inline, while `CharStr` allocates once per unique name within a
file. But the interning amortizes that cost when a name repeats. Names
longer than 24 bytes already allocated on `main`; for those names, this
change both reduces the handle size and deduplicates repeated backing
allocations.

## Memory impact

Accounting for the observed per-file multiplicities and structural
sharing, modeled `Name` storage across the corpus changes as follows:

| | `main` | This PR | Difference |
|---|---:|---:|---:|
| `Name` handles and backing storage | 526.18 MB | 366.27 MB | -159.91
MB (-30.4%) |

The current [instrumented memory
report](https://github.com/astral-sh/ruff/pull/26594#issuecomment-4906725175)
shows a consistent reduction in total retained memory:

| Project | `main` | This PR | Difference |
|---|---:|---:|---:|
| flake8 | 29.21 MB | 28.71 MB | -1.69% |
| trio | 71.01 MB | 70.01 MB | -1.41% |
| sphinx | 168.81 MB | 166.82 MB | -1.18% |
| prefect | 454.75 MB | 449.06 MB | -1.25% |

Within those totals, `parsed_module` decreases by roughly 2.1% and
`semantic_index` by 2.4–2.7%. Several name-heavy collections decrease by
considerably more.
2026-07-16 14:53:48 -04:00
Brent Westbrook f3cf7c81fa [ruff] Add rule-codes-in-selectors (RUF201) (#26772)
Summary
--

This PR adds a new lint rule for TOML config files that checks for the
use of rule codes as
selectors and offers a fix to replace them with human-readable names. At
a high-level, the
implementation just deserializes a TOML config into a stripped down
version of our normal
configuration types and then checks each of its `Spanned` selector
entries. Unless I oversimplified
this too much, it didn't end up being as tricky as I thought. The main
tricky part was adding basic
support for fixes in TOML files, but even this was pretty
straightforward.

Codex was concerned about calling this a safe fix because applying the
fix with `--preview`, or
another temporary way of enabling preview, would break the config if
preview isn't always enabled.
That seemed to go beyond our usual fix safety policy to me, but I'm also
happy to mark the fix as
unsafe if that's preferable.

Test Plan
--

New tests covering all of the expected selectors and new CLI tests to
make sure that `ruff.toml`
files get linted and respect various ways of suppressing fixes.
Previously we only linted
`pyproject.toml` files for `RUF200` and bypassed some of the checks in
`LintContext`. I left the
change to use `LintContext` as a separate commit since it also affects
`RUF200` and I briefly
considered splitting it off into a separate PR.
2026-07-16 10:05:29 -04:00
Brent Westbrook 815468ba20 [ruff] Add rule to use human-readable names in ruff:ignore comments (RUF106) (#26682)
Summary
--

This is the second of our migration rules for moving from `noqa`
comments to `ruff:ignore` comments
with human-readable names. `RUF106` performs the second part of this
transformation, converting
`ruff:ignore` comments that use rule codes to `ruff:ignore` comments
with human-readable names.

The rule skips unknown codes, external and otherwise. Unlike `RUF105` I
don't think there's anything
sensible we could do with those here.

Test Plan
--

New mdtests and a CLI test for the combination of `RUF105` and `RUF106`.

I did a local grep of our ecosystem projects and didn't find any
`ruff:ignore`-style suppressions, so I don't expect any ecosystem hits
for this.
2026-07-10 16:34:30 -04:00
Brent WestbrookandMicha Reiser a907a12075 [ruff] Add rule to replace noqa comments with ruff:ignore (RUF105) (#26423)
Summary
--

This is the first in a series of migration rules to help users move from
`noqa` comments with rule
codes to `ruff:ignore` comments with names. This rule simply replaces
`noqa: codes` with
`ruff:ignore[codes]` (and the file-level variants), deferring the
transformation of codes to names
to a follow-up rule. This rule may be useful on its own without the
codes -> names rule, assuming we
stabilize `ruff:ignore` in the next minor release without stabilizing
human-readable names.

The rule skips any comment consisting entirely of known `external`
selectors, while still emitting diagnostics for totally unknown codes.
We also skip file-level `flake8: noqa` directives assuming they are
intended to be shared with flake8.

I initially wrote a small, standalone implementation in the rule file
itself, but it had to be
combined with the `RUF100` implementation to leave unused `noqa` codes
out of `RUF105` to be cleaned
up by `RUF100` instead, as I note in the mdtest for this case.

Test Plan
--

New mdtests

I also expect a huge number of ecosystem results on this PR, possibly so
many that the check times out.

---------

Co-authored-by: Micha Reiser <micha@reiser.io>
2026-07-09 16:45:20 -04:00
Ed Page 83c3473c28 [pyupgrade] Lint and fix use of deprecated abc decorators
Summary

Report and fix deprecated `abc` decorators in preparation for their
removal.
While deprecated since Python 3.3,
reporting of deprecation warnings is not released yet.
Removal would happen 3-5 years after those warnings are emitted.

Fixes #25105

Test Plan

Added an mdtest to cover the most basic case.
There already seems to be a pylint for switching from
`x = abstractproperty(get, set)` so I left that out.
That case is relevant because pre-deprecation, the documentation didn't
show `@abstractproperty` usage.
2026-07-06 10:25:51 -05:00
Brent Westbrook 485ebab5de Remove RUF076 name from schema (#26371)
Summary
--

I didn't think to rebase #26240 after merging #25887 and there was a
conflict in the schema. This should fix the current failure on main.

Test Plan
--

CI
2026-06-25 12:36:30 -04:00
Brent Westbrook 572b31e237 [ruff] Remove pytest-fixture-autouse (RUF076) (#26240)
Summary
--

This PR removes `RUF076` that was added in #25477 and closes #26178. It
should also reopen #12491.

The reason for the removal is that this rule is very opinionated. I knew
that going in, but I failed
to consider the effect of adding a pedantic rule to the `RUF` selector,
which many preview users
enable as a whole.

The implementation was okay otherwise and can be reinstated once we have
a better category for the
rule, which #1774 should help with.

We initially opted for a full revert, but marking the rule as removed
both avoids an invalid configuration error for projects that already
`ignore` the rule (although they will still see a warning) and prevents
another rule in the future from reusing the code.

I don't believe we've done this before, but we can also reinstate the
rule simply by switching its metadata back from `removed_since` to
`preview_since` (and updating the mdtests, which I also opted to
preserve).
2026-06-25 08:35:11 -07:00
Brent Westbrook f703f219d7 Allow human-readable names in rule selectors (#25887)
## Summary

This PR enables using rule names as selectors in preview by also
attempting to parse a selector as a human-readable name in
`UnresolvedRuleSelector::resolve`. If this succeeds and preview is
enabled, the rule is activated, and if preview is disabled you get a
custom error message.

## Test Plan

A few new CLI tests. I figured the tests from
https://github.com/astral-sh/ruff/pull/26113 cover the shared behavior
for the other selectors well enough and just focused on `select` as an
example for both the CLI and config file.
2026-06-25 08:34:26 -07:00
Gabriel Mitelman TkaczandAmethyst Reese a664a9c366 [pydocstyle] Prevent property docstrings starting with verbs (D421) (#23775)
> Disclaimer: The implementation of this rule was generated by Anthropic
Claude Sonnet 4.6 under human supervision, using the existing `D401`
(`NonImperativeMood`) rule as a reference pattern. The design decisions
were specified by the human author, and the entirety of the generated
code was subsequently also reviewed by the human author.

## Summary

Added a new preview rule to the `pydocstyle` checker to prevent
`@property` docstrings from starting with return/getter verbs, as
specified by the [relevant Google Python style guide
section](https://google.github.io/styleguide/pyguide.html#383-functions-and-methods).

Example: `"Returns the Bigtable path."` (wrong) vs `"The Bigtable
path."` (correct)

Disallowed first words for this implementation (case-insensitive):
`return`, `returns`, `get`, `gets`, `yield`, `yields`, `fetch`,
`fetches`, `retrieve`, `retrieves`.

This rule is enforced whenever `D421` is enabled; it is not restricted
to any `lint.pydocstyle.convention` value.

Closes #16931

## Test Plan

Added `D421.py` to the shared `pydocstyle::tests::rules` test matrix for
`Rule::PropertyDocstringStartsWithVerb`. `LinterSettings::for_rule`
enables preview for the rule.

The fixture `D421.py` covers:

- Bad: `@property` docstrings starting with each of the 10 disallowed
verbs, including a multi-line case
- Good: attribute-style `@property` docstrings (`"""The bar value."""`)
- Good: `@cached_property` with an attribute-style docstring
- Not flagged: regular methods and top-level functions whose docstrings
start with the same verbs

Verified all existing `pydocstyle` tests continue to pass:

```sh
CARGO_PROFILE_DEV_OPT_LEVEL=1 INSTA_FORCE_PASS=1 INSTA_UPDATE=always cargo nextest run -p ruff_linter -- pydocstyle
# 80 passed
```

Manual smoke-check:

```sh
cargo run --bin ruff -- check crates/ruff_linter/resources/test/fixtures/pydocstyle/D421.py --no-cache --preview --select D421
# Found 11 errors.
```

---

Note: the same Google Python style guide specification also states that
this style applies to an attribute or a function argument. These were
not implemented as part of this PR because separate selectors would
allow users to choose those checks individually.

---------

Co-authored-by: Amethyst Reese <amethyst@n7.gg>
2026-06-15 14:32:50 -07:00
43fefbaf34 [ruff] Ban pytest autouse fixtures (RUF076) (#25477)
## Summary

- Closes https://github.com/astral-sh/ruff/issues/12491

This PR introduces a new Ruff-specific lint rule (`RUF076`) in the
preview namespace to ban `pytest` fixtures that set the parameter
`autouse=True` in the decorator constructor.

Implicitly running autouse fixtures is discouraged because it hides test
dependencies and can introduce subtle side effects (especially when
defined in shared `conftest.py` files), making the test suite harder to
reason about and debug. Explicit parameter injection is preferred.

> [!NOTE]
> A default banning of all autouse fixtures is opinionated; we may want
to wait for further configuration settings (such as filtering by scope
or restricting to `conftest.py` files) and appropriate defaults before
taking this rule out of preview.

### Examples

#### Basic
```python
# Avoid
@pytest.fixture(autouse=True)
def my_fixture():
    ...

# Prefer
@pytest.fixture()
def my_fixture():
    ...

def test_foo(my_fixture):
    ...
```

#### Advanced (Combining Fixtures)
Instead of using `autouse=True` to avoid repetitive declarations in test
parameters, multiple related fixtures can be aggregated into a single
high-level fixture and requested explicitly:
```python
# Avoid
@pytest.fixture(autouse=True)
def db():
    return Database()

@pytest.fixture(autouse=True)
def cache():
    return Cache()

@pytest.fixture(autouse=True)
def mock_email_client():
    return MockEmailClient()

def test_user_creation():
    ...

# Prefer
@pytest.fixture
def db():
    return Database()

@pytest.fixture
def cache():
    return Cache()

@pytest.fixture
def mock_email_client():
    return MockEmailClient()

# Combine related dependencies into a single high-level fixture
@pytest.fixture
def app_context(db, cache, mock_email_client):
    return AppContext(db=db, cache=cache, email=mock_email_client)

# Declare only the combining fixture in the test
def test_user_creation(app_context):
    ...
```

### Future Enhancements
Developer `TODO` comments have been added to the checker function to
consider adding settings for:
1. Only flagging this rule when the fixture is defined inside a
`conftest.py` file.
2. Only flagging this rule when the fixture has a specific scope (e.g.
`function` scope, which is the default and typically the most costly),
supporting a whitelist or blacklist approach.

### References
- [`pytest` documentation: Sharing fixtures across classes, modules,
packages or
session](https://docs.pytest.org/en/stable/how-to/fixtures.html#scope-sharing-fixtures-across-classes-modules-packages-or-session)
- [`pytest` documentation: Fixtures can request other
fixtures](https://docs.pytest.org/en/stable/how-to/fixtures.html#fixtures-can-request-other-fixtures)

## Test Plan

Added comprehensive test cases in a new test fixture file `RUF076.py`.
The rule has been registered under `preview_rules` in
`crates/ruff_linter/src/rules/ruff/mod.rs` and verified using snapshot
testing:
```sh
CARGO_PROFILE_DEV_OPT_LEVEL=1 INSTA_FORCE_PASS=1 INSTA_UPDATE=always CARGO_PROFILE_DEV_DEBUG="line-tables-only" MDTEST_UPDATE_SNAPSHOTS=1 cargo test -p ruff_linter --rules pytest_fixture_autouse
```
We also ran:
- `cargo dev generate-all` to generate updated linter schemas and
documentation.
- `cargo clippy -p ruff_linter --all-targets --all-features -- -D
warnings` to verify code quality.
- `uvx prek` on all changed files to ensure compliance with the
repository's formatting/linting hooks.

---------

Co-authored-by: Brent Westbrook <36778786+ntBre@users.noreply.github.com>
Co-authored-by: Brent Westbrook <brentrwestbrook@gmail.com>
2026-06-04 14:23:11 -07:00
e51e132831 [flake8-async] Implement yield-in-context-manager-in-async-generator (ASYNC119) (#24644)
## Summary

Implement ASYNC119 from flake8-async, which detects `yield` inside a
context manager (`with` or `async with`) in an async generator function.

This pattern is unsafe because the cleanup of the context manager may be
delayed until the generator is closed, at which point `await` is no
longer allowed. This can lead to resource leaks, `RuntimeError`s from
structured concurrency violations, or other bugs. See [PEP
533](https://peps.python.org/pep-0533/) for details.

The rule suppresses warnings for functions decorated with:
- `@contextlib.asynccontextmanager`
- `@pytest.fixture`
- `@pytest_asyncio.fixture`

These decorators are known to handle async generator cleanup safely.

Part of https://github.com/astral-sh/ruff/issues/8451

## Test plan

- [x] Added test fixture with error and OK cases
- [x] Snapshot tests pass
- [x] `cargo dev generate-all` run
- [x] `uvx prek run -a` passes
- [x] Tested against a real 500k+ LOC codebase — 56 true positive
findings, no false positives

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Brent Westbrook <brentrwestbrook@gmail.com>
2026-06-04 07:33:07 -07:00
JohnKagundaandBrent Westbrook 7ef96bec9a [pydocstyle] Improve discoverability of rules enabled for each convention (#24973)
## Summary

Improves discoverability of `pydocstyle` convention-based rule filtering
by moving the authoritative documentation from the FAQ into the
`lint.pydocstyle.convention` settings reference, per #15217.
Closes #15217.

## Test Plan

Documentation-only change no functional code modifications.

Verification steps:
1. Ran `cargo dev generate-docs` to regenerate `docs/settings.md` and
`ruff.schema.json` from updated docstrings
2. Ran `cargo fmt --all` to ensure Rust formatting compliance
3. Ran `cargo clippy --workspace --all-targets --all-features -- -D
warnings` - no new warnings
4. Served docs locally with `uvx --with-requirements
docs/requirements.txt -- mkdocs serve -f mkdocs.yml` and verified:
- The `lint.pydocstyle.convention` section renders with the new content
   - The FAQ back-reference links to the settings section as intended
   
   ## Screenshots
   
   ### `/ruff/settings/#lint.pydocstyle`

<img width="1920" height="957" alt="image"
src="https://github.com/user-attachments/assets/d35e94a0-0968-43fb-bfe5-dd2821655716"
/>

### `/ruff/faq/#does-ruff-support-numpy-or-google-style-docstrings`

<img width="1920" height="952" alt="image"
src="https://github.com/user-attachments/assets/b8904757-f7c9-43c7-ac20-e0fbdb713acd"
/>

---------

Signed-off-by: RafaelJohn9 <rafaeljohb@gmail.com>
Co-authored-by: Brent Westbrook <36778786+ntBre@users.noreply.github.com>
2026-06-01 14:36:36 +00:00
Anish Giri e1cdbbad86 [ruff] Add fallible-context-manager (RUF075) (#22844)
## Summary

Adds a new rule `RUF075` (preview) that detects
`@contextlib.contextmanager` and `@contextlib.asynccontextmanager`
decorated functions where `yield` is not protected against exceptions.

Closes #15629.

## Details

When a context manager yields without exception protection, cleanup code
after `yield` won't run if an exception is raised inside the `with`
block.

```python
# Bad - cleanup won't run on exception
@contextmanager
def bad():
    print("setup")
    yield
    print("cleanup")  # never runs if exception raised

# Good
@contextmanager
def good():
    print("setup")
    try:
        yield
    finally:
        print("cleanup")  # always runs
```

The rule does **not** flag:
- Yields inside `try` blocks that have a `finally` or `except` handler
- Yields as the last statement of a `with` block (cleanup is delegated
to `__exit__`)
- Yields in terminal position (last statement in the function body, or
immediately before a `return`), where there is no trailing cleanup that
could be skipped

Terminal position is inherited through `if` / `for` / `while` / `match`
branches: a yield that is the last statement of a branch is terminal
only when the enclosing statement is itself terminal.

The rule is in preview mode.

## Test Plan

Tests live in `crates/ruff_linter/resources/mdtest/ruff.md` and are run
via:

```sh
cargo nextest run -p ruff_mdtest -- mdtest::ruff
```
2026-05-20 13:13:11 -07:00
Anish Giri 51a7c2e7c8 [ruff] Add incorrect-decorator-order (RUF074) (#23461)
## Summary

Implements detection of incorrect decorator ordering on functions and
methods (RUF071).
Decorators are applied bottom-up, so certain stdlib decorator
combinations cause runtime errors or silent wrong behavior when placed
in the wrong order. For example, `@abstractmethod` above `@property`
results in `AttributeError: __isabstractmethod__`.

Detects known-bad pairs involving:
- `abc.abstractmethod` (+ deprecated `abstractclassmethod`,
`abstractstaticmethod`, `abstractproperty`)
- `builtins.property`, `builtins.classmethod`, `builtins.staticmethod`
- `contextlib.contextmanager`, `contextlib.asynccontextmanager`
- `functools.cache`, `functools.cached_property`, `functools.lru_cache`

## Test Plan

`cargo nextest run -p ruff_linter -E
'test(preview_rules::rule_incorrectdecoratororder)'`

 Fixture covers: 
- All known-bad pairs (core + functools)
- Qualified imports (`abc.abstractmethod`, `functools.lru_cache`)
- Deprecated abc forms (`abstractproperty`, `abstractclassmethod`,
`abstractstaticmethod`)
- Decorator call forms (`@lru_cache()`, `@lru_cache(maxsize=128)`)
- Interleaved unknown decorators
- Multiple violations on the same function
- Correct orderings, single decorators, unrelated decorators (no false
positives)

Closes #6697
2026-05-19 10:20:30 -07:00
Dev-iLandClaude Opus 4.7 8c930f5972 [airflow] Implement airflow-task-implicit-multiple-outputs (AIR202) (#25152)
> [!IMPORTANT]
> Disclosure: this PR description was AI-drafted under my direction and
reviewed by me before posting.

## Summary

Implements rule `AIR202` (`airflow-task-implicit-multiple-outputs`) that
flags `@task`-decorated functions whose `multiple_outputs` behavior is
determined by Airflow's runtime inference rather than being set
explicitly on the decorator.

At runtime, Airflow's
[`_infer_multiple_outputs`](https://github.com/apache/airflow/blob/main/task-sdk/src/airflow/sdk/bases/decorator.py)
inspects the function's return annotation: if it resolves to a subclass
of `collections.abc.Mapping`, the return value is split into one `XCom`
per key; otherwise the entire return value is stored as a single `XCom`.
This couples typing to `XCom` layout in a non-obvious way — renaming,
removing, or refining the return annotation silently changes a DAG's
`XCom` behavior. Passing `multiple_outputs=` explicitly makes the
author's intent clear and insulates the DAG from future changes to
inference.

### What the rule flags

```python
from airflow.sdk import task  # or equivalent Airflow 2.x import path


# AIR202 — annotation in the Mapping family
@task
def extract() -> dict:
    return {"x": 1, "y": 2}


# AIR202 — body returns a dict literal
@task()
def transform():
    return {"a": 1}


# AIR202 — call-form decorator with unrelated kwargs
@task(retries=3)
def with_retries() -> dict[str, int]:
    return {"n": 1}


# AIR202 — variant decorators with parens
@task.short_circuit(trigger_rule="all_done")
def gate() -> dict:
    return {"go": True}
```

### Suggested fix

The fix is **always available** but marked **unsafe**: it inserts the
value Airflow would have inferred, preserving runtime behavior at the
moment of the rewrite, but the author may have intended a different
`XCom` layout and a multi-return function may not always return a dict.

```python
@task(multiple_outputs=True)
def extract() -> dict:
    return {"x": 1, "y": 2}


@task(multiple_outputs=True)
def transform():
    return {"a": 1}


@task(retries=3, multiple_outputs=True)
def with_retries() -> dict[str, int]:
    return {"n": 1}
```

For the call-form path (`@task(...)` with existing parentheses), the fix
uses `add_argument` so existing kwargs and formatting are preserved,
including on multiline decorators. For the bare form (`@task`,
`@task.branch`), the fix appends `(multiple_outputs=...)` after the
decorator expression.

### Detection signals

The rule fires when **either** of two independent signals holds and
`multiple_outputs` is absent from the decorator:

1. **Annotation signal** — the return annotation resolves to a member of
the Mapping family: `dict`, `Dict`, `Mapping`, `MutableMapping`,
`OrderedDict`, `DefaultDict`, `Counter`, `ChainMap`, `TypedDict` (and
the `collections` / `typing` variants thereof).
2. **Body signal** — the function body contains at least one `return`
statement whose value is a dict literal, a dict comprehension, or a
`dict(...)` call. `ReturnStatementVisitor` is used so returns inside
nested `if` / `for` / `while` / `try` blocks are considered, while
returns inside nested function definitions or class bodies are correctly
**not** considered.

### What it does NOT flag

- Functions where `multiple_outputs=` is already set explicitly (either
`True` or `False`).
- `@task.sensor`-decorated functions — the sensor decorator hardcodes
`multiple_outputs=False`.
- Functions whose only dict-returning code lives in a nested function or
class method (the outer task is not affected).
- Functions whose return annotation is not in the Mapping family and
whose body does not return a dict-shaped value.

### Implementation details

- Resolves `@task` / `@task.<variant>` via the semantic model, handling
both bare (`@task`) and call (`@task(...)`) forms via `map_callable`.
The supported variants list is local to the rule: `python`,
`virtualenv`, `external_python`, `branch`, `branch_virtualenv`,
`branch_external_python`, `short_circuit`, `docker`, `kubernetes`,
`pyspark`.
- Annotation matching walks subscripts (e.g., `dict[str, int]`,
`Mapping[str, Any]`) down to the head and uses `match_typing_expr` /
known-module resolution.
- Body matching uses `ReturnStatementVisitor` from
`ruff_python_ast::helpers`, which already skips nested function and
class definitions — so nested-scope dict returns are correctly ignored
without a custom traversal.
- The inserted value (`True` / `False`) mirrors Airflow's inference:
`True` when the annotation is in the Mapping family, `False` otherwise.
When both signals fire but the annotation is non-Mapping (e.g., body
returns a dict but the annotation is `list`), the inserted value is
still `False` to preserve runtime behavior.

## Test Plan

Added snapshot tests in `AIR202.py` covering:

| Group | Cases |
|-------|-------|
| Annotation positives | `dict`, `dict[str, int]`, `Dict`, `Mapping`,
`MutableMapping`, `OrderedDict`, `DefaultDict`, `Counter`, `ChainMap`,
`TypedDict` |
| Body positives | dict literal, dict comprehension, `dict(...)` call |
| Decorator forms | bare `@task`, `@task()`, `@task(retries=3)`,
multiline `@task(...)`, `@task.docker(image=...)`, `@task.virtualenv()`,
`@task.short_circuit(trigger_rule=...)`, `@task.branch` |
| Explicit-kwarg negatives | `multiple_outputs=True`,
`multiple_outputs=False` — never flagged |
| Sensor negative | `@task.sensor` returning a dict — never flagged |
| Nested-scope negatives | outer task with inner function returning a
dict; outer task with inner class whose method returns a dict — never
flagged |

A sweep against the local Apache Airflow checkout (`cargo run -p ruff --
check ~/airflow --no-cache --preview --select AIR202`) produced 19
diagnostics on the Airflow codebase itself, all of which were verified
to be genuine cases of implicit `multiple_outputs` inference (no false
positives).

Related: 
- https://github.com/apache/airflow/issues/43176
- https://github.com/apache/airflow/pull/66712

Community approval:
https://lists.apache.org/thread/99s321s2p5xqhzlm0x5wjgy044nggtpm

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-19 06:51:54 -07:00
Clément Robert 2072f3f8d2 [pylint] Implement too-many-try-statements (W0717) (#23970)
## Summary

Close #23810

Opening as a draft mostly to signal that I'm getting this going. At the
time of opening, and as far as I can tell, this *compiles* correctly
locally, but it's missing tests and docs.

I also have a question I would like to ask @ntBre at this early stage of
the PR: it seemed to me that the logic from
`too_many_statements::num_statements` could be entirely re-used, and I
didn't want to duplicate it, so I moved it up the module tree to
`ruff_linter::rules::pylint::helpers`. Is this the prefered approach, or
is there a better way I should implement this code re-use ?

## Test Plan
2026-05-15 13:57:21 -07:00
Charlie MarshandBrent Westbrook 41f8a525b3 Add a rule to flag lazy imports that are eagerly evaluated (#25016)
## Summary

This PR adds a new rule (`TID255`) to flag PEP 810 lazy imports that are
resolved immediately during module import execution.

For example:

```python
lazy import foo

class Bar(foo.Foo): ...
```

Here, `foo` is evaluated while the module is being loaded, so the import
is not meaningfully lazy.

We're also offering an unsafe fix to remove `lazy` when the import
statement imports a single member.

Closes https://github.com/astral-sh/ruff/issues/25014.

---------

Co-authored-by: Brent Westbrook <36778786+ntBre@users.noreply.github.com>
2026-05-06 20:48:23 +00:00
ea6be89b0a Increase max value of line-length setting (#24962)
Co-authored-by: Erik Johnson <source@ekriirke.net>
Co-authored-by: Micha Reiser <micha@reiser.io>
2026-05-05 14:08:51 +00:00
Dev-iL 94e61100ef [airflow] Implement task-branch-as-short-circuit (AIR004) (#23579)
## Summary

Adds a new rule `AIR004` that detects `@task.branch` decorated functions
that could be replaced with `@task.short_circuit`.

In Airflow,
[`@task.branch`](https://airflow.apache.org/docs/apache-airflow/stable/core-concepts/dags.html#branching)
selects which downstream tasks to run by returning a list of task IDs
(or an empty list to skip all). When the function has at least two
`return` statements and exactly one of them returns a non-empty list, it
is effectively acting as a boolean short-circuit (i.e. either run one
specific set of downstream tasks or skip them all). In that case,
[`@task.short_circuit`](https://www.astronomer.io/docs/learn/airflow-branch-operator#taskshort_circuit-shortcircuitoperator)
is a simpler and more readable alternative that returns `True`/`False`
instead.

```python
# Before (AIR004)
@task.branch
def my_task():
    if condition:
        return ["my_downstream_task"]
    return []

# After
@task.short_circuit
def my_task():
    return condition
```

### Implementation details

- Resolves the `@task.branch` decorator via the semantic model
(`airflow.decorators.task` + `.branch` attribute), handling both
`@task.branch` and `@task.branch()` call forms via `map_callable`.
- Uses `ReturnStatementVisitor` to collect all `return` statements
recursively (including those inside nested `if`/`else`/`for`/`while`
blocks).
- Flags the function when: `len(returns) >= 2` and exactly one return
has a non-empty list value.

### What it does NOT flag

- Functions with multiple non-empty list returns (genuine branching
logic).
- Functions with all-empty returns (no downstream tasks selected at
all).
- Functions with only a single return statement.
- Functions not decorated with `@task.branch`.
- Functions returning non-list values (strings, `None`, etc.).

## Test Plan
<!-- How was it tested? -->

Added snapshot tests in `AIR004.py` covering both violation and
non-violation cases:
- two returns with one non-empty list
- three returns with one non-empty list
- nested returns
- multiple non-empty returns
- all-empty returns
- single return
- undecorated functions
- `@task.short_circuit` decorated functions
2026-04-23 10:21:30 -04:00
0921ed25a1 [airflow] Implement airflow-xcom-pull-in-template-string (AIR201) (#23583)
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Micha Reiser <micha@reiser.io>
2026-04-14 08:47:58 +02:00