Compare commits

...

75 Commits

Author SHA1 Message Date
Charlie Marsh
5e9a8fcf53 Bump version to 0.0.157 2022-12-04 14:46:46 -05:00
Charlie Marsh
76439235af Remove unused imports in __init__.py files by default (#1042) 2022-12-04 14:45:54 -05:00
Charlie Marsh
0c9c6a1c1c Remove extraneous test file 2022-12-04 13:59:55 -05:00
Charlie Marsh
46a99243cd Fix D205 autofix by detecting summary line (#1041) 2022-12-04 13:56:51 -05:00
Charlie Marsh
d06dc4c72d Bump version to 0.0.156 2022-12-04 10:22:09 -05:00
Jonathan Plasse
8f6b2fb32b Extend and rename RUF004 to PLR1722 (#1036) 2022-12-04 10:20:12 -05:00
Charlie Marsh
1d61db5b62 Allow import builtins under T100 (#1037) 2022-12-04 10:13:17 -05:00
Charlie Marsh
e15c0c68cb Fix PLW0120 snapshot 2022-12-04 10:10:00 -05:00
Harutaka Kawamura
abb2adc4d8 Implement useless-import-alias (#1025) 2022-12-04 09:48:56 -05:00
Harutaka Kawamura
e070166409 Implement useless-else-on-loop (#1031) 2022-12-04 09:22:04 -05:00
Jonathan Plasse
0ae6890094 Fix Table of Contents (#1030) 2022-12-04 09:14:09 -05:00
Harutaka Kawamura
21cace0973 Fix PLR0402 (#1024) 2022-12-04 09:13:47 -05:00
Jakub Kuczys
4994b72ba2 Fix README header links in isort config section (#1033) 2022-12-04 09:12:25 -05:00
Anders Kaseorg
dbb1a6e44b Remove sloppy match_name_or_attr helper (#1027) 2022-12-04 09:12:03 -05:00
Charlie Marsh
4b0c3e3bc9 Bump version to 0.0.155 2022-12-04 00:12:00 -05:00
Charlie Marsh
ddae3586d5 Add support for combine-as-imports import formatting (#1022) 2022-12-04 00:11:48 -05:00
Charlie Marsh
97684b7215 Mark MisplacedComparisonConstant as fixable 2022-12-04 00:11:19 -05:00
Harutaka Kawamura
20e6ff112a Implement misplaced-comparison-constant (#1023) 2022-12-04 00:10:07 -05:00
Charlie Marsh
6cb84d29f0 Rename M001 to RUF100 (#1021) 2022-12-03 22:51:05 -05:00
Charlie Marsh
d069054792 Rename RUF101 fixtures 2022-12-03 22:47:16 -05:00
Charlie Marsh
c659cb86d9 Rename RUF101 to RUF004 (#1020) 2022-12-03 22:46:13 -05:00
Charlie Marsh
8a3f29497b Add backwards compatible redirect map for U-to-UP rename (#1019) 2022-12-03 22:43:00 -05:00
Harutaka Kawamura
58e7baedd0 Implement consider-using-from-import (#1018) 2022-12-03 22:36:43 -05:00
Charlie Marsh
00eff2b09a Rename pyupgrade rules from UXXX to UPXXX (#957) 2022-12-03 22:35:42 -05:00
Charlie Marsh
b6b509811d Bump version to 0.0.154 2022-12-03 20:14:38 -05:00
Charlie Marsh
87bdda3cfa Make some flake8-return rules auto-fixable (#1017) 2022-12-03 20:13:17 -05:00
Charlie Marsh
291727a27d Implement flake8-return plugin (#1016) 2022-12-03 20:12:11 -05:00
Charlie Marsh
e66b786229 Bump version to 0.0.153 2022-12-03 17:05:39 -05:00
Harutaka Kawamura
e05e1cdf76 Implement consider-merging-isinstance (#1009) 2022-12-03 16:51:53 -05:00
Harutaka Kawamura
f92cc7a159 Fix clippy errors on main (#1010) 2022-12-03 10:02:36 -05:00
Harutaka Kawamura
ebd2181946 Implement unnecessary-direct-lambda-call (#1008) 2022-12-03 09:59:04 -05:00
Harutaka Kawamura
3efa1a03f2 Fix match_like_matches_macro in src/pylint/plugins.rs (#1007) 2022-12-03 00:21:32 -05:00
Harutaka Kawamura
115e85b47d Rename PLE0206 to PLR0206 (#1006) 2022-12-03 00:14:46 -05:00
Harutaka Kawamura
31a3314ebd Implement PLE0206 (#1005) 2022-12-03 00:04:43 -05:00
Charlie Marsh
bf33025ea9 Support whole-file noqa exclusions (#1001) 2022-12-02 23:56:56 -05:00
Charlie Marsh
1a33ee3fc4 Bump version to 0.0.152 2022-12-02 13:23:00 -05:00
Charlie Marsh
4722885910 Avoid recursing on nested deferred annotations (#1000)
Parse nested deferred annotations
2022-12-02 13:22:39 -05:00
Jonathan Plasse
117fcb6936 Add no-eval rule from pygrep-hooks (#994) 2022-12-02 12:59:06 -05:00
Charlie Marsh
1a24d78f67 Bump version to 0.0.151 2022-12-01 22:31:44 -05:00
Charlie Marsh
4a4082cf0e Track type definitions and annotations separately (#992) 2022-12-01 22:31:20 -05:00
Charlie Marsh
18b9fbd71e Improve docstring checks with empty trailing lines (#991) 2022-12-01 20:15:44 -05:00
Charlie Marsh
d699bb7b86 Bump version to 0.0.150 2022-12-01 16:31:18 -05:00
Charlie Marsh
46f5053c73 Include fixes in JSON API output (#988) 2022-12-01 16:30:56 -05:00
Charlie Marsh
af40e64d6c Remove Patch abstraction from Fix (#987) 2022-12-01 16:04:42 -05:00
Charlie Marsh
2e89cd8802 Split test fixtures up by plugin (#985) 2022-12-01 13:33:33 -05:00
Charlie Marsh
1085b547b6 Convert Err(anyhow(...)) to bail (#984) 2022-12-01 13:33:06 -05:00
Charlie Marsh
9e5df82578 Remove trailing punctuation from error messages (#983) 2022-12-01 12:25:37 -05:00
Charlie Marsh
6fe478cb43 Add Conda installation instructions (#982) 2022-12-01 12:19:39 -05:00
Charlie Marsh
c06a1f6da9 Force format --text in tests 2022-12-01 10:51:11 -05:00
Edgar R. M
6f48ac6c0b Add GitHub output format (#975) 2022-12-01 10:22:11 -05:00
Edgar R. M
9e1ba916f0 Send logs to stderr (#977) 2022-12-01 10:19:32 -05:00
Charlie Marsh
f6b0a606d6 Implement await-outside-async / E1142 (#972) 2022-11-30 11:38:03 -05:00
Charlie Marsh
c8e72dfb9e Narrow keyword in yield-outside-function (#971) 2022-11-30 10:03:40 -05:00
Charlie Marsh
6fa0f21227 Bump version to 0.0.149 2022-11-30 00:51:36 -05:00
messense
f5466fe720 Add JUnit xml output format (#968) 2022-11-30 00:47:41 -05:00
Charlie Marsh
a0202e8eb2 Add Pylint parity to FAQ (#969) 2022-11-29 23:51:27 -05:00
Charlie Marsh
30ff4de9a3 Bump version to 0.0.148 2022-11-29 22:50:30 -05:00
Charlie Marsh
897b0f06ef Fix clippy 2022-11-29 22:50:20 -05:00
Charlie Marsh
2fe22a223b Bump version to 0.0.147 2022-11-29 20:17:58 -05:00
Charlie Marsh
e762dec677 Add one more note to README 2022-11-29 20:17:46 -05:00
Charlie Marsh
19baa50003 Remove extraneous key in pyproject.toml 2022-11-29 20:13:28 -05:00
Charlie Marsh
ab0df03a05 Fix pyproject tests to include pyupgrade 2022-11-29 20:11:16 -05:00
Charlie Marsh
808b348c5f Add W to pycodestyle list in README 2022-11-29 20:09:07 -05:00
Charlie Marsh
e55daa89e6 Uses dashes for README options (#966) 2022-11-29 20:08:03 -05:00
Charlie Marsh
b8e7d86696 Add pyupgrade's --keep-runtime-typing option (#965) 2022-11-29 20:05:32 -05:00
Charlie Marsh
ced7868559 Add format setting to pyproject.toml (#964) 2022-11-29 19:22:23 -05:00
Ramazan Elsunakev
7c344e8e4c feat: use more precise ranges for imports (#958) 2022-11-29 19:01:39 -05:00
Hayden
ca38c7ac48 Grouped format implementation (#954) 2022-11-29 18:45:16 -05:00
Guillaume Andreu Sabater
602291c0c2 README: fixed conf section typo (#959) 2022-11-29 09:27:02 -05:00
Charlie Marsh
d4cf376e9b Fix failing pyproject test 2022-11-29 00:00:43 -05:00
Charlie Marsh
0e6a38e6d8 Bump version to 0.0.146 2022-11-28 22:27:41 -05:00
Charlie Marsh
058fd8748d Re-generate check code prefix and rules table 2022-11-28 22:26:32 -05:00
Charlie Marsh
e8247e3ed9 Run cargo fmt 2022-11-28 22:25:09 -05:00
Charlie Marsh
ea73c717be Remove pre-commit note in README.md (#956) 2022-11-28 22:18:59 -05:00
Charlie Marsh
427e0c3158 Allow preservation of external check codes (#955) 2022-11-28 22:16:17 -05:00
691 changed files with 13007 additions and 7954 deletions

View File

@@ -1,6 +1,6 @@
repos:
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.0.145
rev: v0.0.157
hooks:
- id: ruff

71
Cargo.lock generated
View File

@@ -220,13 +220,16 @@ dependencies = [
[[package]]
name = "chrono"
version = "0.4.22"
version = "0.4.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bfd4d1b31faaa3a89d7934dbded3111da0d2ef28e3ebccdb4f0179f5929d1ef1"
checksum = "16b0a3d9ed01224b22057780a37bb8c5dbfe1be8ba48678e7bf57ec4b385411f"
dependencies = [
"iana-time-zone",
"js-sys",
"num-integer",
"num-traits",
"time",
"wasm-bindgen",
"winapi 0.3.9",
]
@@ -700,7 +703,7 @@ checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
[[package]]
name = "flake8-to-ruff"
version = "0.0.145-dev.0"
version = "0.0.157-dev.0"
dependencies = [
"anyhow",
"clap 4.0.22",
@@ -883,9 +886,9 @@ dependencies = [
[[package]]
name = "indexmap"
version = "1.9.1"
version = "1.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10a35a97730320ffe8e2d410b5d3b69279b98d2c14bdb8b70ea89ecf7888d41e"
checksum = "1885e79c1fc4b10f0e172c475f458b7f7b93061064d98c3293e98c5ba0c8b399"
dependencies = [
"autocfg",
"hashbrown",
@@ -1220,6 +1223,12 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4a24736216ec316047a1fc4252e27dabb04218aa4a3f37c6e7ddbf1f9782b54"
[[package]]
name = "nextest-workspace-hack"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d906846a98739ed9d73d66e62c2641eef8321f1734b7a1156ab045a0248fb2b3"
[[package]]
name = "nix"
version = "0.24.2"
@@ -1606,6 +1615,29 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "quick-junit"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05b909fe9bf2abb1e3d6a97c9189a37c8105c61d03dca9ce6aace023e7d682bd"
dependencies = [
"chrono",
"indexmap",
"nextest-workspace-hack",
"quick-xml",
"thiserror",
"uuid",
]
[[package]]
name = "quick-xml"
version = "0.26.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f50b1c63b38611e7d4d7f68b82d3ad0cc71a2ad2e7f61fc10f1328d917c93cd"
dependencies = [
"memchr",
]
[[package]]
name = "quote"
version = "1.0.21"
@@ -1805,7 +1837,7 @@ dependencies = [
[[package]]
name = "ruff"
version = "0.0.145"
version = "0.0.157"
dependencies = [
"annotate-snippets 0.9.1",
"anyhow",
@@ -1835,6 +1867,7 @@ dependencies = [
"num-bigint",
"once_cell",
"path-absolutize",
"quick-junit",
"rayon",
"regex",
"ropey",
@@ -1856,13 +1889,14 @@ dependencies = [
[[package]]
name = "ruff_dev"
version = "0.0.145"
version = "0.0.157"
dependencies = [
"anyhow",
"clap 4.0.22",
"codegen",
"itertools",
"libcst",
"once_cell",
"ruff",
"rustpython-ast",
"rustpython-common",
@@ -2263,6 +2297,17 @@ dependencies = [
"syn",
]
[[package]]
name = "time"
version = "0.1.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b797afad3f312d1c66a56d11d0316f916356d11bd158fbc6ca6389ff6bf805a"
dependencies = [
"libc",
"wasi 0.10.0+wasi-snapshot-preview1",
"winapi 0.3.9",
]
[[package]]
name = "tiny-keccak"
version = "2.0.2"
@@ -2489,6 +2534,12 @@ dependencies = [
"percent-encoding",
]
[[package]]
name = "uuid"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "422ee0de9031b5b948b97a8fc04e3aa35230001a722ddd27943e0be31564ce4c"
[[package]]
name = "version_check"
version = "0.9.4"
@@ -2527,6 +2578,12 @@ version = "0.9.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519"
[[package]]
name = "wasi"
version = "0.10.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f"
[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"

View File

@@ -6,7 +6,7 @@ members = [
[package]
name = "ruff"
version = "0.0.145"
version = "0.0.157"
edition = "2021"
rust-version = "1.65.0"
@@ -28,7 +28,7 @@ common-path = { version = "1.0.0" }
dirs = { version = "4.0.0" }
fern = { version = "0.6.1" }
filetime = { version = "0.2.17" }
globset = {version = "0.4.9" }
globset = { version = "0.4.9" }
itertools = { version = "0.10.5" }
libcst = { git = "https://github.com/charliermarsh/LibCST", rev = "f2f0b7a487a8725d161fe8b3ed73a6758b21e177" }
log = { version = "0.4.17" }
@@ -37,6 +37,7 @@ notify = { version = "4.0.17" }
num-bigint = { version = "0.4.3" }
once_cell = { version = "1.16.0" }
path-absolutize = { version = "3.0.14", features = ["once_cell_cache", "use_unix_paths_on_wasm"] }
quick-junit = { version = "0.3.2" }
rayon = { version = "1.5.3" }
regex = { version = "1.6.0" }
ropey = { version = "1.5.0", features = ["cr_lines", "simd"], default-features = false }

48
LICENSE
View File

@@ -363,6 +363,31 @@ are:
THE SOFTWARE.
"""
- flake8-return, licensed as follows:
"""
MIT License
Copyright (c) 2019 Afonasev Evgeniy
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
- isort, licensed as follows:
"""
The MIT License (MIT)
@@ -471,6 +496,29 @@ are:
SOFTWARE.
"""
- pygrep-hooks, licensed as follows:
"""
Copyright (c) 2018 Anthony Sottile
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
- pyupgrade, licensed as follows:
"""
Copyright (c) 2017 Anthony Sottile

495
README.md
View File

@@ -29,7 +29,9 @@ functionality behind a single, common interface. Ruff can be used to replace Fla
of plugins), [`isort`](https://pypi.org/project/isort/), [`pydocstyle`](https://pypi.org/project/pydocstyle/),
[`yesqa`](https://github.com/asottile/yesqa), [`eradicate`](https://pypi.org/project/eradicate/),
and even a subset of [`pyupgrade`](https://pypi.org/project/pyupgrade/) and [`autoflake`](https://pypi.org/project/autoflake/)
all while executing tens or hundreds of times faster than any individual tool.
all while executing tens or hundreds of times faster than any individual tool. Ruff goes beyond the
responsibilities of a traditional linter, instead functioning as an advanced code transformation
tool capable of upgrading type annotations, rewriting class definitions, sorting imports, and more.
Ruff is extremely actively developed and used in major open-source projects like:
@@ -68,27 +70,29 @@ of [Conda](https://docs.conda.io/en/latest/):
1. [Configuration](#configuration)
1. [Supported Rules](#supported-rules)
1. [Pyflakes (F)](#pyflakes)
1. [pycodestyle (E)](#pycodestyle)
1. [pycodestyle (E, W)](#pycodestyle)
1. [mccabe (C90)](#mccabe)
1. [isort (I)](#isort)
1. [pydocstyle (D)](#pydocstyle)
1. [pyupgrade (U)](#pyupgrade)
1. [pyupgrade (UP)](#pyupgrade)
1. [pep8-naming (N)](#pep8-naming)
1. [eradicate (ERA)](#eradicate)
1. [flake8-2020 (YTT)](#flake8-2020)
1. [flake8-annotations (ANN)](#flake8-annotations)
1. [flake8-bandit (S)](#flake8-bandit)
1. [flake8-comprehensions (C)](#flake8-comprehensions)
1. [flake8-blind-except (BLE)](#flake8-blind-except)
1. [flake8-boolean-trap (FBT)](#flake8-boolean-trap)
1. [flake8-bugbear (B)](#flake8-bugbear)
1. [flake8-builtins (A)](#flake8-builtins)
1. [flake8-debugger (T)](#flake8-debugger)
1. [flake8-tidy-imports (I25)](#flake8-tidy-imports)
1. [flake8-print (T)](#flake8-print)
1. [flake8-comprehensions (C4)](#flake8-comprehensions)
1. [flake8-debugger (T10)](#flake8-debugger)
1. [flake8-print (T20)](#flake8-print)
1. [flake8-quotes (Q)](#flake8-quotes)
1. [flake8-annotations (ANN)](#flake8-annotations)
1. [flake8-2020 (YTT)](#flake8-2020)
1. [flake8-blind-except (BLE)](#flake8-blind-except)
1. [mccabe (C90)](#mccabe)
1. [flake8-return (RET)](#flake8-return)
1. [flake8-tidy-imports (I25)](#flake8-tidy-imports)
1. [eradicate (ERA)](#eradicate)
1. [pygrep-hooks (PGH)](#pygrep-hooks)
1. [Pylint (PL)](#pylint)
1. [Ruff-specific rules (RUF)](#ruff-specific-rules)
1. [Meta rules (M)](#meta-rules)
1. [Editor Integrations](#editor-integrations)
1. [FAQ](#faq)
1. [Development](#development)
@@ -108,12 +112,18 @@ Ruff is available as [`ruff`](https://pypi.org/project/ruff/) on PyPI:
pip install ruff
```
If you're a **macOS Homebrew** or a **Linuxbrew** user, you can also install `ruff` via Homebrew:
For **macOS Homebrew** and **Linuxbrew** users, Ruff is also available as [`ruff`](https://formulae.brew.sh/formula/ruff) on Homebrew:
```shell
brew install ruff
```
For Conda users, Ruff is also available as [`ruff`](https://anaconda.org/conda-forge/ruff) on `conda-forge`:
```shell
conda install -c conda-forge ruff
```
### Usage
To run Ruff, try any of the following:
@@ -135,14 +145,11 @@ Ruff also works with [pre-commit](https://pre-commit.com):
```yaml
repos:
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.0.145
rev: v0.0.157
hooks:
- id: ruff
```
<!-- TODO(charlie): Remove this message a few versions after v0.0.86. -->
_Note: prior to `v0.0.86`, `ruff-pre-commit` used `lint` (rather than `ruff`) as the hook ID._
## Configuration
Ruff is configurable both via `pyproject.toml` and the command line. For a full list of configurable
@@ -239,10 +246,10 @@ See `ruff --help` for more:
```shell
Ruff: An extremely fast Python linter.
Usage: ruff [OPTIONS] <FILES>...
Usage: ruff [OPTIONS] [FILES]...
Arguments:
<FILES>...
[FILES]...
Options:
--config <CONFIG>
@@ -280,7 +287,7 @@ Options:
--per-file-ignores <PER_FILE_IGNORES>
List of mappings from file pattern to code to exclude
--format <FORMAT>
Output serialization format for error messages [default: text] [possible values: text, json]
Output serialization format for error messages [default: text] [possible values: text, json, junit, grouped]
--show-source
Show violations with source code
--show-files
@@ -299,6 +306,8 @@ Options:
Max McCabe complexity allowed for a function
--stdin-filename <STDIN_FILENAME>
The name of the file when passing it through stdin
--explain <EXPLAIN>
Explain a rule
-h, --help
Print help information
-V, --version
@@ -307,10 +316,10 @@ Options:
### Ignoring errors
To omit a lint check entirely, add it to the "ignore" list via `--ignore` or `--extend-ignore`,
either on the command-line or in your `project.toml` file.
To omit a lint check entirely, add it to the "ignore" list via [`ignore`](#ignore) or
[`extend-ignore`](#extend-ignore), either on the command-line or in your `project.toml` file.
To ignore an error in-line, Ruff uses a `noqa` system similar to [Flake8](https://flake8.pycqa.org/en/3.1.1/user/ignoring-errors.html).
To ignore an error inline, Ruff uses a `noqa` system similar to [Flake8](https://flake8.pycqa.org/en/3.1.1/user/ignoring-errors.html).
To ignore an individual error, add `# noqa: {code}` to the end of the line, like so:
```python
@@ -325,7 +334,7 @@ x = 1 # noqa
```
Note that, for multi-line strings, the `noqa` directive should come at the end of the string, and
will apply to the entire body, like so:
will apply to the entire string, like so:
```python
"""Lorem ipsum dolor sit amet.
@@ -334,15 +343,24 @@ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor i
""" # noqa: E501
```
To ignore all errors across an entire file, Ruff supports Flake8's `# flake8: noqa` directive (or,
equivalently, `# ruff: noqa`). Adding either of those directives to any part of a file will disable
error reporting for the entire file.
For targeted exclusions across entire files (e.g., "Ignore all F841 violations in
`/path/to/file.py`"), see the [`per-file-ignores`](#per-file-ignores) configuration setting.
### Automating `noqa` Directives
Ruff supports several workflows to aid in `noqa` management.
First, Ruff provides a special error code, `M001`, to enforce that your `noqa` directives are
First, Ruff provides a special error code, `RUF100`, to enforce that your `noqa` directives are
"valid", in that the errors they _say_ they ignore are actually being triggered on that line (and
thus suppressed). You can run `ruff /path/to/file.py --extend-select M001` to flag unused `noqa`
thus suppressed). You can run `ruff /path/to/file.py --extend-select RUF100` to flag unused `noqa`
directives.
Second, Ruff can _automatically remove_ unused `noqa` directives via its autofix functionality.
You can run `ruff /path/to/file.py --extend-select M001 --fix` to automatically remove unused
You can run `ruff /path/to/file.py --extend-select RUF100 --fix` to automatically remove unused
`noqa` directives.
Third, Ruff can _automatically add_ `noqa` directives to all failing lines. This is useful when
@@ -398,7 +416,7 @@ For more, see [Pyflakes](https://pypi.org/project/pyflakes/2.5.0/) on PyPI.
| F634 | IfTuple | If test is a tuple, which is always `True` | |
| F701 | BreakOutsideLoop | `break` outside loop | |
| F702 | ContinueOutsideLoop | `continue` not properly in loop | |
| F704 | YieldOutsideFunction | `yield` or `yield from` statement outside of a function | |
| F704 | YieldOutsideFunction | `yield` statement outside of a function | |
| F706 | ReturnOutsideFunction | `return` statement outside of a function/method | |
| F707 | DefaultExceptNotLast | An `except` block as not the last exception handler | |
| F722 | ForwardAnnotationSyntaxError | Syntax error in forward annotation: `...` | |
@@ -432,6 +450,14 @@ For more, see [pycodestyle](https://pypi.org/project/pycodestyle/2.9.1/) on PyPI
| W292 | NoNewLineAtEndOfFile | No newline at end of file | |
| W605 | InvalidEscapeSequence | Invalid escape sequence: '\c' | |
### mccabe
For more, see [mccabe](https://pypi.org/project/mccabe/0.7.0/) on PyPI.
| Code | Name | Message | Fix |
| ---- | ---- | ------- | --- |
| C901 | FunctionIsTooComplex | `...` is too complex (10) | |
### isort
For more, see [isort](https://pypi.org/project/isort/5.10.1/) on PyPI.
@@ -497,20 +523,20 @@ For more, see [pyupgrade](https://pypi.org/project/pyupgrade/3.2.0/) on PyPI.
| Code | Name | Message | Fix |
| ---- | ---- | ------- | --- |
| U001 | UselessMetaclassType | `__metaclass__ = type` is implied | 🛠 |
| U003 | TypeOfPrimitive | Use `str` instead of `type(...)` | 🛠 |
| U004 | UselessObjectInheritance | Class `...` inherits from object | 🛠 |
| U005 | DeprecatedUnittestAlias | `assertEquals` is deprecated, use `assertEqual` instead | 🛠 |
| U006 | UsePEP585Annotation | Use `list` instead of `List` for type annotations | 🛠 |
| U007 | UsePEP604Annotation | Use `X \| Y` for type annotations | 🛠 |
| U008 | SuperCallWithParameters | Use `super()` instead of `super(__class__, self)` | 🛠 |
| U009 | PEP3120UnnecessaryCodingComment | UTF-8 encoding declaration is unnecessary | 🛠 |
| U010 | UnnecessaryFutureImport | Unnecessary `__future__` import `...` for target Python version | 🛠 |
| U011 | UnnecessaryLRUCacheParams | Unnecessary parameters to `functools.lru_cache` | 🛠 |
| U012 | UnnecessaryEncodeUTF8 | Unnecessary call to `encode` as UTF-8 | 🛠 |
| U013 | ConvertTypedDictFunctionalToClass | Convert `...` from `TypedDict` functional to class syntax | 🛠 |
| U014 | ConvertNamedTupleFunctionalToClass | Convert `...` from `NamedTuple` functional to class syntax | 🛠 |
| U015 | RedundantOpenModes | Unnecessary open mode parameters | 🛠 |
| UP001 | UselessMetaclassType | `__metaclass__ = type` is implied | 🛠 |
| UP003 | TypeOfPrimitive | Use `str` instead of `type(...)` | 🛠 |
| UP004 | UselessObjectInheritance | Class `...` inherits from object | 🛠 |
| UP005 | DeprecatedUnittestAlias | `assertEquals` is deprecated, use `assertEqual` instead | 🛠 |
| UP006 | UsePEP585Annotation | Use `list` instead of `List` for type annotations | 🛠 |
| UP007 | UsePEP604Annotation | Use `X \| Y` for type annotations | 🛠 |
| UP008 | SuperCallWithParameters | Use `super()` instead of `super(__class__, self)` | 🛠 |
| UP009 | PEP3120UnnecessaryCodingComment | UTF-8 encoding declaration is unnecessary | 🛠 |
| UP010 | UnnecessaryFutureImport | Unnecessary `__future__` import `...` for target Python version | 🛠 |
| UP011 | UnnecessaryLRUCacheParams | Unnecessary parameters to `functools.lru_cache` | 🛠 |
| UP012 | UnnecessaryEncodeUTF8 | Unnecessary call to `encode` as UTF-8 | 🛠 |
| UP013 | ConvertTypedDictFunctionalToClass | Convert `...` from `TypedDict` functional to class syntax | 🛠 |
| UP014 | ConvertNamedTupleFunctionalToClass | Convert `...` from `NamedTuple` functional to class syntax | 🛠 |
| UP015 | RedundantOpenModes | Unnecessary open mode parameters | 🛠 |
### pep8-naming
@@ -534,13 +560,40 @@ For more, see [pep8-naming](https://pypi.org/project/pep8-naming/0.13.2/) on PyP
| N817 | CamelcaseImportedAsAcronym | Camelcase `...` imported as acronym `...` | |
| N818 | ErrorSuffixOnExceptionName | Exception name `...` should be named with an Error suffix | |
### eradicate
### flake8-2020
For more, see [eradicate](https://pypi.org/project/eradicate/2.1.0/) on PyPI.
For more, see [flake8-2020](https://pypi.org/project/flake8-2020/1.7.0/) on PyPI.
| Code | Name | Message | Fix |
| ---- | ---- | ------- | --- |
| ERA001 | CommentedCode | Found commented-out code | 🛠 |
| YTT101 | SysVersionSlice3Referenced | `sys.version[:3]` referenced (python3.10), use `sys.version_info` | |
| YTT102 | SysVersion2Referenced | `sys.version[2]` referenced (python3.10), use `sys.version_info` | |
| YTT103 | SysVersionCmpStr3 | `sys.version` compared to string (python3.10), use `sys.version_info` | |
| YTT201 | SysVersionInfo0Eq3Referenced | `sys.version_info[0] == 3` referenced (python4), use `>=` | |
| YTT202 | SixPY3Referenced | `six.PY3` referenced (python4), use `not six.PY2` | |
| YTT203 | SysVersionInfo1CmpInt | `sys.version_info[1]` compared to integer (python4), compare `sys.version_info` to tuple | |
| YTT204 | SysVersionInfoMinorCmpInt | `sys.version_info.minor` compared to integer (python4), compare `sys.version_info` to tuple | |
| YTT301 | SysVersion0Referenced | `sys.version[0]` referenced (python10), use `sys.version_info` | |
| YTT302 | SysVersionCmpStr10 | `sys.version` compared to string (python10), use `sys.version_info` | |
| YTT303 | SysVersionSlice1Referenced | `sys.version[:1]` referenced (python10), use `sys.version_info` | |
### flake8-annotations
For more, see [flake8-annotations](https://pypi.org/project/flake8-annotations/2.9.1/) on PyPI.
| Code | Name | Message | Fix |
| ---- | ---- | ------- | --- |
| ANN001 | MissingTypeFunctionArgument | Missing type annotation for function argument `...` | |
| ANN002 | MissingTypeArgs | Missing type annotation for `*...` | |
| ANN003 | MissingTypeKwargs | Missing type annotation for `**...` | |
| ANN101 | MissingTypeSelf | Missing type annotation for `...` in method | |
| ANN102 | MissingTypeCls | Missing type annotation for `...` in classmethod | |
| ANN201 | MissingReturnTypePublicFunction | Missing return type annotation for public function `...` | |
| ANN202 | MissingReturnTypePrivateFunction | Missing return type annotation for private function `...` | |
| ANN204 | MissingReturnTypeMagicMethod | Missing return type annotation for magic method `...` | |
| ANN205 | MissingReturnTypeStaticMethod | Missing return type annotation for staticmethod `...` | |
| ANN206 | MissingReturnTypeClassMethod | Missing return type annotation for classmethod `...` | |
| ANN401 | DynamicallyTypedExpression | Dynamically typed expressions (typing.Any) are disallowed in `...` | |
### flake8-bandit
@@ -555,36 +608,13 @@ For more, see [flake8-bandit](https://pypi.org/project/flake8-bandit/4.1.1/) on
| S106 | HardcodedPasswordFuncArg | Possible hardcoded password: `"..."` | |
| S107 | HardcodedPasswordDefault | Possible hardcoded password: `"..."` | |
### flake8-comprehensions
### flake8-blind-except
For more, see [flake8-comprehensions](https://pypi.org/project/flake8-comprehensions/3.10.1/) on PyPI.
For more, see [flake8-blind-except](https://pypi.org/project/flake8-blind-except/0.2.1/) on PyPI.
| Code | Name | Message | Fix |
| ---- | ---- | ------- | --- |
| C400 | UnnecessaryGeneratorList | Unnecessary generator (rewrite as a `list` comprehension) | 🛠 |
| C401 | UnnecessaryGeneratorSet | Unnecessary generator (rewrite as a `set` comprehension) | 🛠 |
| C402 | UnnecessaryGeneratorDict | Unnecessary generator (rewrite as a `dict` comprehension) | 🛠 |
| C403 | UnnecessaryListComprehensionSet | Unnecessary `list` comprehension (rewrite as a `set` comprehension) | 🛠 |
| C404 | UnnecessaryListComprehensionDict | Unnecessary `list` comprehension (rewrite as a `dict` comprehension) | 🛠 |
| C405 | UnnecessaryLiteralSet | Unnecessary `(list\|tuple)` literal (rewrite as a `set` literal) | 🛠 |
| C406 | UnnecessaryLiteralDict | Unnecessary `(list\|tuple)` literal (rewrite as a `dict` literal) | 🛠 |
| C408 | UnnecessaryCollectionCall | Unnecessary `(dict\|list\|tuple)` call (rewrite as a literal) | 🛠 |
| C409 | UnnecessaryLiteralWithinTupleCall | Unnecessary `(list\|tuple)` literal passed to `tuple()` (remove the outer call to `tuple()`) | 🛠 |
| C410 | UnnecessaryLiteralWithinListCall | Unnecessary `(list\|tuple)` literal passed to `list()` (rewrite as a `list` literal) | 🛠 |
| C411 | UnnecessaryListCall | Unnecessary `list` call (remove the outer call to `list()`) | 🛠 |
| C413 | UnnecessaryCallAroundSorted | Unnecessary `(list\|reversed)` call around `sorted()` | |
| C414 | UnnecessaryDoubleCastOrProcess | Unnecessary `(list\|reversed\|set\|sorted\|tuple)` call within `(list\|set\|sorted\|tuple)()` | |
| C415 | UnnecessarySubscriptReversal | Unnecessary subscript reversal of iterable within `(reversed\|set\|sorted)()` | |
| C416 | UnnecessaryComprehension | Unnecessary `(list\|set)` comprehension (rewrite using `(list\|set)()`) | 🛠 |
| C417 | UnnecessaryMap | Unnecessary `map` usage (rewrite using a `(list\|set\|dict)` comprehension) | |
### flake8-debugger
For more, see [flake8-debugger](https://pypi.org/project/flake8-debugger/4.1.2/) on PyPI.
| Code | Name | Message | Fix |
| ---- | ---- | ------- | --- |
| T100 | Debugger | Import for `...` found | |
| BLE001 | BlindExcept | Blind except Exception: statement | |
### flake8-boolean-trap
@@ -640,13 +670,36 @@ For more, see [flake8-builtins](https://pypi.org/project/flake8-builtins/2.0.1/)
| A002 | BuiltinArgumentShadowing | Argument `...` is shadowing a python builtin | |
| A003 | BuiltinAttributeShadowing | Class attribute `...` is shadowing a python builtin | |
### flake8-tidy-imports
### flake8-comprehensions
For more, see [flake8-tidy-imports](https://pypi.org/project/flake8-tidy-imports/4.8.0/) on PyPI.
For more, see [flake8-comprehensions](https://pypi.org/project/flake8-comprehensions/3.10.1/) on PyPI.
| Code | Name | Message | Fix |
| ---- | ---- | ------- | --- |
| I252 | BannedRelativeImport | Relative imports are banned | |
| C400 | UnnecessaryGeneratorList | Unnecessary generator (rewrite as a `list` comprehension) | 🛠 |
| C401 | UnnecessaryGeneratorSet | Unnecessary generator (rewrite as a `set` comprehension) | 🛠 |
| C402 | UnnecessaryGeneratorDict | Unnecessary generator (rewrite as a `dict` comprehension) | 🛠 |
| C403 | UnnecessaryListComprehensionSet | Unnecessary `list` comprehension (rewrite as a `set` comprehension) | 🛠 |
| C404 | UnnecessaryListComprehensionDict | Unnecessary `list` comprehension (rewrite as a `dict` comprehension) | 🛠 |
| C405 | UnnecessaryLiteralSet | Unnecessary `(list\|tuple)` literal (rewrite as a `set` literal) | 🛠 |
| C406 | UnnecessaryLiteralDict | Unnecessary `(list\|tuple)` literal (rewrite as a `dict` literal) | 🛠 |
| C408 | UnnecessaryCollectionCall | Unnecessary `(dict\|list\|tuple)` call (rewrite as a literal) | 🛠 |
| C409 | UnnecessaryLiteralWithinTupleCall | Unnecessary `(list\|tuple)` literal passed to `tuple()` (remove the outer call to `tuple()`) | 🛠 |
| C410 | UnnecessaryLiteralWithinListCall | Unnecessary `(list\|tuple)` literal passed to `list()` (rewrite as a `list` literal) | 🛠 |
| C411 | UnnecessaryListCall | Unnecessary `list` call (remove the outer call to `list()`) | 🛠 |
| C413 | UnnecessaryCallAroundSorted | Unnecessary `(list\|reversed)` call around `sorted()` | |
| C414 | UnnecessaryDoubleCastOrProcess | Unnecessary `(list\|reversed\|set\|sorted\|tuple)` call within `(list\|set\|sorted\|tuple)()` | |
| C415 | UnnecessarySubscriptReversal | Unnecessary subscript reversal of iterable within `(reversed\|set\|sorted)()` | |
| C416 | UnnecessaryComprehension | Unnecessary `(list\|set)` comprehension (rewrite using `(list\|set)()`) | 🛠 |
| C417 | UnnecessaryMap | Unnecessary `map` usage (rewrite using a `(list\|set\|dict)` comprehension) | |
### flake8-debugger
For more, see [flake8-debugger](https://pypi.org/project/flake8-debugger/4.1.2/) on PyPI.
| Code | Name | Message | Fix |
| ---- | ---- | ------- | --- |
| T100 | Debugger | Import for `...` found | |
### flake8-print
@@ -668,56 +721,60 @@ For more, see [flake8-quotes](https://pypi.org/project/flake8-quotes/3.3.1/) on
| Q002 | BadQuotesDocstring | Single quote docstring found but double quotes preferred | |
| Q003 | AvoidQuoteEscape | Change outer quotes to avoid escaping inner quotes | |
### flake8-annotations
### flake8-return
For more, see [flake8-annotations](https://pypi.org/project/flake8-annotations/2.9.1/) on PyPI.
For more, see [flake8-return](https://pypi.org/project/flake8-return/1.2.0/) on PyPI.
| Code | Name | Message | Fix |
| ---- | ---- | ------- | --- |
| ANN001 | MissingTypeFunctionArgument | Missing type annotation for function argument `...` | |
| ANN002 | MissingTypeArgs | Missing type annotation for `*...` | |
| ANN003 | MissingTypeKwargs | Missing type annotation for `**...` | |
| ANN101 | MissingTypeSelf | Missing type annotation for `...` in method | |
| ANN102 | MissingTypeCls | Missing type annotation for `...` in classmethod | |
| ANN201 | MissingReturnTypePublicFunction | Missing return type annotation for public function `...` | |
| ANN202 | MissingReturnTypePrivateFunction | Missing return type annotation for private function `...` | |
| ANN204 | MissingReturnTypeMagicMethod | Missing return type annotation for magic method `...` | |
| ANN205 | MissingReturnTypeStaticMethod | Missing return type annotation for staticmethod `...` | |
| ANN206 | MissingReturnTypeClassMethod | Missing return type annotation for classmethod `...` | |
| ANN401 | DynamicallyTypedExpression | Dynamically typed expressions (typing.Any) are disallowed in `...` | |
| RET501 | UnnecessaryReturnNone | Do not explicitly `return None` in function if it is the only possible return value | 🛠 |
| RET502 | ImplicitReturnValue | Do not implicitly `return None` in function able to return non-`None` value | 🛠 |
| RET503 | ImplicitReturn | Missing explicit `return` at the end of function able to return non-`None` value | 🛠 |
| RET504 | UnnecessaryAssign | Unnecessary variable assignment before `return` statement | |
| RET505 | SuperfluousElseReturn | Unnecessary `else` after `return` statement | |
| RET506 | SuperfluousElseRaise | Unnecessary `else` after `raise` statement | |
| RET507 | SuperfluousElseContinue | Unnecessary `else` after `continue` statement | |
| RET508 | SuperfluousElseBreak | Unnecessary `else` after `break` statement | |
### flake8-2020
### flake8-tidy-imports
For more, see [flake8-2020](https://pypi.org/project/flake8-2020/1.7.0/) on PyPI.
For more, see [flake8-tidy-imports](https://pypi.org/project/flake8-tidy-imports/4.8.0/) on PyPI.
| Code | Name | Message | Fix |
| ---- | ---- | ------- | --- |
| YTT101 | SysVersionSlice3Referenced | `sys.version[:3]` referenced (python3.10), use `sys.version_info` | |
| YTT102 | SysVersion2Referenced | `sys.version[2]` referenced (python3.10), use `sys.version_info` | |
| YTT103 | SysVersionCmpStr3 | `sys.version` compared to string (python3.10), use `sys.version_info` | |
| YTT201 | SysVersionInfo0Eq3Referenced | `sys.version_info[0] == 3` referenced (python4), use `>=` | |
| YTT202 | SixPY3Referenced | `six.PY3` referenced (python4), use `not six.PY2` | |
| YTT203 | SysVersionInfo1CmpInt | `sys.version_info[1]` compared to integer (python4), compare `sys.version_info` to tuple | |
| YTT204 | SysVersionInfoMinorCmpInt | `sys.version_info.minor` compared to integer (python4), compare `sys.version_info` to tuple | |
| YTT301 | SysVersion0Referenced | `sys.version[0]` referenced (python10), use `sys.version_info` | |
| YTT302 | SysVersionCmpStr10 | `sys.version` compared to string (python10), use `sys.version_info` | |
| YTT303 | SysVersionSlice1Referenced | `sys.version[:1]` referenced (python10), use `sys.version_info` | |
| I252 | BannedRelativeImport | Relative imports are banned | |
### flake8-blind-except
### eradicate
For more, see [flake8-blind-except](https://pypi.org/project/flake8-blind-except/0.2.1/) on PyPI.
For more, see [eradicate](https://pypi.org/project/eradicate/2.1.0/) on PyPI.
| Code | Name | Message | Fix |
| ---- | ---- | ------- | --- |
| BLE001 | BlindExcept | Blind except Exception: statement | |
| ERA001 | CommentedOutCode | Found commented-out code | 🛠 |
### mccabe
### pygrep-hooks
For more, see [mccabe](https://pypi.org/project/mccabe/0.7.0/) on PyPI.
For more, see [pygrep-hooks](https://github.com/pre-commit/pygrep-hooks) on GitHub.
| Code | Name | Message | Fix |
| ---- | ---- | ------- | --- |
| C901 | FunctionIsTooComplex | `...` is too complex (10) | |
| PGH001 | NoEval | No builtin `eval()` allowed | |
### Pylint
For more, see [Pylint](https://pypi.org/project/pylint/2.15.7/) on PyPI.
| Code | Name | Message | Fix |
| ---- | ---- | ------- | --- |
| PLC0414 | UselessImportAlias | Import alias does not rename original package | 🛠 |
| PLC2201 | MisplacedComparisonConstant | Comparison should be ... | 🛠 |
| PLC3002 | UnnecessaryDirectLambdaCall | Lambda expression called directly. Execute the expression inline instead. | |
| PLE1142 | AwaitOutsideAsync | `await` should be used within an async function | |
| PLR0206 | PropertyWithParameters | Cannot have defined parameters for properties | |
| PLR0402 | ConsiderUsingFromImport | Consider using `from ... import ...` | |
| PLR1701 | ConsiderMergingIsinstance | Consider merging these isinstance calls: `isinstance(..., (...))` | |
| PLR1722 | ConsiderUsingSysExit | Consider using `sys.exit()` | 🛠 |
| PLW0120 | UselessElseOnLoop | Else clause on loop without a break statement, remove the else and de-indent all the code inside it | |
### Ruff-specific rules
@@ -726,13 +783,7 @@ For more, see [mccabe](https://pypi.org/project/mccabe/0.7.0/) on PyPI.
| RUF001 | AmbiguousUnicodeCharacterString | String contains ambiguous unicode character '𝐁' (did you mean 'B'?) | 🛠 |
| RUF002 | AmbiguousUnicodeCharacterDocstring | Docstring contains ambiguous unicode character '𝐁' (did you mean 'B'?) | 🛠 |
| RUF003 | AmbiguousUnicodeCharacterComment | Comment contains ambiguous unicode character '𝐁' (did you mean 'B'?) | |
| RUF101 | ConvertExitToSysExit | `exit()` is only available in the interpreter, use `sys.exit()` instead | 🛠 |
### Meta rules
| Code | Name | Message | Fix |
| ---- | ---- | ------- | --- |
| M001 | UnusedNOQA | Unused `noqa` directive | 🛠 |
| RUF100 | UnusedNOQA | Unused `noqa` directive | 🛠 |
<!-- End auto-generated sections. -->
@@ -881,12 +932,14 @@ natively, including:
- [`flake8-eradicate`](https://pypi.org/project/flake8-eradicate/)
- [`flake8-print`](https://pypi.org/project/flake8-print/)
- [`flake8-quotes`](https://pypi.org/project/flake8-quotes/)
- [`flake8-return`](https://pypi.org/project/flake8-return/)
- [`flake8-super`](https://pypi.org/project/flake8-super/)
- [`flake8-tidy-imports`](https://pypi.org/project/flake8-tidy-imports/) (1/3)
- [`mccabe`](https://pypi.org/project/mccabe/)
- [`yesqa`](https://github.com/asottile/yesqa)
- [`eradicate`](https://pypi.org/project/eradicate/)
- [`pyupgrade`](https://pypi.org/project/pyupgrade/) (16/33)
- [`pygrep-hooks`](https://github.com/pre-commit/pygrep-hooks) (1/10)
- [`autoflake`](https://pypi.org/project/autoflake/) (1/7)
Beyond the rule set, Ruff suffers from the following limitations vis-à-vis Flake8:
@@ -896,6 +949,18 @@ Beyond the rule set, Ruff suffers from the following limitations vis-à-vis Flak
2. Flake8 has a plugin architecture and supports writing custom lint rules. (Instead, popular Flake8
plugins are re-implemented in Rust as part of Ruff itself.)
### How does Ruff compare to Pylint?
At time of writing, Pylint implements 409 total rules, while Ruff implements 224, of which
at least 60 overlap with the Pylint rule set. Subjectively, Pylint tends to implement more rules
based on type inference (e.g., validating the number of arguments in a function call).
Like Flake8, Pylint supports plugins (called "checkers"), while Ruff implements all checks natively.
Unlike Pylint, Ruff is capable of automatically fixing its own lint errors.
Pylint parity is being tracked in [#689](https://github.com/charliermarsh/ruff/issues/689).
### Which tools does Ruff replace?
Today, Ruff can be used to replace Flake8 when used with any of the following plugins:
@@ -915,12 +980,15 @@ Today, Ruff can be used to replace Flake8 when used with any of the following pl
- [`flake8-eradicate`](https://pypi.org/project/flake8-eradicate/)
- [`flake8-print`](https://pypi.org/project/flake8-print/)
- [`flake8-quotes`](https://pypi.org/project/flake8-quotes/)
- [`flake8-return`](https://pypi.org/project/flake8-return/)
- [`flake8-super`](https://pypi.org/project/flake8-super/)
- [`flake8-tidy-imports`](https://pypi.org/project/flake8-tidy-imports/) (1/3)
- [`mccabe`](https://pypi.org/project/mccabe/)
Ruff can also replace [`isort`](https://pypi.org/project/isort/), [`yesqa`](https://github.com/asottile/yesqa),
and a subset of the rules implemented in [`pyupgrade`](https://pypi.org/project/pyupgrade/) (16/33).
Ruff can also replace [`isort`](https://pypi.org/project/isort/),
[`yesqa`](https://github.com/asottile/yesqa), [`eradicate`](https://pypi.org/project/eradicate/),
[`pygrep-hooks`](https://github.com/pre-commit/pygrep-hooks) (1/10), and a subset of the rules
implemented in [`pyupgrade`](https://pypi.org/project/pyupgrade/) (16/33).
If you're looking to use Ruff, but rely on an unsupported Flake8 plugin, free to file an Issue.
@@ -1202,25 +1270,6 @@ Summary
### Options
#### [`dummy_variable_rgx`](#dummy_variable_rgx)
A regular expression used to identify "dummy" variables, or those which should be ignored when evaluating
(e.g.) unused-variable checks.
**Default value**: `"^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"` (matches `_`, `__`, and `_var`, but not `_var_`)
**Type**: `Regex`
**Example usage**:
```toml
[tool.ruff]
# Only ignore variables named "_".
dummy_variable_rgx = "^_$"
```
---
#### [`exclude`](#exclude)
A list of file patterns to exclude from linting.
@@ -1234,7 +1283,7 @@ Exclusions are based on globs, and can be either:
(to exclude any Python files in `directory`). Note that these paths are relative to the
project root (e.g., the directory containing your `pyproject.toml`).
Note that you'll typically want to use [`extend_exclude`](#extend_exclude) to modify the excluded
Note that you'll typically want to use [`extend-exclude`](#extend-exclude) to modify the excluded
paths.
**Default value**: `[".bzr", ".direnv", ".eggs", ".git", ".hg", ".mypy_cache", ".nox", ".pants.d", ".ruff_cache", ".svn", ".tox", ".venv", "__pypackages__", "_build", "buck-out", "build", "dist", "node_modules", "venv"]`
@@ -1250,7 +1299,7 @@ exclude = [".venv"]
---
#### [`extend_exclude`](#extend_exclude)
#### [`extend-exclude`](#extend-exclude)
A list of file patterns to omit from linting, in addition to those specified by `exclude`.
@@ -1290,7 +1339,7 @@ ignore = ["F841"]
---
#### [`extend_ignore`](#extend_ignore)
#### [`extend-ignore`](#extend-ignore)
A list of check code prefixes to ignore, in addition to those specified by `ignore`.
@@ -1330,7 +1379,7 @@ select = ["E", "F", "B", "Q"]
---
#### [`extend_select`](#extend_select)
#### [`extend-select`](#extend-select)
A list of check code prefixes to enable, in addition to those specified by `select`.
@@ -1348,6 +1397,27 @@ extend-select = ["B", "Q"]
---
#### [`external`](#external)
A list of check codes that are unsupported by Ruff, but should be preserved when (e.g.)
validating `# noqa` directives. Useful for retaining `# noqa` directives that cover plugins not
yet implemented in Ruff.
**Default value**: `[]`
**Type**: `Vec<String>`
**Example usage**:
```toml
[tool.ruff]
# Avoiding flagging (and removing) `V101` from any `# noqa` directives, despite Ruff's lack of
# support for `vulture`.
external = ["V101"]
```
---
#### [`fix`](#fix)
Enable autofix behavior by-default when running `ruff` (overridden by the `--fix` and `--no-fix`
@@ -1402,7 +1472,7 @@ unfixable = ["F401"]
---
#### [`line_length`](#line_length)
#### [`line-length`](#line-length)
The line length to use when enforcing long-lines violations (like E501).
@@ -1420,7 +1490,64 @@ line-length = 120
---
#### [`per_file_ignores`](#per_file_ignores)
#### [`dummy-variable-rgx`](#dummy-variable-rgx)
A regular expression used to identify "dummy" variables, or those which should be ignored when evaluating
(e.g.) unused-variable checks.
**Default value**: `"^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"` (matches `_`, `__`, and `_var`, but not `_var_`)
**Type**: `Regex`
**Example usage**:
```toml
[tool.ruff]
# Only ignore variables named "_".
dummy-variable-rgx = "^_$"
```
---
#### [`ignore-init-module-imports`](#ignore-init-module-imports)
Avoid automatically removing unused imports in `__init__.py` files. Such imports will still be
flagged, but with a dedicated message suggesting that the import is either added to the module's
`__all__` symbol, or re-exported with a redundant alias (e.g., `import os as os`).
**Default value**: `false`
**Type**: `bool`
**Example usage**:
```toml
[tool.ruff]
ignore-init-module-imports = true
```
---
#### [`format`](#format)
The style in which violation messages should be formatted: `"text"` (default), `"grouped"`
(group messages by file), `"json"` (machine-readable), `"junit"` (machine-readable XML), or `"github"` (GitHub Actions annotations).
**Default value**: `"text"`
**Type**: `SerializationFormat`
**Example usage**:
```toml
[tool.ruff]
# Group violations by containing file.
format = "grouped"
```
---
#### [`per-file-ignores`](#per-file-ignores)
A list of mappings from file pattern to check code prefixes to exclude, when considering any
matching files.
@@ -1441,7 +1568,7 @@ matching files.
---
#### [`show_source`](#show_source)
#### [`show-source`](#show-source)
Whether to show source code snippets when reporting lint error violations (overridden by the
`--show-source` command-line flag).
@@ -1455,7 +1582,7 @@ Whether to show source code snippets when reporting lint error violations (overr
```toml
[tool.ruff]
# By default, always show source code snippets.
show_source = true
show-source = true
```
---
@@ -1478,7 +1605,7 @@ src = ["src", "test"]
---
#### [`target_version`](#target_version)
#### [`target-version`](#target-version)
The Python version to target, e.g., when considering automatic code upgrades, like rewriting type
annotations. Note that the target version will _not_ be inferred from the _current_ Python version,
@@ -1498,7 +1625,7 @@ target-version = "py37"
### `flake8-annotations`
#### [`mypy_init_return`](#mypy_init_return)
#### [`mypy-init-return`](#mypy-init-return)
Whether to allow the omission of a return type hint for `__init__` if at least one argument is
annotated.
@@ -1511,12 +1638,12 @@ annotated.
```toml
[tool.ruff.flake8-annotations]
mypy_init_return = true
mypy-init-return = true
```
---
#### [`suppress_dummy_args`](#suppress_dummy_args)
#### [`suppress-dummy-args`](#suppress-dummy-args)
Whether to suppress `ANN000`-level errors for arguments matching the "dummy" variable regex (like
`_`).
@@ -1529,12 +1656,12 @@ Whether to suppress `ANN000`-level errors for arguments matching the "dummy" var
```toml
[tool.ruff.flake8-annotations]
suppress_dummy_args = true
suppress-dummy-args = true
```
---
#### [`suppress_none_returning`](#suppress_none_returning)
#### [`suppress-none-returning`](#suppress-none-returning)
Whether to suppress `ANN200`-level errors for functions that meet either of the following criteria:
@@ -1549,12 +1676,12 @@ Whether to suppress `ANN200`-level errors for functions that meet either of the
```toml
[tool.ruff.flake8-annotations]
suppress_none_returning = true
suppress-none-returning = true
```
---
#### [`allow_star_arg_any`](#allow_star_arg_any)
#### [`allow-star-arg-any`](#allow-star-arg-any)
Whether to suppress `ANN401` for dynamically typed `*args` and `**kwargs` arguments.
@@ -1566,12 +1693,12 @@ Whether to suppress `ANN401` for dynamically typed `*args` and `**kwargs` argume
```toml
[tool.ruff.flake8-annotations]
allow_star_arg_any = true
allow-star-arg-any = true
```
### `flake8-bugbear`
#### [`extend_immutable_calls`](#extend_immutable_calls)
#### [`extend-immutable-calls`](#extend-immutable-calls)
Additional callable functions to consider "immutable" when evaluating, e.g., no-mutable-default-argument
checks (`B006`).
@@ -1590,7 +1717,7 @@ extend-immutable-calls = ["fastapi.Depends", "fastapi.Query"]
### `flake8-quotes`
#### [`inline_quotes`](#inline_quotes)
#### [`inline-quotes`](#inline-quotes)
Quote style to prefer for inline strings (either "single" (`'`) or "double" (`"`)).
@@ -1607,7 +1734,7 @@ inline-quotes = "single"
---
#### [`multiline_quotes`](#multiline_quotes)
#### [`multiline-quotes`](#multiline-quotes)
Quote style to prefer for multiline strings (either "single" (`'`) or "double" (`"`)).
@@ -1624,7 +1751,7 @@ multiline-quotes = "single"
---
#### [`docstring_quotes`](#docstring_quotes)
#### [`docstring-quotes`](#docstring-quotes)
Quote style to prefer for docstrings (either "single" (`'`) or "double" (`"`)).
@@ -1641,7 +1768,7 @@ docstring-quotes = "single"
---
#### [`avoid_escape`](#avoid_escape)
#### [`avoid-escape`](#avoid-escape)
Whether to avoid using single quotes if a string contains single quotes, or vice-versa with
double quotes, as per [PEP8](https://peps.python.org/pep-0008/#string-quotes). This minimizes the
@@ -1661,7 +1788,7 @@ avoid-escape = false
### `flake8-tidy-imports`
#### [`ban_relative_imports`](#ban_relative_imports)
#### [`ban-relative-imports`](#ban-relative-imports)
Whether to ban all relative imports (`"all"`), or only those imports that extend into the parent
module and beyond (`"parents"`).
@@ -1680,7 +1807,25 @@ ban-relative-imports = "all"
### `isort`
#### [`known_first_party`](known_first_party)
#### [`combine-as-imports`](#combine-as-imports)
Combines as imports on the same line. See isort's [`combine-as-imports`](https://pycqa.github.io/isort/docs/configuration/options.html#combine-as-imports)
option.
**Default value**: `false`
**Type**: `bool`
**Example usage**:
```toml
[tool.ruff.isort]
combine-as-imports = true
```
---
#### [`known-first-party`](#known-first-party)
A list of modules to consider first-party, regardless of whether they can be identified as such
via introspection of the local filesystem.
@@ -1698,7 +1843,7 @@ known-first-party = ["src"]
---
#### [`known_third_party`](known_third_party)
#### [`known-third-party`](#known-third-party)
A list of modules to consider third-party, regardless of whether they can be identified as such
via introspection of the local filesystem.
@@ -1716,7 +1861,7 @@ known-third-party = ["fastapi"]
---
#### [`extra_standard_library`](extra_standard_library)
#### [`extra-standard-library`](#extra-standard-library)
A list of modules to consider standard-library, in addition to those known to Ruff in advance.
@@ -1733,7 +1878,7 @@ extra-standard-library = ["path"]
### `mccabe`
#### [`max_complexity`](#max_complexity)
#### [`max-complexity`](#max-complexity)
The maximum McCabe complexity to allow before triggering `C901` errors.
@@ -1744,14 +1889,14 @@ The maximum McCabe complexity to allow before triggering `C901` errors.
**Example usage**:
```toml
[tool.ruff.flake8-tidy-imports]
[tool.ruff.mccabe]
# Flag errors (`C901`) whenever the complexity level exceeds 5.
max-complexity = 5
```
### `pep8-naming`
#### [`ignore_names`](#ignore_names)
#### [`ignore-names`](#ignore-names)
A list of names to ignore when considering `pep8-naming` violations.
@@ -1768,7 +1913,7 @@ ignore-names = ["callMethod"]
---
#### [`classmethod_decorators`](#classmethod_decorators)
#### [`classmethod-decorators`](#classmethod-decorators)
A list of decorators that, when applied to a method, indicate that the method should be treated as
a class method. For example, Ruff will expect that any method decorated by a decorator in this list
@@ -1788,7 +1933,7 @@ classmethod-decorators = ["classmethod", "pydantic.validator"]
---
#### [`staticmethod_decorators`](#staticmethod_decorators)
#### [`staticmethod-decorators`](#staticmethod-decorators)
A list of decorators that, when applied to a method, indicate that the method should be treated as
a static method. For example, Ruff will expect that any method decorated by a decorator in this list
@@ -1806,6 +1951,26 @@ has no `self` or `cls` argument.
staticmethod-decorators = ["staticmethod", "stcmthd"]
```
### `pyupgrade`
#### [`keep-runtime-typing`](#keep-runtime-typing)
Whether to avoid PEP 585 (`List[int]` -> `list[int]`) and PEP 604 (`Optional[str]` -> `str | None`)
rewrites even if a file imports `from __future__ import annotations`. Note that this setting is
only applicable when the target Python version is below 3.9 and 3.10 respectively.
**Default value**: `false`
**Type**: `bool`
**Example usage**:
```toml
[tool.ruff.pyupgrade]
# Preserve types, even if a file imports `from __future__ import annotations`.
keep-runtime-typing = true
```
## License
MIT

11
create_plugin.sh Executable file
View File

@@ -0,0 +1,11 @@
set -euxo pipefail
NAME=$1
mkdir -p src/$1
mkdir -p resources/test/fixtures/$1
touch src/$1/mod.rs
sed -i "" "s/mod flake8_print;/mod flake8_print; mod flake8_return;/g" src/lib.rs
sed -i "" "s|// flake8-print|// flake8-return\n// flake8-print|g" src/checks.rs

View File

@@ -771,7 +771,7 @@ checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
[[package]]
name = "flake8_to_ruff"
version = "0.0.145"
version = "0.0.157"
dependencies = [
"anyhow",
"clap",
@@ -1975,7 +1975,7 @@ dependencies = [
[[package]]
name = "ruff"
version = "0.0.145"
version = "0.0.157"
dependencies = [
"anyhow",
"bincode",

View File

@@ -1,6 +1,6 @@
[package]
name = "flake8-to-ruff"
version = "0.0.145-dev.0"
version = "0.0.157-dev.0"
edition = "2021"
[lib]

View File

@@ -248,9 +248,12 @@ mod tests {
extend_exclude: None,
extend_ignore: None,
extend_select: None,
external: None,
fix: None,
fixable: None,
format: None,
ignore: Some(vec![]),
ignore_init_module_imports: None,
line_length: None,
per_file_ignores: None,
select: Some(vec![
@@ -269,6 +272,7 @@ mod tests {
isort: None,
mccabe: None,
pep8_naming: None,
pyupgrade: None,
});
assert_eq!(actual, expected);
@@ -287,9 +291,12 @@ mod tests {
extend_exclude: None,
extend_ignore: None,
extend_select: None,
external: None,
fix: None,
fixable: None,
format: None,
ignore: Some(vec![]),
ignore_init_module_imports: None,
line_length: Some(100),
per_file_ignores: None,
select: Some(vec![
@@ -308,6 +315,7 @@ mod tests {
isort: None,
mccabe: None,
pep8_naming: None,
pyupgrade: None,
});
assert_eq!(actual, expected);
@@ -326,9 +334,12 @@ mod tests {
extend_exclude: None,
extend_ignore: None,
extend_select: None,
external: None,
fix: None,
fixable: None,
format: None,
ignore: Some(vec![]),
ignore_init_module_imports: None,
line_length: Some(100),
per_file_ignores: None,
select: Some(vec![
@@ -347,6 +358,7 @@ mod tests {
isort: None,
mccabe: None,
pep8_naming: None,
pyupgrade: None,
});
assert_eq!(actual, expected);
@@ -365,9 +377,12 @@ mod tests {
extend_exclude: None,
extend_ignore: None,
extend_select: None,
external: None,
fix: None,
fixable: None,
format: None,
ignore: Some(vec![]),
ignore_init_module_imports: None,
line_length: None,
per_file_ignores: None,
select: Some(vec![
@@ -386,6 +401,7 @@ mod tests {
isort: None,
mccabe: None,
pep8_naming: None,
pyupgrade: None,
});
assert_eq!(actual, expected);
@@ -404,9 +420,12 @@ mod tests {
extend_exclude: None,
extend_ignore: None,
extend_select: None,
external: None,
fix: None,
fixable: None,
format: None,
ignore: Some(vec![]),
ignore_init_module_imports: None,
line_length: None,
per_file_ignores: None,
select: Some(vec![
@@ -430,6 +449,7 @@ mod tests {
isort: None,
mccabe: None,
pep8_naming: None,
pyupgrade: None,
});
assert_eq!(actual, expected);
@@ -451,9 +471,12 @@ mod tests {
extend_exclude: None,
extend_ignore: None,
extend_select: None,
external: None,
fix: None,
fixable: None,
format: None,
ignore: Some(vec![]),
ignore_init_module_imports: None,
line_length: None,
per_file_ignores: None,
select: Some(vec![
@@ -507,6 +530,7 @@ mod tests {
isort: None,
mccabe: None,
pep8_naming: None,
pyupgrade: None,
});
assert_eq!(actual, expected);
@@ -525,9 +549,12 @@ mod tests {
extend_exclude: None,
extend_ignore: None,
extend_select: None,
external: None,
fix: None,
fixable: None,
format: None,
ignore: Some(vec![]),
ignore_init_module_imports: None,
line_length: None,
per_file_ignores: None,
select: Some(vec![
@@ -552,6 +579,7 @@ mod tests {
isort: None,
mccabe: None,
pep8_naming: None,
pyupgrade: None,
});
assert_eq!(actual, expected);

View File

@@ -46,7 +46,7 @@ fn main() -> Result<()> {
// Extract the Flake8 section.
let flake8 = config
.get("flake8")
.expect("Unable to find flake8 section in INI file.");
.expect("Unable to find flake8 section in INI file");
// Create the pyproject.toml.
let pyproject = converter::convert(flake8, cli.plugin)?;

View File

@@ -1,6 +1,6 @@
use std::str::FromStr;
use anyhow::Result;
use anyhow::{bail, Result};
use once_cell::sync::Lazy;
use regex::Regex;
use ruff::checks_gen::CheckCodePrefix;
@@ -42,7 +42,7 @@ pub fn parse_bool(value: &str) -> Result<bool> {
match value.trim() {
"true" => Ok(true),
"false" => Ok(false),
_ => Err(anyhow::anyhow!("Unexpected boolean value: {value}")),
_ => bail!("Unexpected boolean value: {value}"),
}
}
@@ -154,7 +154,7 @@ pub fn parse_files_to_codes_mapping(value: &str) -> Result<Vec<PatternPrefixPair
state.filenames.push(token.src);
state.seen_sep = false;
} else {
return Err(anyhow::anyhow!("Unexpected token: {:?}", token.token_name));
bail!("Unexpected token: {:?}", token.token_name);
}
} else {
if matches!(token.token_name, TokenType::Eof) {
@@ -169,7 +169,7 @@ pub fn parse_files_to_codes_mapping(value: &str) -> Result<Vec<PatternPrefixPair
state.filenames.push(token.src);
state.seen_sep = false;
} else {
return Err(anyhow::anyhow!("Unexpected token: {:?}", token.token_name));
bail!("Unexpected token: {:?}", token.token_name);
}
}
}

View File

@@ -17,6 +17,7 @@ pub enum Plugin {
Flake8Eradicate,
Flake8Print,
Flake8Quotes,
Flake8Return,
Flake8TidyImports,
McCabe,
PEP8Naming,
@@ -39,11 +40,12 @@ impl FromStr for Plugin {
"flake8-eradicate" => Ok(Plugin::Flake8BlindExcept),
"flake8-print" => Ok(Plugin::Flake8Print),
"flake8-quotes" => Ok(Plugin::Flake8Quotes),
"flake8-return" => Ok(Plugin::Flake8Return),
"flake8-tidy-imports" => Ok(Plugin::Flake8TidyImports),
"mccabe" => Ok(Plugin::McCabe),
"pep8-naming" => Ok(Plugin::PEP8Naming),
"pyupgrade" => Ok(Plugin::Pyupgrade),
_ => Err(anyhow!("Unknown plugin: {}", string)),
_ => Err(anyhow!("Unknown plugin: {string}")),
}
}
}
@@ -62,6 +64,7 @@ impl Plugin {
Plugin::Flake8Eradicate => CheckCodePrefix::ERA,
Plugin::Flake8Print => CheckCodePrefix::T2,
Plugin::Flake8Quotes => CheckCodePrefix::Q,
Plugin::Flake8Return => CheckCodePrefix::RET,
Plugin::Flake8TidyImports => CheckCodePrefix::I25,
Plugin::McCabe => CheckCodePrefix::C9,
Plugin::PEP8Naming => CheckCodePrefix::N,
@@ -97,6 +100,7 @@ impl Plugin {
Plugin::Flake8Eradicate => vec![CheckCodePrefix::ERA],
Plugin::Flake8Print => vec![CheckCodePrefix::T2],
Plugin::Flake8Quotes => vec![CheckCodePrefix::Q],
Plugin::Flake8Return => vec![CheckCodePrefix::RET],
Plugin::Flake8TidyImports => vec![CheckCodePrefix::I25],
Plugin::McCabe => vec![CheckCodePrefix::C9],
Plugin::PEP8Naming => vec![CheckCodePrefix::N],
@@ -121,7 +125,7 @@ impl FromStr for DocstringConvention {
"pep8" => Ok(DocstringConvention::PEP8),
"numpy" => Ok(DocstringConvention::NumPy),
"google" => Ok(DocstringConvention::Google),
_ => Err(anyhow!("Unknown docstring convention: {}", string)),
_ => Err(anyhow!("Unknown docstring convention: {string}")),
}
}
}
@@ -389,6 +393,7 @@ pub fn infer_plugins_from_codes(codes: &BTreeSet<CheckCodePrefix>) -> Vec<Plugin
Plugin::Flake8Eradicate,
Plugin::Flake8Print,
Plugin::Flake8Quotes,
Plugin::Flake8Return,
Plugin::Flake8TidyImports,
Plugin::PEP8Naming,
Plugin::Pyupgrade,

View File

@@ -31,7 +31,3 @@ build-backend = "maturin"
[tool.maturin]
bindings = "bin"
strip = true
[tool.isort]
profile = "black"
known_third_party = ["fastapi", "pydantic", "starlette"]

View File

@@ -1,3 +0,0 @@
# coding=utf8 # noqa: U009
print("Hello world")

View File

@@ -2,6 +2,7 @@ breakpoint()
import pdb
import builtins
from builtins import breakpoint
from pdb import set_trace as st
from celery.contrib.rdb import set_trace

View File

@@ -0,0 +1,4 @@
def x(y):
if not y:
return
return None # error

View File

@@ -0,0 +1,65 @@
def x(y):
if not y:
return # error
return 1
# without return value
def x(y):
if not y:
return
return
def x(y):
if y:
return
print()
# with return value
def x(y):
if not y:
return 1
return 2
def x(y):
for i in range(10):
if i > 100:
return i
else:
return 1
def x(y):
try:
return 1
except:
return 2
def x(y):
try:
return 1
finally:
return 2
# inner function
def x(y):
if not y:
return 1
def inner():
return
return 2
def x(y):
if not y:
return
def inner():
return 1

View File

@@ -0,0 +1,116 @@
###
# Errors
###
# if/elif/else
def x(y):
if not y:
return 1
# error
def x(y):
if not y:
print() # error
else:
return 2
def x(y):
if not y:
return 1
print() # error
# for
def x(y):
for i in range(10):
if i > 10:
return i
# error
def x(y):
for i in range(10):
if i > 10:
return i
else:
print() # error
###
# Non-errors
###
# raise as last return
def x(y):
if not y:
return 1
raise Exception
# last line in while loop
def x(y):
while True:
if y > 0:
return 1
y += 1
# exclude empty functions
def x(y):
return None
# return inner with statement
def x(y):
with y:
return 1
async def function():
async with thing as foo:
return foo.bar
# assert as last return
def x(y):
if not y:
return 1
assert False, "Sanity check"
# return value within loop
def bar1(x, y, z):
for i in x:
if i > y:
break
return z
def bar3(x, y, z):
for i in x:
if i > y:
if z:
break
else:
return z
return None
def bar1(x, y, z):
for i in x:
if i < y:
continue
return z
def bar3(x, y, z):
for i in x:
if i < y:
if z:
continue
else:
return z
return None

View File

@@ -0,0 +1,232 @@
###
# Errors
###
def x():
a = 1
return a # error
def x():
b, a = 1, 2
print(b)
return a # error
def x():
a = 1
print()
return a # error
def x():
a = 1
print(a)
a = 2
return a # error
def x():
a = 1
if True:
return a # error
a = 2
print(a)
return a
# Can be refactored false positives
# https://github.com/afonasev/flake8-return/issues/47#issuecomment-1122571066
def get_bar_if_exists(obj):
result = ""
if hasattr(obj, "bar"):
result = str(obj.bar)
return result
# https://github.com/afonasev/flake8-return/issues/47#issue-641117366
def x():
formatted = _USER_AGENT_FORMATTER.format(format_string, **values)
# clean up after any blank components
formatted = formatted.replace("()", "").replace(" ", " ").strip()
return formatted
# https://github.com/afonasev/flake8-return/issues/47#issue-641117366
def user_agent_username(username=None):
if not username:
return ""
username = username.replace(" ", "_") # Avoid spaces or %20.
try:
username.encode("ascii") # just test, but not actually use it
except UnicodeEncodeError:
username = quote(username.encode("utf-8"))
else:
# % is legal in the default $wgLegalTitleChars
# This is so that ops know the real pywikibot will not
# allow a useragent in the username to allow through a hand-coded
# percent-encoded value.
if "%" in username:
username = quote(username)
return username
###
# Non-errors
###
def x(y):
a = 1
print(a)
return a
def x():
a = 1
if y:
return a
a = a + 2
print(a)
return a
def x():
a = {}
a["b"] = 2
return a
def x():
a = []
a.append(2)
return a
def x():
a = lambda x: x
a()
return a
# ignore unpacking
def x():
b, a = [1, 2]
return a
def x():
val = ""
for i in range(5):
val = val + str(i)
return val
def x():
val = ""
i = 5
while i:
val = val + str(i)
i = i - x
return val
# Test cases for using value for assignment then returning it
# See:https://github.com/afonasev/flake8-return/issues/47
def resolve_from_url(self, url: str) -> dict:
local_match = self.local_scope_re.match(url)
if local_match:
schema = get_schema(name=local_match.group(1))
self.store[url] = schema
return schema
raise NotImplementedError(...)
my_dict = {}
def my_func():
foo = calculate_foo()
my_dict["foo_result"] = foo
return foo
# Refactored incorrect false positives
# See test cases above marked: "Can be refactored false positives"
# https://github.com/afonasev/flake8-return/issues/47#issuecomment-1122571066
def get_bar_if_exists(obj):
if hasattr(obj, "bar"):
return str(obj.bar)
return ""
# https://github.com/afonasev/flake8-return/issues/47#issue-641117366
def x():
formatted = _USER_AGENT_FORMATTER.format(format_string, **values)
# clean up after any blank components
return formatted.replace("()", "").replace(" ", " ").strip()
# https://github.com/afonasev/flake8-return/issues/47#issue-641117366
def user_agent_username(username=None):
if not username:
return ""
username = username.replace(" ", "_") # Avoid spaces or %20.
try:
username.encode("ascii") # just test,
# but not actually use it
except UnicodeEncodeError:
username = quote(username.encode("utf-8"))
else:
# % is legal in the default $wgLegalTitleChars
# This is so that ops know the real pywikibot will not
# allow a useragent in the username to allow through a
# hand-coded percent-encoded value.
if "%" in username:
username = quote(username)
return username
# https://github.com/afonasev/flake8-return/issues/116#issue-1367575481
def no_exception_loop():
success = False
for _ in range(10):
try:
success = True
except Exception:
print("exception")
return success
# https://github.com/afonasev/flake8-return/issues/116#issue-1367575481
def no_exception():
success = False
try:
success = True
except Exception:
print("exception")
return success
# https://github.com/afonasev/flake8-return/issues/116#issue-1367575481
def exception():
success = True
try:
print("raising")
raise Exception
except Exception:
success = False
return success
# https://github.com/afonasev/flake8-return/issues/66
def close(self):
any_failed = False
for task in self.tasks:
try:
task()
except BaseException:
any_failed = True
report(traceback.format_exc())
return any_failed

View File

@@ -0,0 +1,141 @@
###
# Error
###
def foo2(x, y, w, z):
if x: # [no-else-return]
a = 1
return y
elif z:
b = 2
return w
else:
c = 3
return z
def foo5(x, y, z):
if x: # [no-else-return]
if y:
a = 4
else:
b = 2
return
elif z:
c = 2
else:
c = 3
return
def foo2(x, y, w, z):
if x:
a = 1
elif z:
b = 2
else:
c = 3
if x: # [no-else-return]
a = 1
return y
elif z:
b = 2
return w
else:
c = 3
return z
def foo1(x, y, z):
if x: # [no-else-return]
a = 1
return y
else:
b = 2
return z
def foo3(x, y, z):
if x:
a = 1
if y: # [no-else-return]
b = 2
return y
else:
c = 3
return x
else:
d = 4
return z
def foo4(x, y):
if x: # [no-else-return]
if y:
a = 4
else:
b = 2
return
else:
c = 3
return
def foo6(x, y):
if x:
if y: # [no-else-return]
a = 4
return
else:
b = 2
else:
c = 3
return
def bar4(x):
if x: # [no-else-return]
return True
else:
try:
return False
except ValueError:
return None
###
# Non-error
###
def bar1(x, y, z):
if x:
return y
return z
def bar2(w, x, y, z):
if x:
return y
if z:
a = 1
else:
return w
return None
def bar3(x, y, z):
if x:
if z:
return y
else:
return z
return None
x = 0
if x == 1:
y = "a"
elif x == 2:
y = "b"
else:
y = "c"

View File

@@ -0,0 +1,112 @@
###
# Errors
###
def foo2(x, y, w, z):
if x: # [no-else-raise]
a = 1
raise Exception(y)
elif z:
b = 2
raise Exception(w)
else:
c = 3
raise Exception(z)
def foo5(x, y, z):
if x: # [no-else-raise]
if y:
a = 4
else:
b = 2
raise Exception(x)
elif z:
raise Exception(y)
else:
c = 3
raise Exception(z)
def foo1(x, y, z):
if x: # [no-else-raise]
a = 1
raise Exception(y)
else:
b = 2
raise Exception(z)
def foo3(x, y, z):
if x:
a = 1
if y: # [no-else-raise]
b = 2
raise Exception(y)
else:
c = 3
raise Exception(x)
else:
d = 4
raise Exception(z)
def foo4(x, y):
if x: # [no-else-raise]
if y:
a = 4
else:
b = 2
raise Exception(x)
else:
c = 3
raise Exception(y)
def foo6(x, y):
if x:
if y: # [no-else-raise]
a = 4
raise Exception(x)
else:
b = 2
else:
c = 3
raise Exception(y)
def bar4(x):
if x: # [no-else-raise]
raise Exception(True)
else:
try:
raise Exception(False)
except ValueError:
raise Exception(None)
###
# Non-errors
###
def bar1(x, y, z):
if x:
raise Exception(y)
raise Exception(z)
def bar2(w, x, y, z):
if x:
raise Exception(y)
if z:
a = 1
else:
raise Exception(w)
raise Exception(None)
def bar3(x, y, z):
if x:
if z:
raise Exception(y)
else:
raise Exception(z)
raise Exception(None)

View File

@@ -0,0 +1,106 @@
###
# Errors
###
def foo2(x, y, w, z):
for i in x:
if i < y: # [no-else-continue]
continue
elif i < w:
continue
else:
a = z
def foo5(x, y, z):
for i in x:
if i < y: # [no-else-continue]
if y:
a = 4
else:
b = 2
continue
elif z:
c = 2
else:
c = 3
continue
###
# Non-errors
###
def foo1(x, y, z):
for i in x:
if i < y: # [no-else-continue]
continue
else:
a = z
def foo3(x, y, z):
for i in x:
if i < y:
a = 1
if z: # [no-else-continue]
b = 2
continue
else:
c = 3
continue
else:
d = 4
continue
def foo4(x, y):
for i in x:
if i < x: # [no-else-continue]
if y:
a = 4
else:
b = 2
continue
else:
c = 3
continue
def foo6(x, y):
for i in x:
if i < x:
if y: # [no-else-continue]
a = 4
continue
else:
b = 2
else:
c = 3
continue
def bar4(x):
for i in range(10):
if x: # [no-else-continue]
continue
else:
try:
return
except ValueError:
continue
def bar1(x, y, z):
for i in x:
if i < y:
continue
return z
def bar3(x, y, z):
for i in x:
if i < y:
if z:
continue
else:
return z
return None

View File

@@ -0,0 +1,138 @@
###
# Errors
###
def foo2(x, y, w, z):
for i in x:
if i > y: # [no-else-break]
break
elif i > w:
break
else:
a = z
def foo5(x, y, z):
for i in x:
if i > y: # [no-else-break]
if y:
a = 4
else:
b = 2
break
elif z:
c = 2
else:
c = 3
break
def foo1(x, y, z):
for i in x:
if i > y: # [no-else-break]
break
else:
a = z
def foo3(x, y, z):
for i in x:
if i > y:
a = 1
if z: # [no-else-break]
b = 2
break
else:
c = 3
break
else:
d = 4
break
def foo4(x, y):
for i in x:
if i > x: # [no-else-break]
if y:
a = 4
else:
b = 2
break
else:
c = 3
break
def foo6(x, y):
for i in x:
if i > x:
if y: # [no-else-break]
a = 4
break
else:
b = 2
else:
c = 3
break
def bar4(x):
for i in range(10):
if x: # [no-else-break]
break
else:
try:
return
except ValueError:
break
###
# Non-errors
###
def bar1(x, y, z):
for i in x:
if i > y:
break
return z
def bar2(w, x, y, z):
for i in w:
if i > x:
break
if z < i:
a = y
else:
break
return
def bar3(x, y, z):
for i in x:
if i > y:
if z:
break
else:
return z
return None
def nested1(x, y, z):
for i in x:
if i > x:
for j in y:
if j < z:
break
else:
a = z
def nested2(x, y, z):
for i in x:
if i > x:
for j in y:
if j > z:
break
break
else:
a = z

View File

@@ -0,0 +1,4 @@
from module import Class as C
from module import CONSTANT
from module import function
from module import function as f

Some files were not shown because too many files have changed in this diff Show More