Compare commits

...

27 Commits

Author SHA1 Message Date
Charlie Marsh
fac6e83705 Avoid 2023-06-22 23:30:23 -04:00
Tom Kuson
1cf307c34c Fix collection-literal-concatenation documentation (#5320)
## Summary

Move `collection-literal-concatenation` markdown documentation to the
correct place.

Fixes error in #5262.

## Test Plan

`python scripts/check_docs_formatted.py`
2023-06-22 18:37:54 -04:00
Charlie Marsh
7819b95d7f Avoid syntax errors when removing f-string prefixes (#5319)
Closes https://github.com/astral-sh/ruff/issues/5281.

Closes https://github.com/astral-sh/ruff/issues/4827.
2023-06-22 17:21:09 -04:00
Lukas Mayrhofer
4a81cfc51a Allow @Author format for "Missing Author" rule in flake8-todos (#4903)
## Summary

The TD-002 rule "Missing Author" was updated to allow another format
using "@". This reflects the current 0.3.0 version of flake8-todos.
2023-06-22 20:53:58 +00:00
qdegraaf
38e618cd18 [perflint] Add PERF101 with autofix (#5121)
## Summary

Adds PERF101 which checks for unnecessary casts to `list` in for loops. 

NOTE: Is not fully equal to its upstream implementation as this
implementation does not flag based on type annotations
(i.e.):
```python
def foo(x: List[str]):
    for y in list(x):
        ...
```

With the current set-up it's quite hard to get the annotation from a
function arg from its binding. Problem is best considered broader than
this implementation.

## Test Plan

Added fixture. 

## Issue links

Refers: https://github.com/astral-sh/ruff/issues/4789

---------

Co-authored-by: Charlie Marsh <charlie.r.marsh@gmail.com>
2023-06-22 20:44:26 +00:00
Charlie Marsh
50f0edd2cb Add dark- and light-mode image modifiers for custom MkDocs themes (#5318)
## Summary

Roughly following the docs
[here](https://squidfunk.github.io/mkdocs-material/reference/images/#custom-light-scheme).

Closes #5311.
2023-06-22 16:11:38 -04:00
Edgar R. M
e0e1d13d9f Fix diagnostics variable name in add_plugin.py script (#5317)
## Summary

Fix a variable name in the `add_plugin.py` script.

## Test Plan

I don't think there are any tests for the scripts, other than manual
confirmation
2023-06-22 20:06:47 +00:00
Charlie Marsh
8bc7378002 Add PythonVersion::Py312 (#5316)
Closes #5310.
2023-06-22 20:01:07 +00:00
Charlie Marsh
cdbd0bd5cd Respect abc decorators when classifying function types (#5315)
Closes #5307.
2023-06-22 19:52:36 +00:00
Charlie Marsh
5f88ff8a96 Allow __slots__ assignments in mutable-class-default (#5314)
Closes #5309.
2023-06-22 19:40:54 +00:00
Charlie Marsh
1c2be54b4a Support pydantic.BaseSettings in mutable-class-default (#5312)
Closes #5308.
2023-06-22 19:27:05 +00:00
Charlie Marsh
5dd00b19e6 Remove off-palette colors from code (#5305) 2023-06-22 16:31:22 +00:00
Charlie Marsh
c0f93fcf3e Publish GitHub release as draft (#5304)
I accidentally changed `draft: false` to `draft: true` in #5240. I
actually think Copilot did this without me realizing.
2023-06-22 16:11:43 +00:00
Charlie Marsh
3238a6ef1f Fix 'our' to 'your' typo (#5303) 2023-06-22 15:58:24 +00:00
Charlie Marsh
96ecfae1c5 Remove off-palette colors (#5302) 2023-06-22 15:52:03 +00:00
konstin
03694ef649 More stability checker options (#5299)
## Summary

This contains three changes:
* repos in `check_ecosystem.py` are stored as `org:name` instead of
`org/name` to create a flat directory layout
* `check_ecosystem.py` performs a maximum of 50 parallel jobs at the
same time to avoid consuming to much RAM
* `check-formatter-stability` gets a new option `--multi-project` so
it's possible to do `cargo run --bin ruff_dev --
check-formatter-stability --multi-project target/checkouts`
With these three changes it becomes easy to check the formatter
stability over a larger number of repositories. This is part of the
integration of integrating formatter regressions checks into the
ecosystem checks.

## Test Plan

```shell
python scripts/check_ecosystem.py --checkouts target/checkouts --projects github_search.jsonl -v $(which true) $(which true)
cargo run --bin ruff_dev -- check-formatter-stability --multi-project target/checkouts
```
2023-06-22 15:48:11 +00:00
Charlie Marsh
f9f0cf7524 Use __future__ imports in scripts (#5301) 2023-06-22 11:40:16 -04:00
Tom Kuson
eaa10ad2d9 Fix deprecated-import false positives (#5291)
## Summary

Remove recommendations to replace
`typing_extensions.dataclass_transform` and
`typing_extensions.SupportsIndex` with their `typing` library
counterparts.

Closes #5112.

## Test Plan

Added extra checks to the test fixture.

`cargo test`
2023-06-22 15:34:44 +00:00
Evan Rittenhouse
84259f5440 Add Applicability to pycodestyle (#5282) 2023-06-22 11:25:20 -04:00
trag1c
e8ebe0a425 Update docs to match updated logo and color palette (#5283)
![8511](https://github.com/astral-sh/ruff/assets/77130613/862d151f-ff1d-4da8-9230-8dd32f41f197)

## Summary

Supersedes #5277, includes redesigned dark mode.

## Test Plan

* `python scripts/generate_mkdocs.py`
* `mkdocs serve`
2023-06-22 11:19:34 -04:00
konstin
d407165aa7 Fix formatter panic with comment after parenthesized dict value (#5293)
## Summary

This snippet used to panic because it expected to see a comma or
something similar after the `2` but met the closing parentheses that is
not part of the range and panicked
```python
a = {
    1: (2),
    # comment
    3: True,
}
```

Originally found in
636a717ef0/testing/marionette/client/marionette_driver/geckoinstance.py (L109)

This snippet is also the test plan.
2023-06-22 16:52:48 +02:00
Micha Reiser
f7e1cf4b51 Format class definitions (#5289) 2023-06-22 09:09:43 +00:00
konstin
7d4f8e59da Improve FormatExprCall dummy (#5290)
This solves an instability when formatting cpython. It also introduces
another one, but i think it's still a worthwhile change for now.

There's no proper testing since this is just a dummy.
2023-06-22 10:59:30 +02:00
Charlie Marsh
2c63f8cdea Update reference to release step (#5280) 2023-06-22 02:04:43 +00:00
Charlie Marsh
1c0a3a467f Bump version to 0.0.275 (#5276) 2023-06-21 21:53:37 -04:00
Charlie Marsh
6b8b318d6b Use mod tests consistently (#5278)
As per the Rust documentation.
2023-06-22 01:50:28 +00:00
Charlie Marsh
c0c59b82ec Use 'Checks for uses' consistently (#5279) 2023-06-22 01:44:52 +00:00
138 changed files with 2304 additions and 1191 deletions

View File

@@ -491,16 +491,16 @@ jobs:
- name: "Publish to GitHub"
uses: softprops/action-gh-release@v1
with:
draft: false
draft: true
files: binaries/*
tag_name: v${{ inputs.tag }}
# After the release has been published, we update downstream repositories
# This is separate because if this fails the release is still fine, we just need to do some manual workflow triggers
update-dependents:
name: Release
name: Update dependents
runs-on: ubuntu-latest
needs: release
needs: publish-release
steps:
- name: "Update pre-commit mirror"
uses: actions/github-script@v6

18
Cargo.lock generated
View File

@@ -733,7 +733,7 @@ dependencies = [
[[package]]
name = "flake8-to-ruff"
version = "0.0.274"
version = "0.0.275"
dependencies = [
"anyhow",
"clap",
@@ -1793,7 +1793,7 @@ dependencies = [
[[package]]
name = "ruff"
version = "0.0.274"
version = "0.0.275"
dependencies = [
"annotate-snippets 0.9.1",
"anyhow",
@@ -1889,7 +1889,7 @@ dependencies = [
[[package]]
name = "ruff_cli"
version = "0.0.274"
version = "0.0.275"
dependencies = [
"annotate-snippets 0.9.1",
"anyhow",
@@ -2105,7 +2105,7 @@ dependencies = [
[[package]]
name = "ruff_text_size"
version = "0.0.0"
source = "git+https://github.com/astral-sh/RustPython-Parser.git?rev=08ebbe40d7776cac6e3ba66277d435056f2b8dca#08ebbe40d7776cac6e3ba66277d435056f2b8dca"
source = "git+https://github.com/astral-sh/RustPython-Parser.git?rev=f60e204b73b95bdb6ce87ccd0de34081b4a17c11#f60e204b73b95bdb6ce87ccd0de34081b4a17c11"
dependencies = [
"schemars",
"serde",
@@ -2183,7 +2183,7 @@ dependencies = [
[[package]]
name = "rustpython-ast"
version = "0.2.0"
source = "git+https://github.com/astral-sh/RustPython-Parser.git?rev=08ebbe40d7776cac6e3ba66277d435056f2b8dca#08ebbe40d7776cac6e3ba66277d435056f2b8dca"
source = "git+https://github.com/astral-sh/RustPython-Parser.git?rev=f60e204b73b95bdb6ce87ccd0de34081b4a17c11#f60e204b73b95bdb6ce87ccd0de34081b4a17c11"
dependencies = [
"is-macro",
"num-bigint",
@@ -2194,7 +2194,7 @@ dependencies = [
[[package]]
name = "rustpython-format"
version = "0.2.0"
source = "git+https://github.com/astral-sh/RustPython-Parser.git?rev=08ebbe40d7776cac6e3ba66277d435056f2b8dca#08ebbe40d7776cac6e3ba66277d435056f2b8dca"
source = "git+https://github.com/astral-sh/RustPython-Parser.git?rev=f60e204b73b95bdb6ce87ccd0de34081b4a17c11#f60e204b73b95bdb6ce87ccd0de34081b4a17c11"
dependencies = [
"bitflags 2.3.1",
"itertools",
@@ -2206,7 +2206,7 @@ dependencies = [
[[package]]
name = "rustpython-literal"
version = "0.2.0"
source = "git+https://github.com/astral-sh/RustPython-Parser.git?rev=08ebbe40d7776cac6e3ba66277d435056f2b8dca#08ebbe40d7776cac6e3ba66277d435056f2b8dca"
source = "git+https://github.com/astral-sh/RustPython-Parser.git?rev=f60e204b73b95bdb6ce87ccd0de34081b4a17c11#f60e204b73b95bdb6ce87ccd0de34081b4a17c11"
dependencies = [
"hexf-parse",
"is-macro",
@@ -2218,7 +2218,7 @@ dependencies = [
[[package]]
name = "rustpython-parser"
version = "0.2.0"
source = "git+https://github.com/astral-sh/RustPython-Parser.git?rev=08ebbe40d7776cac6e3ba66277d435056f2b8dca#08ebbe40d7776cac6e3ba66277d435056f2b8dca"
source = "git+https://github.com/astral-sh/RustPython-Parser.git?rev=f60e204b73b95bdb6ce87ccd0de34081b4a17c11#f60e204b73b95bdb6ce87ccd0de34081b4a17c11"
dependencies = [
"anyhow",
"is-macro",
@@ -2241,7 +2241,7 @@ dependencies = [
[[package]]
name = "rustpython-parser-core"
version = "0.2.0"
source = "git+https://github.com/astral-sh/RustPython-Parser.git?rev=08ebbe40d7776cac6e3ba66277d435056f2b8dca#08ebbe40d7776cac6e3ba66277d435056f2b8dca"
source = "git+https://github.com/astral-sh/RustPython-Parser.git?rev=f60e204b73b95bdb6ce87ccd0de34081b4a17c11#f60e204b73b95bdb6ce87ccd0de34081b4a17c11"
dependencies = [
"is-macro",
"memchr",

View File

@@ -50,15 +50,15 @@ toml = { version = "0.7.2" }
# v0.0.1
libcst = { git = "https://github.com/charliermarsh/LibCST", rev = "80e4c1399f95e5beb532fdd1e209ad2dbb470438" }
# v0.0.3
ruff_text_size = { git = "https://github.com/astral-sh/RustPython-Parser.git", rev = "08ebbe40d7776cac6e3ba66277d435056f2b8dca" }
ruff_text_size = { git = "https://github.com/astral-sh/RustPython-Parser.git", rev = "f60e204b73b95bdb6ce87ccd0de34081b4a17c11" }
# v0.0.3
rustpython-ast = { git = "https://github.com/astral-sh/RustPython-Parser.git", rev = "08ebbe40d7776cac6e3ba66277d435056f2b8dca" , default-features = false, features = ["all-nodes-with-ranges", "num-bigint"]}
rustpython-ast = { git = "https://github.com/astral-sh/RustPython-Parser.git", rev = "f60e204b73b95bdb6ce87ccd0de34081b4a17c11" , default-features = false, features = ["all-nodes-with-ranges", "num-bigint"]}
# v0.0.3
rustpython-format = { git = "https://github.com/astral-sh/RustPython-Parser.git", rev = "08ebbe40d7776cac6e3ba66277d435056f2b8dca", default-features = false, features = ["num-bigint"] }
rustpython-format = { git = "https://github.com/astral-sh/RustPython-Parser.git", rev = "f60e204b73b95bdb6ce87ccd0de34081b4a17c11", default-features = false, features = ["num-bigint"] }
# v0.0.3
rustpython-literal = { git = "https://github.com/astral-sh/RustPython-Parser.git", rev = "08ebbe40d7776cac6e3ba66277d435056f2b8dca", default-features = false }
rustpython-literal = { git = "https://github.com/astral-sh/RustPython-Parser.git", rev = "f60e204b73b95bdb6ce87ccd0de34081b4a17c11", default-features = false }
# v0.0.3
rustpython-parser = { git = "https://github.com/astral-sh/RustPython-Parser.git", rev = "08ebbe40d7776cac6e3ba66277d435056f2b8dca" , default-features = false, features = ["full-lexer", "all-nodes-with-ranges", "num-bigint"] }
rustpython-parser = { git = "https://github.com/astral-sh/RustPython-Parser.git", rev = "f60e204b73b95bdb6ce87ccd0de34081b4a17c11" , default-features = false, features = ["full-lexer", "all-nodes-with-ranges", "num-bigint"] }
[profile.release]
lto = "fat"

View File

@@ -14,9 +14,9 @@ An extremely fast Python linter, written in Rust.
<p align="center">
<picture align="center">
<source media="(prefers-color-scheme: dark)" srcset="https://user-images.githubusercontent.com/1309177/212613422-7faaf278-706b-4294-ad92-236ffcab3430.svg">
<source media="(prefers-color-scheme: light)" srcset="https://user-images.githubusercontent.com/1309177/212613257-5f4bca12-6d6b-4c79-9bac-51a4c6d08928.svg">
<img alt="Shows a bar chart with benchmark results." src="https://user-images.githubusercontent.com/1309177/212613257-5f4bca12-6d6b-4c79-9bac-51a4c6d08928.svg">
<source media="(prefers-color-scheme: dark)" srcset="https://user-images.githubusercontent.com/1309177/232603514-c95e9b0f-6b31-43de-9a80-9e844173fd6a.svg">
<source media="(prefers-color-scheme: light)" srcset="https://user-images.githubusercontent.com/1309177/232603516-4fb4892d-585c-4b20-b810-3db9161831e4.svg">
<img alt="Shows a bar chart with benchmark results." src="https://user-images.githubusercontent.com/1309177/232603516-4fb4892d-585c-4b20-b810-3db9161831e4.svg">
</picture>
</p>
@@ -139,7 +139,7 @@ Ruff can also be used as a [pre-commit](https://pre-commit.com) hook:
```yaml
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.0.274
rev: v0.0.275
hooks:
- id: ruff
```

View File

@@ -1,6 +1,6 @@
[package]
name = "flake8-to-ruff"
version = "0.0.274"
version = "0.0.275"
description = """
Convert Flake8 configuration files to Ruff configuration files.
"""

View File

@@ -1,6 +1,6 @@
[package]
name = "ruff"
version = "0.0.274"
version = "0.0.275"
publish = false
authors = { workspace = true }
edition = { workspace = true }

View File

@@ -1,6 +1,12 @@
# T002 - accepted
# TODO (evanrittenhouse): this has an author
# TODO(evanrittenhouse): this also has an author
# TODO(evanrittenhouse): this has an author
# TODO (evanrittenhouse) and more: this has an author
# TODO(evanrittenhouse) and more: this has an author
# TODO@mayrholu: this has an author
# TODO @mayrholu: this has an author
# TODO@mayrholu and more: this has an author
# TODO @mayrholu and more: this has an author
# T002 - errors
# TODO: this has no author
# FIXME: neither does this

View File

@@ -1,4 +1,4 @@
from abc import ABCMeta
import abc
import pydantic
@@ -19,6 +19,10 @@ class Class:
def class_method(cls):
pass
@abc.abstractclassmethod
def abstract_class_method(cls):
pass
@staticmethod
def static_method(x):
return x
@@ -41,7 +45,7 @@ class Class:
...
class MetaClass(ABCMeta):
class MetaClass(abc.ABCMeta):
def bad_method(self):
pass

View File

@@ -1,4 +1,4 @@
from abc import ABCMeta
import abc
import pydantic
@@ -34,6 +34,23 @@ class Class:
def stillBad(cls, my_field: str) -> str:
pass
@classmethod
def badAllowed(cls):
pass
@classmethod
def stillBad(cls):
pass
@abc.abstractclassmethod
def badAllowed(cls):
pass
@abc.abstractclassmethod
def stillBad(cls):
pass
class PosOnlyClass:
def badAllowed(this, blah, /, self, something: str):
pass

View File

@@ -0,0 +1,52 @@
foo_tuple = (1, 2, 3)
foo_list = [1, 2, 3]
foo_set = {1, 2, 3}
foo_dict = {1: 2, 3: 4}
foo_int = 123
for i in list(foo_tuple): # PERF101
pass
for i in list(foo_list): # PERF101
pass
for i in list(foo_set): # PERF101
pass
for i in list((1, 2, 3)): # PERF101
pass
for i in list([1, 2, 3]): # PERF101
pass
for i in list({1, 2, 3}): # PERF101
pass
for i in list(
{
1,
2,
3,
}
):
pass
for i in list( # Comment
{1, 2, 3}
): # PERF101
pass
for i in list(foo_dict): # Ok
pass
for i in list(1): # Ok
pass
for i in list(foo_int): # Ok
pass
import itertools
for i in itertools.product(foo_int): # Ok
pass

View File

@@ -37,7 +37,10 @@ f"{{test}}"
f'{{ 40 }}'
f"{{a {{x}}"
f"{{{{x}}}}"
""f""
''f""
(""f""r"")
# To be fixed
# Error: f-string: single '}' is not allowed at line 41 column 8
# f"\{{x}}"
# f"\{{x}}"

View File

@@ -48,3 +48,12 @@ if True: from collections import (
# OK
from a import b
# Ok: `typing_extensions` contains backported improvements.
from typing_extensions import SupportsIndex
# Ok: `typing_extensions` contains backported improvements.
from typing_extensions import NamedTuple
# Ok: `typing_extensions` supports `frozen_default` (backported from 3.12).
from typing_extensions import dataclass_transform

View File

@@ -1,23 +1,14 @@
import typing
from typing import ClassVar, Sequence, Final
KNOWINGLY_MUTABLE_DEFAULT = []
class A:
mutable_default: list[int] = []
immutable_annotation: typing.Sequence[int] = []
without_annotation = []
correct_code: list[int] = KNOWINGLY_MUTABLE_DEFAULT
class_variable: typing.ClassVar[list[int]] = []
final_variable: typing.Final[list[int]] = []
__slots__ = {
"mutable_default": "A mutable default value",
}
class B:
mutable_default: list[int] = []
immutable_annotation: Sequence[int] = []
without_annotation = []
correct_code: list[int] = KNOWINGLY_MUTABLE_DEFAULT
class_variable: ClassVar[list[int]] = []
final_variable: Final[list[int]] = []
@@ -30,7 +21,6 @@ class C:
mutable_default: list[int] = []
immutable_annotation: Sequence[int] = []
without_annotation = []
correct_code: list[int] = KNOWINGLY_MUTABLE_DEFAULT
perfectly_fine: list[int] = field(default_factory=list)
class_variable: ClassVar[list[int]] = []
final_variable: Final[list[int]] = []
@@ -43,7 +33,5 @@ class D(BaseModel):
mutable_default: list[int] = []
immutable_annotation: Sequence[int] = []
without_annotation = []
correct_code: list[int] = KNOWINGLY_MUTABLE_DEFAULT
perfectly_fine: list[int] = field(default_factory=list)
class_variable: ClassVar[list[int]] = []
final_variable: Final[list[int]] = []

View File

@@ -1481,6 +1481,9 @@ where
if self.enabled(Rule::IncorrectDictIterator) {
perflint::rules::incorrect_dict_iterator(self, target, iter);
}
if self.enabled(Rule::UnnecessaryListCast) {
perflint::rules::unnecessary_list_cast(self, iter);
}
}
Stmt::Try(ast::StmtTry {
body,

View File

@@ -784,6 +784,7 @@ pub fn code_to_rule(linter: Linter, code: &str) -> Option<(RuleGroup, Rule)> {
(Airflow, "001") => (RuleGroup::Unspecified, rules::airflow::rules::AirflowVariableNameTaskIdMismatch),
// perflint
(Perflint, "101") => (RuleGroup::Unspecified, rules::perflint::rules::UnnecessaryListCast),
(Perflint, "102") => (RuleGroup::Unspecified, rules::perflint::rules::IncorrectDictIterator),
// flake8-fixme

View File

@@ -445,7 +445,7 @@ impl Notebook {
}
#[cfg(test)]
mod test {
mod tests {
use std::path::Path;
use anyhow::Result;

View File

@@ -1,4 +1,4 @@
use rustpython_parser::ast::{self, Expr, Stmt};
use rustpython_parser::ast::{self, Stmt};
use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};
@@ -50,9 +50,9 @@ pub(crate) fn f_string_docstring(checker: &mut Checker, body: &[Stmt]) {
let Stmt::Expr(ast::StmtExpr { value, range: _ }) = stmt else {
return;
};
let Expr::JoinedStr ( _) = value.as_ref() else {
if !value.is_joined_str_expr() {
return;
};
}
checker
.diagnostics
.push(Diagnostic::new(FStringDocstring, stmt.identifier()));

View File

@@ -6,7 +6,7 @@ use ruff_macros::{derive_message_formats, violation};
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for usages of comparators other than `<` and `>=` for
/// Checks for uses of comparators other than `<` and `>=` for
/// `sys.version_info` checks in `.pyi` files. All other comparators, such
/// as `>`, `<=`, and `==`, are banned.
///

View File

@@ -7,7 +7,7 @@ use ruff_python_semantic::SemanticModel;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for usages of the builtin `open()` function without an associated context
/// Checks for uses of the builtin `open()` function without an associated context
/// manager.
///
/// ## Why is this bad?

View File

@@ -67,7 +67,7 @@ pub struct MissingTodoAuthor;
impl Violation for MissingTodoAuthor {
#[derive_message_formats]
fn message(&self) -> String {
format!("Missing author in TODO; try: `# TODO(<author_name>): ...`")
format!("Missing author in TODO; try: `# TODO(<author_name>): ...` or `# TODO @<author_name>: ...`")
}
}
@@ -229,7 +229,7 @@ static ISSUE_LINK_REGEX_SET: Lazy<RegexSet> = Lazy::new(|| {
RegexSet::new([
r#"^#\s*(http|https)://.*"#, // issue link
r#"^#\s*\d+$"#, // issue code - like "003"
r#"^#\s*[A-Z]{1,6}\-?\d+$"#, // issue code - like "TD003" or "TD-003"
r#"^#\s*[A-Z]{1,6}\-?\d+$"#, // issue code - like "TD003"
])
.unwrap()
});
@@ -339,8 +339,7 @@ fn directive_errors(
}
}
/// Checks for "static" errors in the comment: missing colon, missing author, etc. This function
/// modifies `diagnostics` in-place.
/// Checks for "static" errors in the comment: missing colon, missing author, etc.
fn static_errors(
diagnostics: &mut Vec<Diagnostic>,
comment: &str,
@@ -358,6 +357,15 @@ fn static_errors(
} else {
trimmed.text_len()
}
} else if trimmed.starts_with('@') {
if let Some(end_index) = trimmed.find(|c: char| c.is_whitespace() || c == ':') {
TextSize::try_from(end_index).unwrap()
} else {
// TD002
diagnostics.push(Diagnostic::new(MissingTodoAuthor, directive.range));
TextSize::new(0)
}
} else {
// TD002
diagnostics.push(Diagnostic::new(MissingTodoAuthor, directive.range));

View File

@@ -1,41 +1,41 @@
---
source: crates/ruff/src/rules/flake8_todos/mod.rs
---
TD002.py:5:3: TD002 Missing author in TODO; try: `# TODO(<author_name>): ...`
|
3 | # TODO(evanrittenhouse): this also has an author
4 | # T002 - errors
5 | # TODO: this has no author
| ^^^^ TD002
6 | # FIXME: neither does this
7 | # TODO : and neither does this
|
TD002.py:11:3: TD002 Missing author in TODO; try: `# TODO(<author_name>): ...` or `# TODO @<author_name>: ...`
|
9 | # TODO @mayrholu and more: this has an author
10 | # T002 - errors
11 | # TODO: this has no author
| ^^^^ TD002
12 | # FIXME: neither does this
13 | # TODO : and neither does this
|
TD002.py:6:3: TD002 Missing author in TODO; try: `# TODO(<author_name>): ...`
|
4 | # T002 - errors
5 | # TODO: this has no author
6 | # FIXME: neither does this
| ^^^^^ TD002
7 | # TODO : and neither does this
8 | # foo # TODO: this doesn't either
|
TD002.py:12:3: TD002 Missing author in TODO; try: `# TODO(<author_name>): ...` or `# TODO @<author_name>: ...`
|
10 | # T002 - errors
11 | # TODO: this has no author
12 | # FIXME: neither does this
| ^^^^^ TD002
13 | # TODO : and neither does this
14 | # foo # TODO: this doesn't either
|
TD002.py:7:3: TD002 Missing author in TODO; try: `# TODO(<author_name>): ...`
|
5 | # TODO: this has no author
6 | # FIXME: neither does this
7 | # TODO : and neither does this
| ^^^^ TD002
8 | # foo # TODO: this doesn't either
|
TD002.py:13:3: TD002 Missing author in TODO; try: `# TODO(<author_name>): ...` or `# TODO @<author_name>: ...`
|
11 | # TODO: this has no author
12 | # FIXME: neither does this
13 | # TODO : and neither does this
| ^^^^ TD002
14 | # foo # TODO: this doesn't either
|
TD002.py:8:9: TD002 Missing author in TODO; try: `# TODO(<author_name>): ...`
|
6 | # FIXME: neither does this
7 | # TODO : and neither does this
8 | # foo # TODO: this doesn't either
| ^^^^ TD002
|
TD002.py:14:9: TD002 Missing author in TODO; try: `# TODO(<author_name>): ...` or `# TODO @<author_name>: ...`
|
12 | # FIXME: neither does this
13 | # TODO : and neither does this
14 | # foo # TODO: this doesn't either
| ^^^^ TD002
|

View File

@@ -18,29 +18,29 @@ N805.py:12:30: N805 First argument of a method should be named `self`
13 | pass
|
N805.py:27:15: N805 First argument of a method should be named `self`
|
26 | @pydantic.validator
27 | def lower(cls, my_field: str) -> str:
| ^^^ N805
28 | pass
|
N805.py:31:15: N805 First argument of a method should be named `self`
|
30 | @pydantic.validator("my_field")
30 | @pydantic.validator
31 | def lower(cls, my_field: str) -> str:
| ^^^ N805
32 | pass
|
N805.py:60:29: N805 First argument of a method should be named `self`
N805.py:35:15: N805 First argument of a method should be named `self`
|
58 | pass
59 |
60 | def bad_method_pos_only(this, blah, /, self, something: str):
34 | @pydantic.validator("my_field")
35 | def lower(cls, my_field: str) -> str:
| ^^^ N805
36 | pass
|
N805.py:64:29: N805 First argument of a method should be named `self`
|
62 | pass
63 |
64 | def bad_method_pos_only(this, blah, /, self, something: str):
| ^^^^ N805
61 | pass
65 | pass
|

View File

@@ -18,13 +18,13 @@ N805.py:12:30: N805 First argument of a method should be named `self`
13 | pass
|
N805.py:60:29: N805 First argument of a method should be named `self`
N805.py:64:29: N805 First argument of a method should be named `self`
|
58 | pass
59 |
60 | def bad_method_pos_only(this, blah, /, self, something: str):
62 | pass
63 |
64 | def bad_method_pos_only(this, blah, /, self, something: str):
| ^^^^ N805
61 | pass
65 | pass
|

View File

@@ -35,13 +35,13 @@ N805.py:34:18: N805 First argument of a method should be named `self`
35 | pass
|
N805.py:41:18: N805 First argument of a method should be named `self`
N805.py:58:18: N805 First argument of a method should be named `self`
|
39 | pass
40 |
41 | def stillBad(this, blah, /, self, something: str):
56 | pass
57 |
58 | def stillBad(this, blah, /, self, something: str):
| ^^^^ N805
42 | pass
59 | pass
|

View File

@@ -13,6 +13,7 @@ mod tests {
use crate::settings::Settings;
use crate::test::test_path;
#[test_case(Rule::UnnecessaryListCast, Path::new("PERF101.py"))]
#[test_case(Rule::IncorrectDictIterator, Path::new("PERF102.py"))]
fn rules(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", rule_code.noqa_code(), path.to_string_lossy());

View File

@@ -1,3 +1,5 @@
pub(crate) use incorrect_dict_iterator::{incorrect_dict_iterator, IncorrectDictIterator};
pub(crate) use incorrect_dict_iterator::*;
pub(crate) use unnecessary_list_cast::*;
mod incorrect_dict_iterator;
mod unnecessary_list_cast;

View File

@@ -0,0 +1,129 @@
use ruff_text_size::TextRange;
use rustpython_parser::ast::{self, Expr};
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::prelude::Stmt;
use crate::checkers::ast::Checker;
use crate::registry::AsRule;
/// ## What it does
/// Checks for explicit casts to `list` on for-loop iterables.
///
/// ## Why is this bad?
/// Using a `list()` call to eagerly iterate over an already-iterable type
/// (like a tuple, list, or set) is inefficient, as it forces Python to create
/// a new list unnecessarily.
///
/// Removing the `list()` call will not change the behavior of the code, but
/// may improve performance.
///
/// ## Example
/// ```python
/// items = (1, 2, 3)
/// for i in list(items):
/// print(i)
/// ```
///
/// Use instead:
/// ```python
/// items = (1, 2, 3)
/// for i in items:
/// print(i)
/// ```
#[violation]
pub struct UnnecessaryListCast;
impl AlwaysAutofixableViolation for UnnecessaryListCast {
#[derive_message_formats]
fn message(&self) -> String {
format!("Do not cast an iterable to `list` before iterating over it")
}
fn autofix_title(&self) -> String {
format!("Remove `list()` cast")
}
}
/// PERF101
pub(crate) fn unnecessary_list_cast(checker: &mut Checker, iter: &Expr) {
let Expr::Call(ast::ExprCall{ func, args, range: list_range, ..}) = iter else {
return;
};
if args.len() != 1 {
return;
}
let Expr::Name(ast::ExprName { id, .. }) = func.as_ref() else{
return;
};
if !(id == "list" && checker.semantic().is_builtin("list")) {
return;
}
match &args[0] {
Expr::Tuple(ast::ExprTuple {
range: iterable_range,
..
})
| Expr::List(ast::ExprList {
range: iterable_range,
..
})
| Expr::Set(ast::ExprSet {
range: iterable_range,
..
}) => {
let mut diagnostic = Diagnostic::new(UnnecessaryListCast, *list_range);
if checker.patch(diagnostic.kind.rule()) {
diagnostic.set_fix(remove_cast(*list_range, *iterable_range));
}
checker.diagnostics.push(diagnostic);
}
Expr::Name(ast::ExprName {
id,
range: iterable_range,
..
}) => {
let scope = checker.semantic().scope();
if let Some(binding_id) = scope.get(id) {
let binding = checker.semantic().binding(binding_id);
if binding.kind.is_assignment() || binding.kind.is_named_expr_assignment() {
if let Some(parent_id) = binding.source {
let parent = checker.semantic().stmts[parent_id];
if let Stmt::Assign(ast::StmtAssign { value, .. })
| Stmt::AnnAssign(ast::StmtAnnAssign {
value: Some(value), ..
})
| Stmt::AugAssign(ast::StmtAugAssign { value, .. }) = parent
{
if matches!(
value.as_ref(),
Expr::Tuple(_) | Expr::List(_) | Expr::Set(_)
) {
let mut diagnostic =
Diagnostic::new(UnnecessaryListCast, *list_range);
if checker.patch(diagnostic.kind.rule()) {
diagnostic.set_fix(remove_cast(*list_range, *iterable_range));
}
checker.diagnostics.push(diagnostic);
}
}
}
}
}
}
_ => {}
}
}
/// Generate a [`Fix`] to remove a `list` cast from an expression.
fn remove_cast(list_range: TextRange, iterable_range: TextRange) -> Fix {
Fix::automatic_edits(
Edit::deletion(list_range.start(), iterable_range.start()),
[Edit::deletion(iterable_range.end(), list_range.end())],
)
}

View File

@@ -0,0 +1,183 @@
---
source: crates/ruff/src/rules/perflint/mod.rs
---
PERF101.py:7:10: PERF101 [*] Do not cast an iterable to `list` before iterating over it
|
5 | foo_int = 123
6 |
7 | for i in list(foo_tuple): # PERF101
| ^^^^^^^^^^^^^^^ PERF101
8 | pass
|
= help: Remove `list()` cast
Fix
4 4 | foo_dict = {1: 2, 3: 4}
5 5 | foo_int = 123
6 6 |
7 |-for i in list(foo_tuple): # PERF101
7 |+for i in foo_tuple: # PERF101
8 8 | pass
9 9 |
10 10 | for i in list(foo_list): # PERF101
PERF101.py:10:10: PERF101 [*] Do not cast an iterable to `list` before iterating over it
|
8 | pass
9 |
10 | for i in list(foo_list): # PERF101
| ^^^^^^^^^^^^^^ PERF101
11 | pass
|
= help: Remove `list()` cast
Fix
7 7 | for i in list(foo_tuple): # PERF101
8 8 | pass
9 9 |
10 |-for i in list(foo_list): # PERF101
10 |+for i in foo_list: # PERF101
11 11 | pass
12 12 |
13 13 | for i in list(foo_set): # PERF101
PERF101.py:13:10: PERF101 [*] Do not cast an iterable to `list` before iterating over it
|
11 | pass
12 |
13 | for i in list(foo_set): # PERF101
| ^^^^^^^^^^^^^ PERF101
14 | pass
|
= help: Remove `list()` cast
Fix
10 10 | for i in list(foo_list): # PERF101
11 11 | pass
12 12 |
13 |-for i in list(foo_set): # PERF101
13 |+for i in foo_set: # PERF101
14 14 | pass
15 15 |
16 16 | for i in list((1, 2, 3)): # PERF101
PERF101.py:16:10: PERF101 [*] Do not cast an iterable to `list` before iterating over it
|
14 | pass
15 |
16 | for i in list((1, 2, 3)): # PERF101
| ^^^^^^^^^^^^^^^ PERF101
17 | pass
|
= help: Remove `list()` cast
Fix
13 13 | for i in list(foo_set): # PERF101
14 14 | pass
15 15 |
16 |-for i in list((1, 2, 3)): # PERF101
16 |+for i in (1, 2, 3): # PERF101
17 17 | pass
18 18 |
19 19 | for i in list([1, 2, 3]): # PERF101
PERF101.py:19:10: PERF101 [*] Do not cast an iterable to `list` before iterating over it
|
17 | pass
18 |
19 | for i in list([1, 2, 3]): # PERF101
| ^^^^^^^^^^^^^^^ PERF101
20 | pass
|
= help: Remove `list()` cast
Fix
16 16 | for i in list((1, 2, 3)): # PERF101
17 17 | pass
18 18 |
19 |-for i in list([1, 2, 3]): # PERF101
19 |+for i in [1, 2, 3]: # PERF101
20 20 | pass
21 21 |
22 22 | for i in list({1, 2, 3}): # PERF101
PERF101.py:22:10: PERF101 [*] Do not cast an iterable to `list` before iterating over it
|
20 | pass
21 |
22 | for i in list({1, 2, 3}): # PERF101
| ^^^^^^^^^^^^^^^ PERF101
23 | pass
|
= help: Remove `list()` cast
Fix
19 19 | for i in list([1, 2, 3]): # PERF101
20 20 | pass
21 21 |
22 |-for i in list({1, 2, 3}): # PERF101
22 |+for i in {1, 2, 3}: # PERF101
23 23 | pass
24 24 |
25 25 | for i in list(
PERF101.py:25:10: PERF101 [*] Do not cast an iterable to `list` before iterating over it
|
23 | pass
24 |
25 | for i in list(
| __________^
26 | | {
27 | | 1,
28 | | 2,
29 | | 3,
30 | | }
31 | | ):
| |_^ PERF101
32 | pass
|
= help: Remove `list()` cast
Fix
22 22 | for i in list({1, 2, 3}): # PERF101
23 23 | pass
24 24 |
25 |-for i in list(
26 |- {
25 |+for i in {
27 26 | 1,
28 27 | 2,
29 28 | 3,
30 |- }
31 |-):
29 |+ }:
32 30 | pass
33 31 |
34 32 | for i in list( # Comment
PERF101.py:34:10: PERF101 [*] Do not cast an iterable to `list` before iterating over it
|
32 | pass
33 |
34 | for i in list( # Comment
| __________^
35 | | {1, 2, 3}
36 | | ): # PERF101
| |_^ PERF101
37 | pass
|
= help: Remove `list()` cast
Fix
31 31 | ):
32 32 | pass
33 33 |
34 |-for i in list( # Comment
35 |- {1, 2, 3}
36 |-): # PERF101
34 |+for i in {1, 2, 3}: # PERF101
37 35 | pass
38 36 |
39 37 | for i in list(foo_dict): # Ok

View File

@@ -108,8 +108,7 @@ pub(crate) fn invalid_escape_sequence(
let range = TextRange::at(location, next_char.text_len() + TextSize::from(1));
let mut diagnostic = Diagnostic::new(InvalidEscapeSequence(*next_char), range);
if autofix {
#[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::insertion(
diagnostic.set_fix(Fix::automatic(Edit::insertion(
r"\".to_string(),
range.start() + TextSize::from(1),
)));

View File

@@ -92,8 +92,7 @@ pub(crate) fn missing_whitespace(
let mut diagnostic = Diagnostic::new(kind, token.range());
if autofix {
#[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::insertion(
diagnostic.set_fix(Fix::automatic(Edit::insertion(
" ".to_string(),
token.end(),
)));

View File

@@ -65,8 +65,7 @@ pub(crate) fn whitespace_before_parameters(
let mut diagnostic = Diagnostic::new(kind, TextRange::new(start, end));
if autofix {
#[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::deletion(start, end)));
diagnostic.set_fix(Fix::automatic(Edit::deletion(start, end)));
}
context.push_diagnostic(diagnostic);
}

View File

@@ -55,8 +55,7 @@ pub(crate) fn no_newline_at_end_of_file(
let mut diagnostic = Diagnostic::new(MissingNewlineAtEndOfFile, range);
if autofix {
#[allow(deprecated)]
diagnostic.set_fix(Fix::unspecified(Edit::insertion(
diagnostic.set_fix(Fix::automatic(Edit::insertion(
stylist.line_ending().to_string(),
range.start(),
)));

View File

@@ -11,7 +11,7 @@ E21.py:2:5: E211 [*] Whitespace before '('
|
= help: Removed whitespace before '('
Suggested fix
Fix
1 1 | #: E211
2 |-spam (1)
2 |+spam(1)
@@ -30,7 +30,7 @@ E21.py:4:5: E211 [*] Whitespace before '['
|
= help: Removed whitespace before '['
Suggested fix
Fix
1 1 | #: E211
2 2 | spam (1)
3 3 | #: E211 E211
@@ -51,7 +51,7 @@ E21.py:4:20: E211 [*] Whitespace before '['
|
= help: Removed whitespace before '['
Suggested fix
Fix
1 1 | #: E211
2 2 | spam (1)
3 3 | #: E211 E211
@@ -72,7 +72,7 @@ E21.py:6:12: E211 [*] Whitespace before '['
|
= help: Removed whitespace before '['
Suggested fix
Fix
3 3 | #: E211 E211
4 4 | dict ['key'] = list [index]
5 5 | #: E211

View File

@@ -11,7 +11,7 @@ E23.py:2:7: E231 [*] Missing whitespace after ','
|
= help: Added missing whitespace after ','
Suggested fix
Fix
1 1 | #: E231
2 |-a = (1,2)
2 |+a = (1, 2)
@@ -30,7 +30,7 @@ E23.py:4:5: E231 [*] Missing whitespace after ','
|
= help: Added missing whitespace after ','
Suggested fix
Fix
1 1 | #: E231
2 2 | a = (1,2)
3 3 | #: E231
@@ -51,7 +51,7 @@ E23.py:6:10: E231 [*] Missing whitespace after ':'
|
= help: Added missing whitespace after ':'
Suggested fix
Fix
3 3 | #: E231
4 4 | a[b1,:]
5 5 | #: E231
@@ -71,7 +71,7 @@ E23.py:19:10: E231 [*] Missing whitespace after ','
|
= help: Added missing whitespace after ','
Suggested fix
Fix
16 16 |
17 17 | def foo() -> None:
18 18 | #: E231
@@ -91,7 +91,7 @@ E23.py:29:20: E231 [*] Missing whitespace after ':'
|
= help: Added missing whitespace after ':'
Suggested fix
Fix
26 26 | #: E231:2:20
27 27 | mdtypes_template = {
28 28 | 'tag_full': [('mdtype', 'u4'), ('byte_count', 'u4')],

View File

@@ -9,7 +9,7 @@ W292_0.py:2:9: W292 [*] No newline at end of file
|
= help: Add trailing newline
Suggested fix
Fix
1 1 | def fn() -> None:
2 |- pass
2 |+ pass

View File

@@ -11,7 +11,7 @@ W605_0.py:2:10: W605 [*] Invalid escape sequence: `\.`
|
= help: Add backslash to escape sequence
Suggested fix
Fix
1 1 | #: W605:1:10
2 |-regex = '\.png$'
2 |+regex = '\\.png$'
@@ -29,7 +29,7 @@ W605_0.py:6:1: W605 [*] Invalid escape sequence: `\.`
|
= help: Add backslash to escape sequence
Suggested fix
Fix
3 3 |
4 4 | #: W605:2:1
5 5 | regex = '''
@@ -49,7 +49,7 @@ W605_0.py:11:6: W605 [*] Invalid escape sequence: `\_`
|
= help: Add backslash to escape sequence
Suggested fix
Fix
8 8 |
9 9 | #: W605:2:6
10 10 | f(
@@ -70,7 +70,7 @@ W605_0.py:18:6: W605 [*] Invalid escape sequence: `\_`
|
= help: Add backslash to escape sequence
Suggested fix
Fix
15 15 | """
16 16 | multi-line
17 17 | literal

View File

@@ -11,7 +11,7 @@ W605_1.py:2:10: W605 [*] Invalid escape sequence: `\.`
|
= help: Add backslash to escape sequence
Suggested fix
Fix
1 1 | #: W605:1:10
2 |-regex = '\.png$'
2 |+regex = '\\.png$'
@@ -29,7 +29,7 @@ W605_1.py:6:1: W605 [*] Invalid escape sequence: `\.`
|
= help: Add backslash to escape sequence
Suggested fix
Fix
3 3 |
4 4 | #: W605:2:1
5 5 | regex = '''
@@ -49,7 +49,7 @@ W605_1.py:11:6: W605 [*] Invalid escape sequence: `\_`
|
= help: Add backslash to escape sequence
Suggested fix
Fix
8 8 |
9 9 | #: W605:2:6
10 10 | f(
@@ -70,7 +70,7 @@ W605_1.py:18:6: W605 [*] Invalid escape sequence: `\_`
|
= help: Add backslash to escape sequence
Suggested fix
Fix
15 15 | """
16 16 | multi-line
17 17 | literal

View File

@@ -8,7 +8,7 @@ W292_4.py:1:2: W292 [*] No newline at end of file
|
= help: Add trailing newline
Suggested fix
Fix
1 |-
1 |+

View File

@@ -79,23 +79,6 @@ fn find_useless_f_strings<'a>(
})
}
fn unescape_f_string(content: &str) -> String {
content.replace("{{", "{").replace("}}", "}")
}
fn fix_f_string_missing_placeholders(
prefix_range: TextRange,
tok_range: TextRange,
checker: &mut Checker,
) -> Fix {
let content = &checker.locator.contents()[TextRange::new(prefix_range.end(), tok_range.end())];
Fix::automatic(Edit::replacement(
unescape_f_string(content),
prefix_range.start(),
tok_range.end(),
))
}
/// F541
pub(crate) fn f_string_missing_placeholders(expr: &Expr, values: &[Expr], checker: &mut Checker) {
if !values
@@ -105,13 +88,51 @@ pub(crate) fn f_string_missing_placeholders(expr: &Expr, values: &[Expr], checke
for (prefix_range, tok_range) in find_useless_f_strings(expr, checker.locator) {
let mut diagnostic = Diagnostic::new(FStringMissingPlaceholders, tok_range);
if checker.patch(diagnostic.kind.rule()) {
diagnostic.set_fix(fix_f_string_missing_placeholders(
diagnostic.set_fix(convert_f_string_to_regular_string(
prefix_range,
tok_range,
checker,
checker.locator,
));
}
checker.diagnostics.push(diagnostic);
}
}
}
/// Unescape an f-string body by replacing `{{` with `{` and `}}` with `}`.
///
/// In Python, curly-brace literals within f-strings must be escaped by doubling the braces.
/// When rewriting an f-string to a regular string, we need to unescape any curly-brace literals.
/// For example, given `{{Hello, world!}}`, return `{Hello, world!}`.
fn unescape_f_string(content: &str) -> String {
content.replace("{{", "{").replace("}}", "}")
}
/// Generate a [`Fix`] to rewrite an f-string as a regular string.
fn convert_f_string_to_regular_string(
prefix_range: TextRange,
tok_range: TextRange,
locator: &Locator,
) -> Fix {
// Extract the f-string body.
let mut content =
unescape_f_string(locator.slice(TextRange::new(prefix_range.end(), tok_range.end())));
// If the preceding character is equivalent to the quote character, insert a space to avoid a
// syntax error. For example, when removing the `f` prefix in `""f""`, rewrite to `"" ""`
// instead of `""""`.
if locator
.slice(TextRange::up_to(prefix_range.start()))
.chars()
.last()
.map_or(false, |char| content.starts_with(char))
{
content.insert(0, ' ');
}
Fix::automatic(Edit::replacement(
content,
prefix_range.start(),
tok_range.end(),
))
}

View File

@@ -269,7 +269,7 @@ F541.py:37:1: F541 [*] f-string without any placeholders
37 |+'{ 40 }'
38 38 | f"{{a {{x}}"
39 39 | f"{{{{x}}}}"
40 40 |
40 40 | ""f""
F541.py:38:1: F541 [*] f-string without any placeholders
|
@@ -278,6 +278,7 @@ F541.py:38:1: F541 [*] f-string without any placeholders
38 | f"{{a {{x}}"
| ^^^^^^^^^^^^ F541
39 | f"{{{{x}}}}"
40 | ""f""
|
= help: Remove extraneous `f` prefix
@@ -288,8 +289,8 @@ F541.py:38:1: F541 [*] f-string without any placeholders
38 |-f"{{a {{x}}"
38 |+"{a {x}"
39 39 | f"{{{{x}}}}"
40 40 |
41 41 | # To be fixed
40 40 | ""f""
41 41 | ''f""
F541.py:39:1: F541 [*] f-string without any placeholders
|
@@ -297,8 +298,8 @@ F541.py:39:1: F541 [*] f-string without any placeholders
38 | f"{{a {{x}}"
39 | f"{{{{x}}}}"
| ^^^^^^^^^^^^ F541
40 |
41 | # To be fixed
40 | ""f""
41 | ''f""
|
= help: Remove extraneous `f` prefix
@@ -308,8 +309,70 @@ F541.py:39:1: F541 [*] f-string without any placeholders
38 38 | f"{{a {{x}}"
39 |-f"{{{{x}}}}"
39 |+"{{x}}"
40 40 |
41 41 | # To be fixed
42 42 | # Error: f-string: single '}' is not allowed at line 41 column 8
40 40 | ""f""
41 41 | ''f""
42 42 | (""f""r"")
F541.py:40:3: F541 [*] f-string without any placeholders
|
38 | f"{{a {{x}}"
39 | f"{{{{x}}}}"
40 | ""f""
| ^^^ F541
41 | ''f""
42 | (""f""r"")
|
= help: Remove extraneous `f` prefix
Fix
37 37 | f'{{ 40 }}'
38 38 | f"{{a {{x}}"
39 39 | f"{{{{x}}}}"
40 |-""f""
40 |+"" ""
41 41 | ''f""
42 42 | (""f""r"")
43 43 |
F541.py:41:3: F541 [*] f-string without any placeholders
|
39 | f"{{{{x}}}}"
40 | ""f""
41 | ''f""
| ^^^ F541
42 | (""f""r"")
|
= help: Remove extraneous `f` prefix
Fix
38 38 | f"{{a {{x}}"
39 39 | f"{{{{x}}}}"
40 40 | ""f""
41 |-''f""
41 |+''""
42 42 | (""f""r"")
43 43 |
44 44 | # To be fixed
F541.py:42:4: F541 [*] f-string without any placeholders
|
40 | ""f""
41 | ''f""
42 | (""f""r"")
| ^^^ F541
43 |
44 | # To be fixed
|
= help: Remove extraneous `f` prefix
Fix
39 39 | f"{{{{x}}}}"
40 40 | ""f""
41 41 | ''f""
42 |-(""f""r"")
42 |+("" ""r"")
43 43 |
44 44 | # To be fixed
45 45 | # Error: f-string: single '}' is not allowed at line 41 column 8

View File

@@ -6,7 +6,7 @@ use ruff_macros::{derive_message_formats, violation};
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for usages of the builtin `eval()` function.
/// Checks for uses of the builtin `eval()` function.
///
/// ## Why is this bad?
/// The `eval()` function is insecure as it enables arbitrary code execution.

View File

@@ -6,7 +6,7 @@ use ruff_macros::{derive_message_formats, violation};
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for usages of `await` outside of `async` functions.
/// Checks for uses of `await` outside of `async` functions.
///
/// ## Why is this bad?
/// Using `await` outside of an `async` function is a syntax error.

View File

@@ -7,7 +7,7 @@ use ruff_python_ast::source_code::OneIndexed;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for usages of names that are declared as `global` prior to the
/// Checks for uses of names that are declared as `global` prior to the
/// relevant `global` declaration.
///
/// ## Why is this bad?

View File

@@ -6,7 +6,7 @@ use ruff_macros::{derive_message_formats, violation};
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for usages of named expressions (e.g., `a := 42`) that can be
/// Checks for uses of named expressions (e.g., `a := 42`) that can be
/// replaced by regular assignment statements (e.g., `a = 42`).
///
/// ## Why is this bad?

View File

@@ -126,7 +126,7 @@ pub(crate) fn remove_import_members(contents: &str, members: &[&str]) -> String
}
#[cfg(test)]
mod test {
mod tests {
use crate::rules::pyupgrade::fixes::remove_import_members;
#[test]

View File

@@ -43,6 +43,12 @@ enum Deprecation {
/// Deprecated imports may be removed in future versions of Python, and
/// should be replaced with their new equivalents.
///
/// Note that, in some cases, it may be preferable to continue importing
/// members from `typing_extensions` even after they're added to the Python
/// standard library, as `typing_extensions` can backport bugfixes and
/// optimizations from later Python versions. This rule thus avoids flagging
/// imports from `typing_extensions` in such cases.
///
/// ## Example
/// ```python
/// from collections import Sequence
@@ -139,10 +145,12 @@ const TYPING_EXTENSIONS_TO_TYPING: &[&str] = &[
"ContextManager",
"Coroutine",
"DefaultDict",
"NewType",
"TYPE_CHECKING",
"Text",
"Type",
// Introduced in Python 3.5.2, but `typing_extensions` contains backported bugfixes and
// optimizations,
// "NewType",
];
// Python 3.7+
@@ -168,11 +176,13 @@ const MYPY_EXTENSIONS_TO_TYPING_38: &[&str] = &["TypedDict"];
// Members of `typing_extensions` that were moved to `typing`.
const TYPING_EXTENSIONS_TO_TYPING_38: &[&str] = &[
"Final",
"Literal",
"OrderedDict",
"Protocol",
"SupportsIndex",
"runtime_checkable",
// Introduced in Python 3.8, but `typing_extensions` contains backported bugfixes and
// optimizations.
// "Literal",
// "Protocol",
// "SupportsIndex",
];
// Python 3.9+
@@ -243,6 +253,8 @@ const TYPING_TO_COLLECTIONS_ABC_310: &[&str] = &["Callable"];
// Members of `typing_extensions` that were moved to `typing`.
const TYPING_EXTENSIONS_TO_TYPING_310: &[&str] = &[
"Concatenate",
"Literal",
"NewType",
"ParamSpecArgs",
"ParamSpecKwargs",
"TypeAlias",
@@ -258,23 +270,28 @@ const TYPING_EXTENSIONS_TO_TYPING_310: &[&str] = &[
const TYPING_EXTENSIONS_TO_TYPING_311: &[&str] = &[
"Any",
"LiteralString",
"NamedTuple",
"Never",
"NotRequired",
"Required",
"Self",
"TypedDict",
"Unpack",
"assert_never",
"assert_type",
"clear_overloads",
"dataclass_transform",
"final",
"get_overloads",
"overload",
"reveal_type",
];
// Python 3.12+
// Members of `typing_extensions` that were moved to `typing`.
const TYPING_EXTENSIONS_TO_TYPING_312: &[&str] = &[
// Introduced in Python 3.11, but `typing_extensions` backports the `frozen_default` argument,
// which was introduced in Python 3.12.
"dataclass_transform",
];
struct ImportReplacer<'a> {
stmt: &'a Stmt,
module: &'a str,
@@ -359,6 +376,9 @@ impl<'a> ImportReplacer<'a> {
if self.version >= PythonVersion::Py311 {
typing_extensions_to_typing.extend(TYPING_EXTENSIONS_TO_TYPING_311);
}
if self.version >= PythonVersion::Py312 {
typing_extensions_to_typing.extend(TYPING_EXTENSIONS_TO_TYPING_312);
}
if let Some(operation) = self.try_replace(&typing_extensions_to_typing, "typing") {
operations.push(operation);
}

View File

@@ -477,7 +477,7 @@ pub(crate) fn printf_string_formatting(
}
#[cfg(test)]
mod test {
mod tests {
use test_case::test_case;
use super::*;

View File

@@ -8,11 +8,6 @@ use ruff_python_ast::helpers::has_comments;
use crate::checkers::ast::Checker;
use crate::registry::AsRule;
#[violation]
pub struct CollectionLiteralConcatenation {
expr: String,
}
/// ## What it does
/// Checks for uses of the `+` operator to concatenate collections.
///
@@ -43,6 +38,11 @@ pub struct CollectionLiteralConcatenation {
/// ## References
/// - [PEP 448 Additional Unpacking Generalizations](https://peps.python.org/pep-0448/)
/// - [Python docs: Sequence Types — `list`, `tuple`, `range`](https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range)
#[violation]
pub struct CollectionLiteralConcatenation {
expr: String,
}
impl Violation for CollectionLiteralConcatenation {
const AUTOFIX: AutofixKind = AutofixKind::Sometimes;

View File

@@ -3,6 +3,22 @@ use rustpython_parser::ast::{self, Expr};
use ruff_python_ast::helpers::map_callable;
use ruff_python_semantic::SemanticModel;
/// Return `true` if the given [`Expr`] is a special class attribute, like `__slots__`.
///
/// While `__slots__` is typically defined via a tuple, Python accepts any iterable and, in
/// particular, allows the use of a dictionary to define the attribute names (as keys) and
/// docstrings (as values).
pub(super) fn is_special_attribute(value: &Expr) -> bool {
if let Expr::Name(ast::ExprName { id, .. }) = value {
matches!(
id.as_str(),
"__slots__" | "__dict__" | "__weakref__" | "__annotations__"
)
} else {
false
}
}
/// Returns `true` if the given [`Expr`] is a `dataclasses.field` call.
pub(super) fn is_dataclass_field(func: &Expr, semantic: &SemanticModel) -> bool {
semantic.resolve_call_path(func).map_or(false, |call_path| {
@@ -37,11 +53,14 @@ pub(super) fn is_dataclass(class_def: &ast::StmtClassDef, semantic: &SemanticMod
})
}
/// Returns `true` if the given class is a Pydantic `BaseModel`.
/// Returns `true` if the given class is a Pydantic `BaseModel` or `BaseSettings` subclass.
pub(super) fn is_pydantic_model(class_def: &ast::StmtClassDef, semantic: &SemanticModel) -> bool {
class_def.bases.iter().any(|expr| {
semantic.resolve_call_path(expr).map_or(false, |call_path| {
matches!(call_path.as_slice(), ["pydantic", "BaseModel"])
matches!(
call_path.as_slice(),
["pydantic", "BaseModel" | "BaseSettings"]
)
})
})
}

View File

@@ -7,6 +7,7 @@ use ruff_python_semantic::analyze::typing::{is_immutable_annotation, is_mutable_
use crate::checkers::ast::Checker;
use crate::rules::ruff::rules::helpers::{
is_class_var_annotation, is_dataclass, is_final_annotation, is_pydantic_model,
is_special_attribute,
};
/// ## What it does
@@ -51,10 +52,12 @@ pub(crate) fn mutable_class_default(checker: &mut Checker, class_def: &ast::Stmt
match statement {
Stmt::AnnAssign(ast::StmtAnnAssign {
annotation,
target,
value: Some(value),
..
}) => {
if is_mutable_expr(value, checker.semantic())
if !is_special_attribute(target)
&& is_mutable_expr(value, checker.semantic())
&& !is_class_var_annotation(annotation, checker.semantic())
&& !is_final_annotation(annotation, checker.semantic())
&& !is_immutable_annotation(annotation, checker.semantic())
@@ -70,8 +73,10 @@ pub(crate) fn mutable_class_default(checker: &mut Checker, class_def: &ast::Stmt
.push(Diagnostic::new(MutableClassDefault, value.range()));
}
}
Stmt::Assign(ast::StmtAssign { value, .. }) => {
if is_mutable_expr(value, checker.semantic()) {
Stmt::Assign(ast::StmtAssign { value, targets, .. }) => {
if !targets.iter().all(is_special_attribute)
&& is_mutable_expr(value, checker.semantic())
{
// Avoid Pydantic models, which end up copying defaults on instance creation.
if is_pydantic_model(class_def, checker.semantic()) {
return;

View File

@@ -1,52 +1,34 @@
---
source: crates/ruff/src/rules/ruff/mod.rs
---
RUF012.py:8:34: RUF012 Mutable class attributes should be annotated with `typing.ClassVar`
RUF012.py:9:34: RUF012 Mutable class attributes should be annotated with `typing.ClassVar`
|
7 | class A:
8 | mutable_default: list[int] = []
7 | }
8 |
9 | mutable_default: list[int] = []
| ^^ RUF012
9 | immutable_annotation: typing.Sequence[int] = []
10 | without_annotation = []
10 | immutable_annotation: Sequence[int] = []
11 | without_annotation = []
|
RUF012.py:10:26: RUF012 Mutable class attributes should be annotated with `typing.ClassVar`
RUF012.py:11:26: RUF012 Mutable class attributes should be annotated with `typing.ClassVar`
|
8 | mutable_default: list[int] = []
9 | immutable_annotation: typing.Sequence[int] = []
10 | without_annotation = []
9 | mutable_default: list[int] = []
10 | immutable_annotation: Sequence[int] = []
11 | without_annotation = []
| ^^ RUF012
11 | correct_code: list[int] = KNOWINGLY_MUTABLE_DEFAULT
12 | class_variable: typing.ClassVar[list[int]] = []
12 | class_variable: ClassVar[list[int]] = []
13 | final_variable: Final[list[int]] = []
|
RUF012.py:17:34: RUF012 Mutable class attributes should be annotated with `typing.ClassVar`
RUF012.py:23:26: RUF012 Mutable class attributes should be annotated with `typing.ClassVar`
|
16 | class B:
17 | mutable_default: list[int] = []
| ^^ RUF012
18 | immutable_annotation: Sequence[int] = []
19 | without_annotation = []
|
RUF012.py:19:26: RUF012 Mutable class attributes should be annotated with `typing.ClassVar`
|
17 | mutable_default: list[int] = []
18 | immutable_annotation: Sequence[int] = []
19 | without_annotation = []
21 | mutable_default: list[int] = []
22 | immutable_annotation: Sequence[int] = []
23 | without_annotation = []
| ^^ RUF012
20 | correct_code: list[int] = KNOWINGLY_MUTABLE_DEFAULT
21 | class_variable: ClassVar[list[int]] = []
|
RUF012.py:32:26: RUF012 Mutable class attributes should be annotated with `typing.ClassVar`
|
30 | mutable_default: list[int] = []
31 | immutable_annotation: Sequence[int] = []
32 | without_annotation = []
| ^^ RUF012
33 | correct_code: list[int] = KNOWINGLY_MUTABLE_DEFAULT
34 | perfectly_fine: list[int] = field(default_factory=list)
24 | perfectly_fine: list[int] = field(default_factory=list)
25 | class_variable: ClassVar[list[int]] = []
|

View File

@@ -433,7 +433,7 @@ pub struct Options {
pub namespace_packages: Option<Vec<String>>,
#[option(
default = r#""py310""#,
value_type = r#""py37" | "py38" | "py39" | "py310" | "py311""#,
value_type = r#""py37" | "py38" | "py39" | "py310" | "py311" | "py312""#,
example = r#"
# Always generate Python 3.7-compatible code.
target-version = "py37"

View File

@@ -30,6 +30,7 @@ pub enum PythonVersion {
Py39,
Py310,
Py311,
Py312,
}
impl From<PythonVersion> for Pep440Version {
@@ -47,6 +48,7 @@ impl PythonVersion {
Self::Py39 => (3, 9),
Self::Py310 => (3, 10),
Self::Py311 => (3, 11),
Self::Py312 => (3, 12),
}
}

View File

@@ -1,6 +1,6 @@
[package]
name = "ruff_cli"
version = "0.0.274"
version = "0.0.275"
publish = false
authors = { workspace = true }
edition = { workspace = true }

View File

@@ -299,7 +299,7 @@ pub(crate) fn init(path: &Path) -> Result<()> {
}
#[cfg(test)]
mod test {
mod tests {
use std::env::temp_dir;
use std::fs;
use std::io::{self, Write};

View File

@@ -346,7 +346,7 @@ pub(crate) fn lint_stdin(
}
#[cfg(test)]
mod test {
mod tests {
use std::path::Path;
use crate::diagnostics::{load_jupyter_notebook, Diagnostics};

View File

@@ -42,6 +42,9 @@ pub(crate) struct Args {
/// Print only the first error and exit, `-x` is same as pytest
#[arg(long, short = 'x')]
pub(crate) exit_first_error: bool,
/// Checks each project inside a directory
#[arg(long)]
pub(crate) multi_project: bool,
}
/// Generate ourself a `try_parse_from` impl for `CheckArgs`. This is a strange way to use clap but
@@ -54,6 +57,35 @@ struct WrapperArgs {
}
pub(crate) fn main(args: &Args) -> anyhow::Result<ExitCode> {
let all_success = if args.multi_project {
let mut all_success = true;
for base_dir in &args.files {
for dir in base_dir.read_dir()? {
let dir = dir?;
println!("Starting {}", dir.path().display());
let success = check_repo(&Args {
files: vec![dir.path().clone()],
..*args
});
println!("Finished {}: {:?}", dir.path().display(), success);
if !matches!(success, Ok(true)) {
all_success = false;
}
}
}
all_success
} else {
check_repo(args)?
};
if all_success {
Ok(ExitCode::SUCCESS)
} else {
Ok(ExitCode::FAILURE)
}
}
/// Returns whether the check was successful
pub(crate) fn check_repo(args: &Args) -> anyhow::Result<bool> {
let start = Instant::now();
// Find files to check (or in this case, format twice). Adapted from ruff_cli
@@ -77,13 +109,20 @@ pub(crate) fn main(args: &Args) -> anyhow::Result<ExitCode> {
let (paths, _resolver) = python_files_in_path(&cli.files, &pyproject_config, &overrides)?;
assert!(!paths.is_empty(), "no python files in {:?}", cli.files);
let mut formatted_counter = 0;
let errors = paths
.into_iter()
.map(|dir_entry| {
// Doesn't make sense to recover here in this test script
let file = dir_entry
.expect("Iterating the files in the repository failed")
.into_path();
dir_entry.expect("Iterating the files in the repository failed")
})
.filter(|dir_entry| {
// For some reason it does not filter in the beginning
dir_entry.file_name() != "pyproject.toml"
})
.map(|dir_entry| {
let file = dir_entry.path().to_path_buf();
formatted_counter += 1;
// Handle panics (mostly in `debug_assert!`)
let result = match catch_unwind(|| check_file(&file)) {
Ok(result) => result,
@@ -166,20 +205,20 @@ Formatted twice:
}
if args.exit_first_error {
return Ok(ExitCode::FAILURE);
return Ok(false);
}
}
let duration = start.elapsed();
println!(
"Formatting {} files twice took {:.2}s",
cli.files.len(),
formatted_counter,
duration.as_secs_f32()
);
if any_errors {
Ok(ExitCode::FAILURE)
Ok(false)
} else {
Ok(ExitCode::SUCCESS)
Ok(true)
}
}

View File

@@ -119,7 +119,7 @@ fn check_help_text() -> String {
}
#[cfg(test)]
mod test {
mod tests {
use anyhow::Result;
use crate::generate_all::Mode;

View File

@@ -53,7 +53,7 @@ pub(crate) fn main(args: &Args) -> Result<()> {
}
#[cfg(test)]
mod test {
mod tests {
use anyhow::Result;
use std::env;

View File

@@ -48,3 +48,11 @@ mapping = {
C: 0.1 * (10.0 / 12),
D: 0.1 * (10.0 / 12),
}
# Regression test for formatter panic with comment after parenthesized dict value
# Originally found in https://github.com/bolucat/Firefox/blob/636a717ef025c16434997dc89e42351ef740ee6b/testing/marionette/client/marionette_driver/geckoinstance.py#L109
a = {
1: (2),
# comment
3: True,
}

View File

@@ -0,0 +1,36 @@
class Test(
Aaaaaaaaaaaaaaaaa,
Bbbbbbbbbbbbbbbb,
DDDDDDDDDDDDDDDD,
EEEEEEEEEEEEEE,
metaclass=meta,
):
pass
class Test((Aaaaaaaaaaaaaaaaa), Bbbbbbbbbbbbbbbb, metaclass=meta):
pass
class Test( # trailing class comment
Aaaaaaaaaaaaaaaaa, # trailing comment
# in between comment
Bbbbbbbbbbbbbbbb,
# another leading comment
DDDDDDDDDDDDDDDD,
EEEEEEEEEEEEEE,
# meta comment
metaclass=meta, # trailing meta comment
):
pass
class Test((Aaaa)):
...
class Test(aaaaaaaaaaaaaaa + bbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccc + dddddddddddddddddddddd + eeeeeeeee, ffffffffffffffffff, gggggggggggggggggg):
pass
class Test(Aaaa): # trailing comment
pass

View File

@@ -582,6 +582,12 @@ fn handle_trailing_end_of_line_condition_comment<'a>(
.as_deref()
.map(AnyNodeRef::from)
.or_else(|| Some(AnyNodeRef::from(args.as_ref()))),
AnyNodeRef::StmtClassDef(StmtClassDef {
bases, keywords, ..
}) => keywords
.last()
.map(AnyNodeRef::from)
.or_else(|| bases.last().map(AnyNodeRef::from)),
_ => None,
};
@@ -622,8 +628,13 @@ fn handle_trailing_end_of_line_condition_comment<'a>(
TokenKind::RParen => {
// Skip over any closing parentheses
}
_ => {
unreachable!("Only ')' or ':' should follow the condition")
TokenKind::Comma => {
// Skip over any trailing comma
}
kind => {
unreachable!(
"Only ')' or ':' should follow the condition but encountered {kind:?}"
)
}
}
}
@@ -980,14 +991,22 @@ fn handle_dict_unpacking_comment<'a>(
.skip_trivia();
// we start from the preceding node but we skip its token
if let Some(first) = tokens.next() {
debug_assert!(matches!(
first,
Token {
kind: TokenKind::LBrace | TokenKind::Comma | TokenKind::Colon,
..
}
));
for token in tokens.by_ref() {
// Skip closing parentheses that are not part of the node range
if token.kind == TokenKind::RParen {
continue;
}
debug_assert!(
matches!(
token,
Token {
kind: TokenKind::LBrace | TokenKind::Comma | TokenKind::Colon,
..
}
),
"{token:?}",
);
break;
}
// if the remaining tokens from the previous node is exactly `**`,

View File

@@ -10,11 +10,20 @@ use rustpython_parser::ast::ExprCall;
pub struct FormatExprCall;
impl FormatNodeRule<ExprCall> for FormatExprCall {
fn fmt_fields(&self, _item: &ExprCall, f: &mut PyFormatter) -> FormatResult<()> {
write!(
f,
[not_yet_implemented_custom_text("NOT_IMPLEMENTED_call()")]
)
fn fmt_fields(&self, item: &ExprCall, f: &mut PyFormatter) -> FormatResult<()> {
if item.args.is_empty() && item.keywords.is_empty() {
write!(
f,
[not_yet_implemented_custom_text("NOT_IMPLEMENTED_call()")]
)
} else {
write!(
f,
[not_yet_implemented_custom_text(
"NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)"
)]
)
}
}
}

View File

@@ -26,6 +26,8 @@ pub(super) fn default_expression_needs_parentheses(
#[allow(clippy::if_same_then_else)]
if parenthesize.is_always() {
Parentheses::Always
} else if parenthesize.is_never() {
Parentheses::Never
}
// `Optional` or `Preserve` and expression has parentheses in source code.
else if !parenthesize.is_if_breaks() && is_expression_parenthesized(node, source) {
@@ -58,7 +60,11 @@ pub enum Parenthesize {
/// Parenthesizes the expression only if it doesn't fit on a line.
IfBreaks,
/// Always adds parentheses
Always,
/// Never adds parentheses. Parentheses are handled by the caller.
Never,
}
impl Parenthesize {
@@ -66,6 +72,10 @@ impl Parenthesize {
matches!(self, Parenthesize::Always)
}
pub(crate) const fn is_never(self) -> bool {
matches!(self, Parenthesize::Never)
}
pub(crate) const fn is_if_breaks(self) -> bool {
matches!(self, Parenthesize::IfBreaks)
}

View File

@@ -247,12 +247,12 @@ mod tests {
let input = r#"
# preceding
if True:
print( "hi" )
pass
# trailing
"#;
let expected = r#"# preceding
if True:
NOT_IMPLEMENTED_call()
pass
# trailing
"#;
let actual = format_module(input)?.as_code().to_string();

View File

@@ -1,5 +1,6 @@
use crate::{not_yet_implemented, FormatNodeRule, PyFormatter};
use ruff_formatter::{write, Buffer, FormatResult};
use crate::prelude::*;
use crate::FormatNodeRule;
use ruff_formatter::write;
use rustpython_parser::ast::Keyword;
#[derive(Default)]
@@ -7,6 +8,15 @@ pub struct FormatKeyword;
impl FormatNodeRule<Keyword> for FormatKeyword {
fn fmt_fields(&self, item: &Keyword, f: &mut PyFormatter) -> FormatResult<()> {
write!(f, [not_yet_implemented(item)])
let Keyword {
range: _,
arg,
value,
} = item;
if let Some(argument) = arg {
write!(f, [argument.format(), text("=")])?;
}
value.format().fmt(f)
}
}

View File

@@ -62,7 +62,7 @@ y = 100(no)
+x = (123456789.123456789E123456789).real
+x = NOT_IMPLEMENTED_call()
+x = 123456789J.real
+x = NOT_IMPLEMENTED_call()
+x = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+x = NOT_IMPLEMENTED_call()
+x = NOT_IMPLEMENTED_call()
+x = (0O777).real
@@ -74,7 +74,7 @@ y = 100(no)
y = 100[no]
-y = 100(no)
+y = NOT_IMPLEMENTED_call()
+y = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
```
## Ruff Output
@@ -90,7 +90,7 @@ x = NOT_IMPLEMENTED_call()
x = (123456789.123456789E123456789).real
x = NOT_IMPLEMENTED_call()
x = 123456789J.real
x = NOT_IMPLEMENTED_call()
x = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
x = NOT_IMPLEMENTED_call()
x = NOT_IMPLEMENTED_call()
x = (0O777).real
@@ -101,7 +101,7 @@ if (10).real:
...
y = 100[no]
y = NOT_IMPLEMENTED_call()
y = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
```
## Black Output

View File

@@ -22,13 +22,13 @@ print("hello, world")
+++ Ruff
@@ -1 +1 @@
-print("hello, world")
+NOT_IMPLEMENTED_call()
+NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
```
## Ruff Output
```py
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
```
## Black Output

View File

@@ -1,135 +0,0 @@
---
source: crates/ruff_python_formatter/src/lib.rs
expression: snapshot
input_file: crates/ruff_python_formatter/resources/test/fixtures/black/simple_cases/class_blank_parentheses.py
---
## Input
```py
class SimpleClassWithBlankParentheses():
pass
class ClassWithSpaceParentheses ( ):
first_test_data = 90
second_test_data = 100
def test_func(self):
return None
class ClassWithEmptyFunc(object):
def func_with_blank_parentheses():
return 5
def public_func_with_blank_parentheses():
return None
def class_under_the_func_with_blank_parentheses():
class InsideFunc():
pass
class NormalClass (
):
def func_for_testing(self, first, second):
sum = first + second
return sum
```
## Black Differences
```diff
--- Black
+++ Ruff
@@ -1,18 +1,10 @@
-class SimpleClassWithBlankParentheses:
- pass
+NOT_YET_IMPLEMENTED_StmtClassDef
-class ClassWithSpaceParentheses:
- first_test_data = 90
- second_test_data = 100
-
- def test_func(self):
- return None
+NOT_YET_IMPLEMENTED_StmtClassDef
-class ClassWithEmptyFunc(object):
- def func_with_blank_parentheses():
- return 5
+NOT_YET_IMPLEMENTED_StmtClassDef
def public_func_with_blank_parentheses():
@@ -20,11 +12,7 @@
def class_under_the_func_with_blank_parentheses():
- class InsideFunc:
- pass
+ NOT_YET_IMPLEMENTED_StmtClassDef
-class NormalClass:
- def func_for_testing(self, first, second):
- sum = first + second
- return sum
+NOT_YET_IMPLEMENTED_StmtClassDef
```
## Ruff Output
```py
NOT_YET_IMPLEMENTED_StmtClassDef
NOT_YET_IMPLEMENTED_StmtClassDef
NOT_YET_IMPLEMENTED_StmtClassDef
def public_func_with_blank_parentheses():
return None
def class_under_the_func_with_blank_parentheses():
NOT_YET_IMPLEMENTED_StmtClassDef
NOT_YET_IMPLEMENTED_StmtClassDef
```
## Black Output
```py
class SimpleClassWithBlankParentheses:
pass
class ClassWithSpaceParentheses:
first_test_data = 90
second_test_data = 100
def test_func(self):
return None
class ClassWithEmptyFunc(object):
def func_with_blank_parentheses():
return 5
def public_func_with_blank_parentheses():
return None
def class_under_the_func_with_blank_parentheses():
class InsideFunc:
pass
class NormalClass:
def func_for_testing(self, first, second):
sum = first + second
return sum
```

View File

@@ -113,259 +113,257 @@ class ClassWithDecoInitAndVarsAndDocstringWithInner2:
```diff
--- Black
+++ Ruff
@@ -1,165 +1,61 @@
-class ClassSimplest:
- pass
+NOT_YET_IMPLEMENTED_StmtClassDef
@@ -7,7 +7,7 @@
-class ClassWithSingleField:
- a = 1
+NOT_YET_IMPLEMENTED_StmtClassDef
-class ClassWithJustTheDocstring:
class ClassWithJustTheDocstring:
- """Just a docstring."""
+NOT_YET_IMPLEMENTED_StmtClassDef
+ "NOT_YET_IMPLEMENTED_STRING"
-class ClassWithInit:
- def __init__(self):
- pass
+NOT_YET_IMPLEMENTED_StmtClassDef
class ClassWithInit:
@@ -16,7 +16,7 @@
-class ClassWithTheDocstringAndInit:
class ClassWithTheDocstringAndInit:
- """Just a docstring."""
+NOT_YET_IMPLEMENTED_StmtClassDef
+ "NOT_YET_IMPLEMENTED_STRING"
- def __init__(self):
- pass
+NOT_YET_IMPLEMENTED_StmtClassDef
-class ClassWithInitAndVars:
- cls_var = 100
- def __init__(self):
- pass
+NOT_YET_IMPLEMENTED_StmtClassDef
def __init__(self):
pass
@@ -30,8 +30,7 @@
-class ClassWithInitAndVarsAndDocstring:
class ClassWithInitAndVarsAndDocstring:
- """Test class"""
+NOT_YET_IMPLEMENTED_StmtClassDef
-
+ "NOT_YET_IMPLEMENTED_STRING"
cls_var = 100
- cls_var = 100
- def __init__(self):
- pass
+NOT_YET_IMPLEMENTED_StmtClassDef
def __init__(self):
@@ -53,8 +52,7 @@
-class ClassWithDecoInit:
- @deco
- def __init__(self):
- pass
+NOT_YET_IMPLEMENTED_StmtClassDef
-class ClassWithDecoInitAndVars:
- cls_var = 100
+NOT_YET_IMPLEMENTED_StmtClassDef
- @deco
- def __init__(self):
- pass
+NOT_YET_IMPLEMENTED_StmtClassDef
-class ClassWithDecoInitAndVarsAndDocstring:
class ClassWithDecoInitAndVarsAndDocstring:
- """Test class"""
-
+ "NOT_YET_IMPLEMENTED_STRING"
cls_var = 100
- cls_var = 100
+NOT_YET_IMPLEMENTED_StmtClassDef
@deco
@@ -69,7 +67,7 @@
- @deco
- def __init__(self):
- pass
+NOT_YET_IMPLEMENTED_StmtClassDef
-class ClassSimplestWithInner:
- class Inner:
- pass
+NOT_YET_IMPLEMENTED_StmtClassDef
-class ClassSimplestWithInnerWithDocstring:
- class Inner:
class ClassSimplestWithInnerWithDocstring:
class Inner:
- """Just a docstring."""
+ "NOT_YET_IMPLEMENTED_STRING"
- def __init__(self):
- pass
+NOT_YET_IMPLEMENTED_StmtClassDef
def __init__(self):
pass
@@ -83,7 +81,7 @@
-class ClassWithSingleFieldWithInner:
- a = 1
+NOT_YET_IMPLEMENTED_StmtClassDef
- class Inner:
- pass
+NOT_YET_IMPLEMENTED_StmtClassDef
-class ClassWithJustTheDocstringWithInner:
class ClassWithJustTheDocstringWithInner:
- """Just a docstring."""
+ "NOT_YET_IMPLEMENTED_STRING"
- class Inner:
- pass
+NOT_YET_IMPLEMENTED_StmtClassDef
class Inner:
pass
@@ -108,8 +106,7 @@
-class ClassWithInitWithInner:
- class Inner:
- pass
-
- def __init__(self):
- pass
-
-
-class ClassWithInitAndVarsWithInner:
- cls_var = 100
-
- class Inner:
- pass
-
- def __init__(self):
- pass
-
-
-class ClassWithInitAndVarsAndDocstringWithInner:
class ClassWithInitAndVarsAndDocstringWithInner:
- """Test class"""
-
- cls_var = 100
-
- class Inner:
- pass
-
- def __init__(self):
- pass
-
-
-class ClassWithDecoInitWithInner:
- class Inner:
- pass
-
- @deco
- def __init__(self):
- pass
+NOT_YET_IMPLEMENTED_StmtClassDef
+ "NOT_YET_IMPLEMENTED_STRING"
cls_var = 100
class Inner:
@@ -140,8 +137,7 @@
-class ClassWithDecoInitAndVarsWithInner:
- cls_var = 100
-
- class Inner:
- pass
-
- @deco
- def __init__(self):
- pass
-
-
-class ClassWithDecoInitAndVarsAndDocstringWithInner:
class ClassWithDecoInitAndVarsAndDocstringWithInner:
- """Test class"""
-
- cls_var = 100
-
- class Inner:
- pass
-
- @deco
- def __init__(self):
- pass
-
-
-class ClassWithDecoInitAndVarsAndDocstringWithInner2:
+ "NOT_YET_IMPLEMENTED_STRING"
cls_var = 100
class Inner:
@@ -153,7 +149,7 @@
class ClassWithDecoInitAndVarsAndDocstringWithInner2:
- """Test class"""
-
- class Inner:
- pass
-
- cls_var = 100
-
- @deco
- def __init__(self):
- pass
+NOT_YET_IMPLEMENTED_StmtClassDef
+ "NOT_YET_IMPLEMENTED_STRING"
class Inner:
pass
```
## Ruff Output
```py
NOT_YET_IMPLEMENTED_StmtClassDef
class ClassSimplest:
pass
NOT_YET_IMPLEMENTED_StmtClassDef
class ClassWithSingleField:
a = 1
NOT_YET_IMPLEMENTED_StmtClassDef
class ClassWithJustTheDocstring:
"NOT_YET_IMPLEMENTED_STRING"
NOT_YET_IMPLEMENTED_StmtClassDef
class ClassWithInit:
def __init__(self):
pass
NOT_YET_IMPLEMENTED_StmtClassDef
class ClassWithTheDocstringAndInit:
"NOT_YET_IMPLEMENTED_STRING"
def __init__(self):
pass
NOT_YET_IMPLEMENTED_StmtClassDef
class ClassWithInitAndVars:
cls_var = 100
def __init__(self):
pass
NOT_YET_IMPLEMENTED_StmtClassDef
class ClassWithInitAndVarsAndDocstring:
"NOT_YET_IMPLEMENTED_STRING"
cls_var = 100
def __init__(self):
pass
NOT_YET_IMPLEMENTED_StmtClassDef
class ClassWithDecoInit:
@deco
def __init__(self):
pass
NOT_YET_IMPLEMENTED_StmtClassDef
class ClassWithDecoInitAndVars:
cls_var = 100
@deco
def __init__(self):
pass
NOT_YET_IMPLEMENTED_StmtClassDef
class ClassWithDecoInitAndVarsAndDocstring:
"NOT_YET_IMPLEMENTED_STRING"
cls_var = 100
@deco
def __init__(self):
pass
NOT_YET_IMPLEMENTED_StmtClassDef
class ClassSimplestWithInner:
class Inner:
pass
NOT_YET_IMPLEMENTED_StmtClassDef
class ClassSimplestWithInnerWithDocstring:
class Inner:
"NOT_YET_IMPLEMENTED_STRING"
def __init__(self):
pass
NOT_YET_IMPLEMENTED_StmtClassDef
class ClassWithSingleFieldWithInner:
a = 1
class Inner:
pass
NOT_YET_IMPLEMENTED_StmtClassDef
class ClassWithJustTheDocstringWithInner:
"NOT_YET_IMPLEMENTED_STRING"
class Inner:
pass
NOT_YET_IMPLEMENTED_StmtClassDef
class ClassWithInitWithInner:
class Inner:
pass
def __init__(self):
pass
NOT_YET_IMPLEMENTED_StmtClassDef
class ClassWithInitAndVarsWithInner:
cls_var = 100
class Inner:
pass
def __init__(self):
pass
NOT_YET_IMPLEMENTED_StmtClassDef
class ClassWithInitAndVarsAndDocstringWithInner:
"NOT_YET_IMPLEMENTED_STRING"
cls_var = 100
class Inner:
pass
def __init__(self):
pass
NOT_YET_IMPLEMENTED_StmtClassDef
class ClassWithDecoInitWithInner:
class Inner:
pass
@deco
def __init__(self):
pass
NOT_YET_IMPLEMENTED_StmtClassDef
class ClassWithDecoInitAndVarsWithInner:
cls_var = 100
class Inner:
pass
@deco
def __init__(self):
pass
NOT_YET_IMPLEMENTED_StmtClassDef
class ClassWithDecoInitAndVarsAndDocstringWithInner:
"NOT_YET_IMPLEMENTED_STRING"
cls_var = 100
class Inner:
pass
@deco
def __init__(self):
pass
NOT_YET_IMPLEMENTED_StmtClassDef
class ClassWithDecoInitAndVarsAndDocstringWithInner2:
"NOT_YET_IMPLEMENTED_STRING"
class Inner:
pass
cls_var = 100
@deco
def __init__(self):
pass
```
## Black Output

View File

@@ -178,7 +178,7 @@ if True:
division_result_tuple = (6 / 2,)
-print("foo %r", (foo.bar,))
+NOT_IMPLEMENTED_call()
+NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
if True:
IGNORED_TYPES_FOR_ATTRIBUTE_CHECKING = (
@@ -204,9 +204,9 @@ if True:
- "Delay": 5,
- },
- )
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
```
## Ruff Output
@@ -259,7 +259,7 @@ for (x,) in (1,), (2,), (3,):
[1, 2, 3]
division_result_tuple = (6 / 2,)
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
if True:
IGNORED_TYPES_FOR_ATTRIBUTE_CHECKING = (
@@ -268,9 +268,9 @@ if True:
)
if True:
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
```
## Black Output

View File

@@ -243,19 +243,19 @@ instruction()#comment with bad spacing
Cheese,
- Cheese("Wensleydale"),
- SubBytes(b"spam"),
+ NOT_IMPLEMENTED_call(),
+ NOT_IMPLEMENTED_call(),
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg),
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg),
]
-if "PYTHON" in os.environ:
- add_compiler(compiler_from_env())
+if NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right:
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
else:
# for compiler in compilers.values():
# add_compiler(compiler)
- add_compiler(compilers[(7.0, 32)])
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# add_compiler(compilers[(7.1, 64)])
@@ -307,7 +307,7 @@ instruction()#comment with bad spacing
-""",
- arg3=True,
- )
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
############################################################################
@@ -342,14 +342,14 @@ instruction()#comment with bad spacing
- # right
- if element is not None
- ]
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+ lcomp = [i for i in []]
+ lcomp2 = [i for i in []]
+ lcomp3 = [i for i in []]
while True:
if False:
continue
@@ -141,25 +111,13 @@
@@ -141,24 +111,18 @@
# and round and round we go
# let's return
@@ -357,7 +357,7 @@ instruction()#comment with bad spacing
- syms.simple_stmt,
- [Node(statement, result), Leaf(token.NEWLINE, "\n")], # FIXME: \r\n?
- )
+ return NOT_IMPLEMENTED_call()
+ return NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
-CONFIG_FILES = (
@@ -370,15 +370,17 @@ instruction()#comment with bad spacing
+CONFIG_FILES = [CONFIG_FILE] + SHARED_CONFIG_FILES + USER_CONFIG_FILES # type: Final
-class Test:
- def _init_host(self, parsed) -> None:
class Test:
def _init_host(self, parsed) -> None:
- if parsed.hostname is None or not parsed.hostname.strip(): # type: ignore
- pass
+NOT_YET_IMPLEMENTED_StmtClassDef
+ if (
+ NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right # type: ignore
+ or not NOT_IMPLEMENTED_call()
+ ):
pass
#######################
@@ -167,7 +125,7 @@
@@ -167,7 +131,7 @@
#######################
@@ -434,16 +436,16 @@ not_shareables = [
"NOT_YET_IMPLEMENTED_STRING",
# user-defined types and objects
Cheese,
NOT_IMPLEMENTED_call(),
NOT_IMPLEMENTED_call(),
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg),
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg),
]
if NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right:
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
else:
# for compiler in compilers.values():
# add_compiler(compiler)
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# add_compiler(compilers[(7.1, 64)])
@@ -489,11 +491,11 @@ def inline_comments_in_brackets_ruin_everything():
]
# no newline after
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
############################################################################
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
lcomp = [i for i in []]
lcomp2 = [i for i in []]
lcomp3 = [i for i in []]
@@ -505,13 +507,19 @@ def inline_comments_in_brackets_ruin_everything():
# and round and round we go
# let's return
return NOT_IMPLEMENTED_call()
return NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
CONFIG_FILES = [CONFIG_FILE] + SHARED_CONFIG_FILES + USER_CONFIG_FILES # type: Final
NOT_YET_IMPLEMENTED_StmtClassDef
class Test:
def _init_host(self, parsed) -> None:
if (
NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right # type: ignore
or not NOT_IMPLEMENTED_call()
):
pass
#######################

View File

@@ -80,7 +80,7 @@ def func():
+ lcomp3 = [i for i in []]
# Capture each of the exceptions in the MultiError along with each of their causes and contexts
- if isinstance(exc_value, MultiError):
+ if NOT_IMPLEMENTED_call():
+ if NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg):
embedded = []
for exc in exc_value.exceptions:
- if exc not in _seen:
@@ -98,7 +98,7 @@ def func():
- # This should be left alone (after)
- )
+ if NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right:
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# everything is fine if the expression isn't nested
- traceback.TracebackException.from_exception(
@@ -110,7 +110,7 @@ def func():
- # shared between sub-exceptions are not omitted
- _seen=set(_seen),
- )
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# %%
@@ -127,14 +127,14 @@ def func():
x = "NOT_YET_IMPLEMENTED_STRING"
lcomp3 = [i for i in []]
# Capture each of the exceptions in the MultiError along with each of their causes and contexts
if NOT_IMPLEMENTED_call():
if NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg):
embedded = []
for exc in exc_value.exceptions:
if NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right:
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# everything is fine if the expression isn't nested
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# %%

View File

@@ -107,7 +107,7 @@ def foo3(list_a, list_b):
```diff
--- Black
+++ Ruff
@@ -1,94 +1,22 @@
@@ -1,94 +1,28 @@
-from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import (
- MyLovelyCompanyTeamProjectComponent, # NOT DRY
-)
@@ -118,7 +118,7 @@ def foo3(list_a, list_b):
+NOT_YET_IMPLEMENTED_StmtImportFrom
-class C:
class C:
- @pytest.mark.parametrize(
- ("post_data", "message"),
- [
@@ -161,12 +161,14 @@ def foo3(list_a, list_b):
- ),
- ],
- )
- def test_fails_invalid_post_data(
- self, pyramid_config, db_request, post_data, message
- ):
+ @NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
def test_fails_invalid_post_data(
self, pyramid_config, db_request, post_data, message
):
- pyramid_config.testing_securitypolicy(userid=1)
- db_request.POST = MultiDict(post_data)
+NOT_YET_IMPLEMENTED_StmtClassDef
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+ db_request.POST = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
def foo(list_a, list_b):
@@ -195,7 +197,7 @@ def foo3(list_a, list_b):
- )
- .filter(User.xyz.is_(None))
- )
+ return NOT_IMPLEMENTED_call()
+ return NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
def foo3(list_a, list_b):
@@ -206,7 +208,7 @@ def foo3(list_a, list_b):
- db.or_(User.field_a.astext.in_(list_a), User.field_b.astext.in_(list_b))
- )
- .filter(User.xyz.is_(None))
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
)
```
@@ -217,7 +219,13 @@ NOT_YET_IMPLEMENTED_StmtImportFrom
NOT_YET_IMPLEMENTED_StmtImportFrom
NOT_YET_IMPLEMENTED_StmtClassDef
class C:
@NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
def test_fails_invalid_post_data(
self, pyramid_config, db_request, post_data, message
):
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
db_request.POST = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
def foo(list_a, list_b):
@@ -227,13 +235,13 @@ def foo(list_a, list_b):
def foo2(list_a, list_b):
# Standalone comment reasonably placed.
return NOT_IMPLEMENTED_call()
return NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
def foo3(list_a, list_b):
return (
# Standalone comment but weirdly placed.
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
)
```

View File

@@ -99,7 +99,7 @@ if __name__ == "__main__":
# This one is properly standalone now.
-for i in range(100):
+for i in NOT_IMPLEMENTED_call():
+for i in NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg):
# first we do this
- if i % 33 == 0:
+ if NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right:
@@ -107,7 +107,7 @@ if __name__ == "__main__":
# then we do this
- print(i)
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# and finally we loop around
-with open(some_temp_file) as f:
@@ -132,7 +132,7 @@ if __name__ == "__main__":
@deco1
# leading 2
-@deco2(with_args=True)
+@NOT_IMPLEMENTED_call()
+@NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# leading 3
@deco3
def decorated1():
@@ -141,7 +141,7 @@ if __name__ == "__main__":
@deco1
# leading 2
-@deco2(with_args=True)
+@NOT_IMPLEMENTED_call()
+@NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# leading function comment
def decorated1():
...
@@ -168,13 +168,13 @@ while True:
# This one is properly standalone now.
for i in NOT_IMPLEMENTED_call():
for i in NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg):
# first we do this
if NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right:
break
# then we do this
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# and finally we loop around
NOT_YET_IMPLEMENTED_StmtWith
@@ -196,7 +196,7 @@ def wat():
# leading 1
@deco1
# leading 2
@NOT_IMPLEMENTED_call()
@NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# leading 3
@deco3
def decorated1():
@@ -206,7 +206,7 @@ def decorated1():
# leading 1
@deco1
# leading 2
@NOT_IMPLEMENTED_call()
@NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# leading function comment
def decorated1():
...

View File

@@ -169,12 +169,12 @@ aaaaaaaaaaaaa, bbbbbbbbb = map(list, map(itertools.chain.from_iterable, zip(*ite
- 0.0789,
- a[-1], # type: ignore
- )
+ c = NOT_IMPLEMENTED_call()
+ c = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
- c = call(
- "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa" # type: ignore
- )
+ c = NOT_IMPLEMENTED_call()
+ c = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
-result = ( # aaa
@@ -194,10 +194,10 @@ aaaaaaaaaaaaa, bbbbbbbbb = map(list, map(itertools.chain.from_iterable, zip(*ite
- foo,
- [AAAAAAAAAAAAAAAAAAAAAAA, AAAAAAAAAAAAAAAAAAAAAAA, AAAAAAAAAAAAAAAAAAAAAAA, BBBBBBBBBBBB], # type: ignore
-)
+NOT_IMPLEMENTED_call()
+NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
-aaaaaaaaaaaaa, bbbbbbbbb = map(list, map(itertools.chain.from_iterable, zip(*items))) # type: ignore[arg-type]
+aaaaaaaaaaaaa, bbbbbbbbb = NOT_IMPLEMENTED_call() # type: ignore[arg-type]
+aaaaaaaaaaaaa, bbbbbbbbb = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg) # type: ignore[arg-type]
```
## Ruff Output
@@ -292,9 +292,9 @@ def f(
def func(
a=some_list[0], # type: int
): # type: () -> int
c = NOT_IMPLEMENTED_call()
c = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
c = NOT_IMPLEMENTED_call()
c = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
result = "NOT_YET_IMPLEMENTED_STRING" # aaa
@@ -306,9 +306,9 @@ AAAAAAAAAAAAA = (
+ AAAAAAAAAAAAA
) # type: ignore
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
aaaaaaaaaaaaa, bbbbbbbbb = NOT_IMPLEMENTED_call() # type: ignore[arg-type]
aaaaaaaaaaaaa, bbbbbbbbb = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg) # type: ignore[arg-type]
```
## Black Output

View File

@@ -152,65 +152,43 @@ def bar():
```diff
--- Black
+++ Ruff
@@ -30,8 +30,7 @@
@@ -44,7 +44,7 @@
# This comment should be split from the statement above by two lines.
-class MyClass:
- pass
+NOT_YET_IMPLEMENTED_StmtClassDef
some = statement
@@ -39,17 +38,14 @@
# This should be split from the above by two lines
-class MyClassWithComplexLeadingComments:
- pass
+NOT_YET_IMPLEMENTED_StmtClassDef
-class ClassWithDocstring:
class ClassWithDocstring:
- """A docstring."""
+NOT_YET_IMPLEMENTED_StmtClassDef
+ "NOT_YET_IMPLEMENTED_STRING"
# Leading comment after a class with just a docstring
-class MyClassAfterAnotherClassWithDocstring:
- pass
+NOT_YET_IMPLEMENTED_StmtClassDef
some = statement
@@ -59,7 +55,7 @@
@@ -59,7 +59,7 @@
@deco1
# leading 2
# leading 2 extra
-@deco2(with_args=True)
+@NOT_IMPLEMENTED_call()
+@NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# leading 3
@deco3
# leading 4
@@ -73,7 +69,7 @@
@@ -73,7 +73,7 @@
# leading 1
@deco1
# leading 2
-@deco2(with_args=True)
+@NOT_IMPLEMENTED_call()
+@NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# leading 3 that already has an empty line
@deco3
@@ -88,7 +84,7 @@
@@ -88,7 +88,7 @@
# leading 1
@deco1
# leading 2
-@deco2(with_args=True)
+@NOT_IMPLEMENTED_call()
+@NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# leading 3
@deco3
@@ -106,7 +102,6 @@
@@ -106,7 +106,6 @@
# Another leading comment
def another_inline():
pass
@@ -218,7 +196,7 @@ def bar():
else:
# More leading comments
def inline_after_else():
@@ -121,18 +116,13 @@
@@ -121,7 +120,6 @@
# Another leading comment
def another_top_level_quote_inline_inline():
pass
@@ -226,18 +204,6 @@ def bar():
else:
# More leading comments
def top_level_quote_inline_after_else():
pass
-class MyClass:
- # First method has no empty lines between bare class def.
- # More comments.
- def first_method(self):
- pass
+NOT_YET_IMPLEMENTED_StmtClassDef
# Regression test for https://github.com/psf/black/issues/3454.
```
## Ruff Output
@@ -275,7 +241,8 @@ some = statement
# This comment should be split from the statement above by two lines.
NOT_YET_IMPLEMENTED_StmtClassDef
class MyClass:
pass
some = statement
@@ -283,14 +250,17 @@ some = statement
# This should be split from the above by two lines
NOT_YET_IMPLEMENTED_StmtClassDef
class MyClassWithComplexLeadingComments:
pass
NOT_YET_IMPLEMENTED_StmtClassDef
class ClassWithDocstring:
"NOT_YET_IMPLEMENTED_STRING"
# Leading comment after a class with just a docstring
NOT_YET_IMPLEMENTED_StmtClassDef
class MyClassAfterAnotherClassWithDocstring:
pass
some = statement
@@ -300,7 +270,7 @@ some = statement
@deco1
# leading 2
# leading 2 extra
@NOT_IMPLEMENTED_call()
@NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# leading 3
@deco3
# leading 4
@@ -314,7 +284,7 @@ some = statement
# leading 1
@deco1
# leading 2
@NOT_IMPLEMENTED_call()
@NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# leading 3 that already has an empty line
@deco3
@@ -329,7 +299,7 @@ some = statement
# leading 1
@deco1
# leading 2
@NOT_IMPLEMENTED_call()
@NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# leading 3
@deco3
@@ -367,7 +337,11 @@ else:
pass
NOT_YET_IMPLEMENTED_StmtClassDef
class MyClass:
# First method has no empty lines between bare class def.
# More comments.
def first_method(self):
pass
# Regression test for https://github.com/psf/black/issues/3454.

View File

@@ -47,7 +47,7 @@ def function(a:int=42):
result = 1 #  type: ignore
result = 1 # This comment is talking about type: ignore
-square = Square(4) #  type: Optional[Square]
+square = NOT_IMPLEMENTED_call() #  type: Optional[Square]
+square = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg) #  type: Optional[Square]
def function(a: int = 42):
@@ -71,7 +71,7 @@ result = (1,) # Another one
result = 1 #  type: ignore
result = 1 # This comment is talking about type: ignore
square = NOT_IMPLEMENTED_call() #  type: Optional[Square]
square = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg) #  type: Optional[Square]
def function(a: int = 42):

View File

@@ -114,16 +114,16 @@ async def wat():
# Has many lines. Many, many lines.
# Many, many, many lines.
-"""Module docstring.
-
+"NOT_YET_IMPLEMENTED_STRING"
-Possibly also many, many lines.
-"""
+"NOT_YET_IMPLEMENTED_STRING"
+NOT_YET_IMPLEMENTED_StmtImport
+NOT_YET_IMPLEMENTED_StmtImport
-import os.path
-import sys
+NOT_YET_IMPLEMENTED_StmtImport
+NOT_YET_IMPLEMENTED_StmtImport
-
-import a
-from b.c import X # some noqa comment
+NOT_YET_IMPLEMENTED_StmtImport
@@ -137,7 +137,7 @@ async def wat():
# Some comment before a function.
@@ -30,67 +24,50 @@
@@ -30,25 +24,26 @@
def function(default=None):
@@ -166,42 +166,43 @@ async def wat():
# Explains why we use global state.
-GLOBAL_STATE = {"a": a(1), "b": a(2), "c": a(3)}
+GLOBAL_STATE = {
+ "NOT_YET_IMPLEMENTED_STRING": NOT_IMPLEMENTED_call(),
+ "NOT_YET_IMPLEMENTED_STRING": NOT_IMPLEMENTED_call(),
+ "NOT_YET_IMPLEMENTED_STRING": NOT_IMPLEMENTED_call(),
+ "NOT_YET_IMPLEMENTED_STRING": NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg),
+ "NOT_YET_IMPLEMENTED_STRING": NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg),
+ "NOT_YET_IMPLEMENTED_STRING": NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg),
+}
# Another comment!
# This time two lines.
@@ -56,7 +51,7 @@
-class Foo:
class Foo:
- """Docstring for class Foo. Example from Sphinx docs."""
-
- #: Doc comment for class attribute Foo.bar.
- #: It can have multiple lines.
- bar = 1
-
- flox = 1.5 #: Doc comment for Foo.flox. One line only.
-
- baz = 2
+ "NOT_YET_IMPLEMENTED_STRING"
#: Doc comment for class attribute Foo.bar.
#: It can have multiple lines.
@@ -65,32 +60,31 @@
flox = 1.5 #: Doc comment for Foo.flox. One line only.
baz = 2
- """Docstring for class attribute Foo.baz."""
-
- def __init__(self):
- #: Doc comment for instance attribute qux.
- self.qux = 3
-
- self.spam = 4
+ "NOT_YET_IMPLEMENTED_STRING"
def __init__(self):
#: Doc comment for instance attribute qux.
self.qux = 3
self.spam = 4
- """Docstring for instance attribute spam."""
+NOT_YET_IMPLEMENTED_StmtClassDef
+ "NOT_YET_IMPLEMENTED_STRING"
#' <h1>This is pweave!</h1>
-@fast(really=True)
+@NOT_IMPLEMENTED_call()
+@NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
async def wat():
# This comment, for some reason \
# contains a trailing backslash.
@@ -211,7 +212,7 @@ async def wat():
# Comment after ending a block.
if result:
- print("A OK", file=sys.stdout)
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# Comment between things.
- print()
+ NOT_IMPLEMENTED_call()
@@ -269,9 +270,9 @@ def function(default=None):
# Explains why we use global state.
GLOBAL_STATE = {
"NOT_YET_IMPLEMENTED_STRING": NOT_IMPLEMENTED_call(),
"NOT_YET_IMPLEMENTED_STRING": NOT_IMPLEMENTED_call(),
"NOT_YET_IMPLEMENTED_STRING": NOT_IMPLEMENTED_call(),
"NOT_YET_IMPLEMENTED_STRING": NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg),
"NOT_YET_IMPLEMENTED_STRING": NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg),
"NOT_YET_IMPLEMENTED_STRING": NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg),
}
@@ -279,20 +280,37 @@ GLOBAL_STATE = {
# This time two lines.
NOT_YET_IMPLEMENTED_StmtClassDef
class Foo:
"NOT_YET_IMPLEMENTED_STRING"
#: Doc comment for class attribute Foo.bar.
#: It can have multiple lines.
bar = 1
flox = 1.5 #: Doc comment for Foo.flox. One line only.
baz = 2
"NOT_YET_IMPLEMENTED_STRING"
def __init__(self):
#: Doc comment for instance attribute qux.
self.qux = 3
self.spam = 4
"NOT_YET_IMPLEMENTED_STRING"
#' <h1>This is pweave!</h1>
@NOT_IMPLEMENTED_call()
@NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
async def wat():
# This comment, for some reason \
# contains a trailing backslash.
NOT_YET_IMPLEMENTED_StmtAsyncWith # Some more comments
# Comment after ending a block.
if result:
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# Comment between things.
NOT_IMPLEMENTED_call()

View File

@@ -194,9 +194,9 @@ class C:
```diff
--- Black
+++ Ruff
@@ -1,181 +1 @@
-class C:
- def test(self) -> None:
@@ -1,181 +1,46 @@
class C:
def test(self) -> None:
- with patch("black.out", print):
- self.assertEqual(
- unstyle(str(report)), "1 file reformatted, 1 file failed to reformat."
@@ -239,23 +239,38 @@ class C:
- return (
- 'Utterly failed doctest test for %s\n File "%s", line %s, in %s\n\n%s'
- % (test.name, test.filename, lineno, lname, err)
- )
-
- def omitting_trailers(self) -> None:
+ NOT_YET_IMPLEMENTED_StmtWith
+ xxxxxxxxxxxxxxxx = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+ return "NOT_YET_IMPLEMENTED_STRING" % (
+ test.name,
+ test.filename,
+ lineno,
+ lname,
+ err,
)
def omitting_trailers(self) -> None:
- get_collection(
- hey_this_is_a_very_long_call, it_has_funny_attributes, really=True
- )[OneLevelIndex]
- get_collection(
- hey_this_is_a_very_long_call, it_has_funny_attributes, really=True
- )[OneLevelIndex][TwoLevelIndex][ThreeLevelIndex][FourLevelIndex]
- d[0][1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18][19][20][21][
- 22
- ]
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)[OneLevelIndex]
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)[OneLevelIndex][TwoLevelIndex][
+ ThreeLevelIndex
+ ][
+ FourLevelIndex
+ ]
d[0][1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18][19][20][21][
22
]
- assignment = (
- some.rather.elaborate.rule() and another.rule.ending_with.index[123]
- )
-
- def easy_asserts(self) -> None:
+ assignment = NOT_IMPLEMENTED_call() and another.rule.ending_with.index[123]
def easy_asserts(self) -> None:
- assert {
- key1: value1,
- key2: value2,
@@ -267,7 +282,8 @@ class C:
- key8: value8,
- key9: value9,
- } == expected, "Not what we expected"
-
+ NOT_YET_IMPLEMENTED_StmtAssert
- assert expected == {
- key1: value1,
- key2: value2,
@@ -279,7 +295,8 @@ class C:
- key8: value8,
- key9: value9,
- }, "Not what we expected"
-
+ NOT_YET_IMPLEMENTED_StmtAssert
- assert expected == {
- key1: value1,
- key2: value2,
@@ -291,8 +308,9 @@ class C:
- key8: value8,
- key9: value9,
- }
-
- def tricky_asserts(self) -> None:
+ NOT_YET_IMPLEMENTED_StmtAssert
def tricky_asserts(self) -> None:
- assert {
- key1: value1,
- key2: value2,
@@ -306,7 +324,8 @@ class C:
- } == expected(
- value, is_going_to_be="too long to fit in a single line", srsly=True
- ), "Not what we expected"
-
+ NOT_YET_IMPLEMENTED_StmtAssert
- assert {
- key1: value1,
- key2: value2,
@@ -320,7 +339,8 @@ class C:
- } == expected, (
- "Not what we expected and the message is too long to fit in one line"
- )
-
+ NOT_YET_IMPLEMENTED_StmtAssert
- assert expected(
- value, is_going_to_be="too long to fit in a single line", srsly=True
- ) == {
@@ -334,7 +354,8 @@ class C:
- key8: value8,
- key9: value9,
- }, "Not what we expected"
-
+ NOT_YET_IMPLEMENTED_StmtAssert
- assert expected == {
- key1: value1,
- key2: value2,
@@ -349,7 +370,8 @@ class C:
- "Not what we expected and the message is too long to fit in one line"
- " because it's too long"
- )
-
+ NOT_YET_IMPLEMENTED_StmtAssert
- dis_c_instance_method = """\
- %3d 0 LOAD_FAST 1 (x)
- 2 LOAD_CONST 1 (1)
@@ -360,8 +382,11 @@ class C:
- 12 RETURN_VALUE
- """ % (
- _C.__init__.__code__.co_firstlineno + 1,
- )
-
+ dis_c_instance_method = "NOT_YET_IMPLEMENTED_STRING" % (
+ _C.__init__.__code__.co_firstlineno
+ + 1,
)
- assert (
- expectedexpectedexpectedexpectedexpectedexpectedexpectedexpectedexpect
- == {
@@ -376,13 +401,58 @@ class C:
- key9: value9,
- }
- )
+NOT_YET_IMPLEMENTED_StmtClassDef
+ NOT_YET_IMPLEMENTED_StmtAssert
```
## Ruff Output
```py
NOT_YET_IMPLEMENTED_StmtClassDef
class C:
def test(self) -> None:
NOT_YET_IMPLEMENTED_StmtWith
xxxxxxxxxxxxxxxx = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
return "NOT_YET_IMPLEMENTED_STRING" % (
test.name,
test.filename,
lineno,
lname,
err,
)
def omitting_trailers(self) -> None:
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)[OneLevelIndex]
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)[OneLevelIndex][TwoLevelIndex][
ThreeLevelIndex
][
FourLevelIndex
]
d[0][1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18][19][20][21][
22
]
assignment = NOT_IMPLEMENTED_call() and another.rule.ending_with.index[123]
def easy_asserts(self) -> None:
NOT_YET_IMPLEMENTED_StmtAssert
NOT_YET_IMPLEMENTED_StmtAssert
NOT_YET_IMPLEMENTED_StmtAssert
def tricky_asserts(self) -> None:
NOT_YET_IMPLEMENTED_StmtAssert
NOT_YET_IMPLEMENTED_StmtAssert
NOT_YET_IMPLEMENTED_StmtAssert
NOT_YET_IMPLEMENTED_StmtAssert
dis_c_instance_method = "NOT_YET_IMPLEMENTED_STRING" % (
_C.__init__.__code__.co_firstlineno
+ 1,
)
NOT_YET_IMPLEMENTED_StmtAssert
```
## Black Output

View File

@@ -194,9 +194,9 @@ class C:
```diff
--- Black
+++ Ruff
@@ -1,181 +1 @@
-class C:
- def test(self) -> None:
@@ -1,181 +1,46 @@
class C:
def test(self) -> None:
- with patch("black.out", print):
- self.assertEqual(
- unstyle(str(report)), "1 file reformatted, 1 file failed to reformat."
@@ -239,23 +239,38 @@ class C:
- return (
- 'Utterly failed doctest test for %s\n File "%s", line %s, in %s\n\n%s'
- % (test.name, test.filename, lineno, lname, err)
- )
-
- def omitting_trailers(self) -> None:
+ NOT_YET_IMPLEMENTED_StmtWith
+ xxxxxxxxxxxxxxxx = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+ return "NOT_YET_IMPLEMENTED_STRING" % (
+ test.name,
+ test.filename,
+ lineno,
+ lname,
+ err,
)
def omitting_trailers(self) -> None:
- get_collection(
- hey_this_is_a_very_long_call, it_has_funny_attributes, really=True
- )[OneLevelIndex]
- get_collection(
- hey_this_is_a_very_long_call, it_has_funny_attributes, really=True
- )[OneLevelIndex][TwoLevelIndex][ThreeLevelIndex][FourLevelIndex]
- d[0][1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18][19][20][21][
- 22
- ]
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)[OneLevelIndex]
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)[OneLevelIndex][TwoLevelIndex][
+ ThreeLevelIndex
+ ][
+ FourLevelIndex
+ ]
d[0][1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18][19][20][21][
22
]
- assignment = (
- some.rather.elaborate.rule() and another.rule.ending_with.index[123]
- )
-
- def easy_asserts(self) -> None:
+ assignment = NOT_IMPLEMENTED_call() and another.rule.ending_with.index[123]
def easy_asserts(self) -> None:
- assert {
- key1: value1,
- key2: value2,
@@ -267,7 +282,8 @@ class C:
- key8: value8,
- key9: value9,
- } == expected, "Not what we expected"
-
+ NOT_YET_IMPLEMENTED_StmtAssert
- assert expected == {
- key1: value1,
- key2: value2,
@@ -279,7 +295,8 @@ class C:
- key8: value8,
- key9: value9,
- }, "Not what we expected"
-
+ NOT_YET_IMPLEMENTED_StmtAssert
- assert expected == {
- key1: value1,
- key2: value2,
@@ -291,8 +308,9 @@ class C:
- key8: value8,
- key9: value9,
- }
-
- def tricky_asserts(self) -> None:
+ NOT_YET_IMPLEMENTED_StmtAssert
def tricky_asserts(self) -> None:
- assert {
- key1: value1,
- key2: value2,
@@ -306,7 +324,8 @@ class C:
- } == expected(
- value, is_going_to_be="too long to fit in a single line", srsly=True
- ), "Not what we expected"
-
+ NOT_YET_IMPLEMENTED_StmtAssert
- assert {
- key1: value1,
- key2: value2,
@@ -320,7 +339,8 @@ class C:
- } == expected, (
- "Not what we expected and the message is too long to fit in one line"
- )
-
+ NOT_YET_IMPLEMENTED_StmtAssert
- assert expected(
- value, is_going_to_be="too long to fit in a single line", srsly=True
- ) == {
@@ -334,7 +354,8 @@ class C:
- key8: value8,
- key9: value9,
- }, "Not what we expected"
-
+ NOT_YET_IMPLEMENTED_StmtAssert
- assert expected == {
- key1: value1,
- key2: value2,
@@ -349,7 +370,8 @@ class C:
- "Not what we expected and the message is too long to fit in one line"
- " because it's too long"
- )
-
+ NOT_YET_IMPLEMENTED_StmtAssert
- dis_c_instance_method = """\
- %3d 0 LOAD_FAST 1 (x)
- 2 LOAD_CONST 1 (1)
@@ -360,8 +382,11 @@ class C:
- 12 RETURN_VALUE
- """ % (
- _C.__init__.__code__.co_firstlineno + 1,
- )
-
+ dis_c_instance_method = "NOT_YET_IMPLEMENTED_STRING" % (
+ _C.__init__.__code__.co_firstlineno
+ + 1,
)
- assert (
- expectedexpectedexpectedexpectedexpectedexpectedexpectedexpectedexpect
- == {
@@ -376,13 +401,58 @@ class C:
- key9: value9,
- }
- )
+NOT_YET_IMPLEMENTED_StmtClassDef
+ NOT_YET_IMPLEMENTED_StmtAssert
```
## Ruff Output
```py
NOT_YET_IMPLEMENTED_StmtClassDef
class C:
def test(self) -> None:
NOT_YET_IMPLEMENTED_StmtWith
xxxxxxxxxxxxxxxx = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
return "NOT_YET_IMPLEMENTED_STRING" % (
test.name,
test.filename,
lineno,
lname,
err,
)
def omitting_trailers(self) -> None:
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)[OneLevelIndex]
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)[OneLevelIndex][TwoLevelIndex][
ThreeLevelIndex
][
FourLevelIndex
]
d[0][1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18][19][20][21][
22
]
assignment = NOT_IMPLEMENTED_call() and another.rule.ending_with.index[123]
def easy_asserts(self) -> None:
NOT_YET_IMPLEMENTED_StmtAssert
NOT_YET_IMPLEMENTED_StmtAssert
NOT_YET_IMPLEMENTED_StmtAssert
def tricky_asserts(self) -> None:
NOT_YET_IMPLEMENTED_StmtAssert
NOT_YET_IMPLEMENTED_StmtAssert
NOT_YET_IMPLEMENTED_StmtAssert
NOT_YET_IMPLEMENTED_StmtAssert
dis_c_instance_method = "NOT_YET_IMPLEMENTED_STRING" % (
_C.__init__.__code__.co_firstlineno
+ 1,
)
NOT_YET_IMPLEMENTED_StmtAssert
```
## Black Output

View File

@@ -17,12 +17,12 @@ class ClassWithDocstring:
```diff
--- Black
+++ Ruff
@@ -1,4 +1,3 @@
@@ -1,4 +1,4 @@
# Make sure when the file ends with class's docstring,
# It doesn't add extra blank lines.
-class ClassWithDocstring:
class ClassWithDocstring:
- """A docstring."""
+NOT_YET_IMPLEMENTED_StmtClassDef
+ "NOT_YET_IMPLEMENTED_STRING"
```
## Ruff Output
@@ -30,7 +30,8 @@ class ClassWithDocstring:
```py
# Make sure when the file ends with class's docstring,
# It doesn't add extra blank lines.
NOT_YET_IMPLEMENTED_StmtClassDef
class ClassWithDocstring:
"NOT_YET_IMPLEMENTED_STRING"
```
## Black Output

View File

@@ -234,18 +234,19 @@ def stable_quote_normalization_with_immediate_inner_single_quote(self):
```diff
--- Black
+++ Ruff
@@ -1,219 +1,149 @@
-class MyClass:
@@ -1,219 +1,154 @@
class MyClass:
- """Multiline
- class docstring
- """
-
- def method(self):
+ "NOT_YET_IMPLEMENTED_STRING"
def method(self):
- """Multiline
- method docstring
- """
- pass
+NOT_YET_IMPLEMENTED_StmtClassDef
+ "NOT_YET_IMPLEMENTED_STRING"
pass
def foo():
@@ -396,12 +397,12 @@ def stable_quote_normalization_with_immediate_inner_single_quote(self):
- tab at start of line and then a tab separated value
- multiple tabs at the beginning and inline
- mixed tabs and spaces at beginning. next line has mixed tabs and spaces only.
-
- line ends with some tabs
- """
+ "NOT_YET_IMPLEMENTED_STRING"
- line ends with some tabs
- """
-
def docstring_with_inline_tabs_and_tab_indentation():
- """hey
-
@@ -494,7 +495,12 @@ def stable_quote_normalization_with_immediate_inner_single_quote(self):
## Ruff Output
```py
NOT_YET_IMPLEMENTED_StmtClassDef
class MyClass:
"NOT_YET_IMPLEMENTED_STRING"
def method(self):
"NOT_YET_IMPLEMENTED_STRING"
pass
def foo():

View File

@@ -137,7 +137,7 @@ def g():
if not prev:
- prevp = preceding_leaf(p)
- if not prevp or prevp.type in OPENING_BRACKETS:
+ prevp = NOT_IMPLEMENTED_call()
+ prevp = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+ if not prevp or NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right:
return NO
@@ -199,7 +199,7 @@ def g():
prev = leaf.prev_sibling
if not prev:
- prevp = preceding_leaf(p)
+ prevp = NOT_IMPLEMENTED_call()
+ prevp = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
- if not prevp or prevp.type in OPENING_BRACKETS:
+ if not prevp or NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right:
@@ -245,7 +245,7 @@ def f():
prev = leaf.prev_sibling
if not prev:
prevp = NOT_IMPLEMENTED_call()
prevp = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
if not prevp or NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right:
return NO
@@ -283,7 +283,7 @@ def g():
prev = leaf.prev_sibling
if not prev:
prevp = NOT_IMPLEMENTED_call()
prevp = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
if not prevp or NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right:
# Start of the line or a bracketed expression.

View File

@@ -431,18 +431,18 @@ last_call()
+NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right
+NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right
+NOT_IMPLEMENTED_call()
+NOT_IMPLEMENTED_call()
+NOT_IMPLEMENTED_call()
+NOT_IMPLEMENTED_call()
+NOT_IMPLEMENTED_call()
+NOT_IMPLEMENTED_call() # note: no trailing comma pre-3.6
+NOT_IMPLEMENTED_call()
+NOT_IMPLEMENTED_call()
+NOT_IMPLEMENTED_call()
+NOT_IMPLEMENTED_call()
+NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg) # note: no trailing comma pre-3.6
+NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
lukasz.langa.pl
-call.me(maybe)
+NOT_IMPLEMENTED_call()
+NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
(1).real
(1.0).real
....__class__
@@ -454,9 +454,6 @@ last_call()
- int,
- float,
- dict[str, int],
-]
-very_long_variable_name_filters: t.List[
- t.Tuple[str, t.Union[str, t.List[t.Optional[str]]]],
+ (
+ str,
+ int,
@@ -464,6 +461,9 @@ last_call()
+ dict[str, int],
+ )
]
-very_long_variable_name_filters: t.List[
- t.Tuple[str, t.Union[str, t.List[t.Optional[str]]]],
-]
-xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = classmethod( # type: ignore
- sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__)
-)
@@ -494,7 +494,7 @@ last_call()
numpy[0, :]
numpy[:, i]
numpy[0, :2]
@@ -171,62 +158,58 @@
@@ -171,62 +158,59 @@
numpy[1 : c + 1, c]
numpy[-(c + 1) :, d]
numpy[:, l[-2]]
@@ -541,7 +541,8 @@ last_call()
+ "NOT_YET_IMPLEMENTED_STRING": "NOT_YET_IMPLEMENTED_STRING",
+ "NOT_YET_IMPLEMENTED_STRING": "NOT_YET_IMPLEMENTED_STRING",
+ "NOT_YET_IMPLEMENTED_STRING": NOT_IMPLEMENTED_call(),
+ "NOT_YET_IMPLEMENTED_STRING": NOT_IMPLEMENTED_call() + NOT_IMPLEMENTED_call(),
+ "NOT_YET_IMPLEMENTED_STRING": NOT_IMPLEMENTED_call()
+ + NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg),
+ "NOT_YET_IMPLEMENTED_STRING": 1,
+ "NOT_YET_IMPLEMENTED_STRING": 1,
**kwargs,
@@ -555,16 +556,19 @@ last_call()
-g = 1, *"ten"
-what_is_up_with_those_new_coord_names = (coord_names + set(vars_to_create)) + set(
- vars_to_remove
+e = NOT_IMPLEMENTED_call()
+e = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+f = 1, NOT_YET_IMPLEMENTED_ExprStarred
+g = 1, NOT_YET_IMPLEMENTED_ExprStarred
+what_is_up_with_those_new_coord_names = (
+ (coord_names + NOT_IMPLEMENTED_call())
+ + NOT_IMPLEMENTED_call()
+ (coord_names + NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg))
+ + NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
)
-what_is_up_with_those_new_coord_names = (coord_names | set(vars_to_create)) - set(
- vars_to_remove
-)
+what_is_up_with_those_new_coord_names = (
+ (coord_names | NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg))
+ - NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
)
-result = (
- session.query(models.Customer.id)
- .filter(
@@ -582,10 +586,7 @@ last_call()
- models.Customer.id.asc(),
- )
- .all()
+what_is_up_with_those_new_coord_names = (
+ (coord_names | NOT_IMPLEMENTED_call())
+ - NOT_IMPLEMENTED_call()
)
-)
-Ø = set()
-authors.łukasz.say_thanks()
+result = NOT_IMPLEMENTED_call()
@@ -595,7 +596,7 @@ last_call()
mapping = {
A: 0.25 * (10.0 / 12),
B: 0.1 * (10.0 / 12),
@@ -236,31 +219,29 @@
@@ -236,31 +220,29 @@
def gen():
@@ -611,7 +612,7 @@ last_call()
async def f():
- await some.complicated[0].call(with_args=(True or (1 is not 1)))
+ await NOT_IMPLEMENTED_call()
+ await NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
-print(*[] or [1])
@@ -622,9 +623,9 @@ last_call()
- force=False
-), "Short message"
-assert parens is TooMany
+NOT_IMPLEMENTED_call()
+NOT_IMPLEMENTED_call()
+NOT_IMPLEMENTED_call()
+NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+NOT_YET_IMPLEMENTED_StmtAssert
+NOT_YET_IMPLEMENTED_StmtAssert
+NOT_YET_IMPLEMENTED_StmtAssert
@@ -640,12 +641,12 @@ last_call()
...
for j in 1 + (2 + 3):
...
@@ -272,28 +253,16 @@
@@ -272,28 +254,16 @@
addr_proto,
addr_canonname,
addr_sockaddr,
-) in socket.getaddrinfo("google.com", "http"):
+) in NOT_IMPLEMENTED_call():
+) in NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg):
pass
-a = (
- aaaa.bbbb.cccc.dddd.eeee.ffff.gggg.hhhh.iiii.jjjj.kkkk.llll.mmmm.nnnn.oooo.pppp
@@ -677,7 +678,7 @@ last_call()
):
return True
if (
@@ -327,13 +296,18 @@
@@ -327,13 +297,18 @@
):
return True
if (
@@ -699,7 +700,7 @@ last_call()
^ aaaaaaaa.i << aaaaaaaa.k >> aaaaaaaa.l**aaaaaaaa.m // aaaaaaaa.n
):
return True
@@ -341,7 +315,8 @@
@@ -341,7 +316,8 @@
~aaaaaaaaaaaaaaaa.a
+ aaaaaaaaaaaaaaaa.b
- aaaaaaaaaaaaaaaa.c * aaaaaaaaaaaaaaaa.d @ aaaaaaaaaaaaaaaa.e
@@ -709,7 +710,7 @@ last_call()
^ aaaaaaaaaaaaaaaa.i
<< aaaaaaaaaaaaaaaa.k
>> aaaaaaaaaaaaaaaa.l**aaaaaaaaaaaaaaaa.m // aaaaaaaaaaaaaaaa.n
@@ -366,5 +341,5 @@
@@ -366,5 +342,5 @@
^ bbbb.a & aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
^ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
)
@@ -827,17 +828,17 @@ NOT_YET_IMPLEMENTED_ExprSetComp
NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right
NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call() # note: no trailing comma pre-3.6
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg) # note: no trailing comma pre-3.6
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
lukasz.langa.pl
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
(1).real
(1.0).real
....__class__
@@ -909,7 +910,8 @@ SomeName
"NOT_YET_IMPLEMENTED_STRING": "NOT_YET_IMPLEMENTED_STRING",
"NOT_YET_IMPLEMENTED_STRING": "NOT_YET_IMPLEMENTED_STRING",
"NOT_YET_IMPLEMENTED_STRING": NOT_IMPLEMENTED_call(),
"NOT_YET_IMPLEMENTED_STRING": NOT_IMPLEMENTED_call() + NOT_IMPLEMENTED_call(),
"NOT_YET_IMPLEMENTED_STRING": NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg),
"NOT_YET_IMPLEMENTED_STRING": 1,
"NOT_YET_IMPLEMENTED_STRING": 1,
**kwargs,
@@ -918,16 +920,16 @@ a = (1,)
b = (1,)
c = 1
d = (1,) + a + (2,)
e = NOT_IMPLEMENTED_call()
e = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
f = 1, NOT_YET_IMPLEMENTED_ExprStarred
g = 1, NOT_YET_IMPLEMENTED_ExprStarred
what_is_up_with_those_new_coord_names = (
(coord_names + NOT_IMPLEMENTED_call())
+ NOT_IMPLEMENTED_call()
(coord_names + NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg))
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
)
what_is_up_with_those_new_coord_names = (
(coord_names | NOT_IMPLEMENTED_call())
- NOT_IMPLEMENTED_call()
(coord_names | NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg))
- NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
)
result = NOT_IMPLEMENTED_call()
result = NOT_IMPLEMENTED_call()
@@ -949,12 +951,12 @@ def gen():
async def f():
await NOT_IMPLEMENTED_call()
await NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
NOT_YET_IMPLEMENTED_StmtAssert
NOT_YET_IMPLEMENTED_StmtAssert
NOT_YET_IMPLEMENTED_StmtAssert
@@ -976,7 +978,7 @@ for (
addr_proto,
addr_canonname,
addr_sockaddr,
) in NOT_IMPLEMENTED_call():
) in NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg):
pass
a = NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right
a = NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right

View File

@@ -73,7 +73,7 @@ def test_calculate_fades():
- ('stuff', 'in')
- ],
-])
+@NOT_IMPLEMENTED_call()
+@NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
def test_fader(test):
pass
@@ -122,7 +122,7 @@ TmEx = 2
# Test data:
# Position, Volume, State, TmSt/TmEx/None, [call, [arg1...]]
@NOT_IMPLEMENTED_call()
@NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
def test_fader(test):
pass

View File

@@ -32,7 +32,7 @@ def f(): pass
- 1, 2,
- 3, 4,
-])
+@NOT_IMPLEMENTED_call()
+@NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# fmt: on
def f():
pass
@@ -46,7 +46,7 @@ def f(): pass
- 4,
- ]
-)
+@NOT_IMPLEMENTED_call()
+@NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
def f():
pass
```
@@ -55,13 +55,13 @@ def f(): pass
```py
# fmt: off
@NOT_IMPLEMENTED_call()
@NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# fmt: on
def f():
pass
@NOT_IMPLEMENTED_call()
@NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
def f():
pass
```

View File

@@ -109,7 +109,7 @@ elif unformatted:
- ] # Includes an formatted indentation.
- },
-)
+NOT_IMPLEMENTED_call()
+NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# Regression test for https://github.com/psf/black/issues/2015.
@@ -123,18 +123,18 @@ elif unformatted:
- + path,
- check=True,
-)
+NOT_IMPLEMENTED_call()
+NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# Regression test for https://github.com/psf/black/issues/3026.
def test_func():
# yapf: disable
- if unformatted( args ):
+ if NOT_IMPLEMENTED_call():
+ if NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg):
return True
# yapf: enable
elif b:
@@ -39,49 +21,29 @@
@@ -39,12 +21,12 @@
# Regression test for https://github.com/psf/black/issues/2567.
if True:
# fmt: off
@@ -142,50 +142,54 @@ elif unformatted:
- # fmt: on
- print ( "This won't be formatted" )
- print ( "This won't be formatted either" )
+ for _ in NOT_IMPLEMENTED_call():
+ for _ in NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg):
+ # fmt: on
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
else:
- print("This will be formatted")
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# Regression test for https://github.com/psf/black/issues/3184.
-class A:
- async def call(param):
- if param:
- # fmt: off
@@ -52,29 +34,27 @@
async def call(param):
if param:
# fmt: off
- if param[0:4] in (
- "ABCD", "EFGH"
- ) :
- # fmt: on
+ if NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right:
# fmt: on
- print ( "This won't be formatted" )
-
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
- elif param[0:4] in ("ZZZZ",):
- print ( "This won't be formatted either" )
-
+ elif NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right:
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
- print("This will be formatted")
+NOT_YET_IMPLEMENTED_StmtClassDef
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# Regression test for https://github.com/psf/black/issues/2985.
-class Named(t.Protocol):
- # fmt: off
- @property
class Named(t.Protocol):
# fmt: off
@property
- def this_wont_be_formatted ( self ) -> str: ...
+NOT_YET_IMPLEMENTED_StmtClassDef
+ def this_wont_be_formatted(self) -> str:
+ ...
-class Factory(t.Protocol):
- def this_will_be_formatted(self, **kwargs) -> Named:
- ...
class Factory(t.Protocol):
def this_will_be_formatted(self, **kwargs) -> Named:
...
-
- # fmt: on
+NOT_YET_IMPLEMENTED_StmtClassDef
# fmt: on
# Regression test for https://github.com/psf/black/issues/3436.
@@ -82,6 +62,6 @@
if x:
return x
# fmt: off
@@ -200,17 +204,17 @@ elif unformatted:
```py
# Regression test for https://github.com/psf/black/issues/3129.
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# Regression test for https://github.com/psf/black/issues/2015.
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# Regression test for https://github.com/psf/black/issues/3026.
def test_func():
# yapf: disable
if NOT_IMPLEMENTED_call():
if NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg):
return True
# yapf: enable
elif b:
@@ -222,23 +226,41 @@ def test_func():
# Regression test for https://github.com/psf/black/issues/2567.
if True:
# fmt: off
for _ in NOT_IMPLEMENTED_call():
for _ in NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg):
# fmt: on
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
else:
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# Regression test for https://github.com/psf/black/issues/3184.
NOT_YET_IMPLEMENTED_StmtClassDef
class A:
async def call(param):
if param:
# fmt: off
if NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right:
# fmt: on
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
elif NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right:
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# Regression test for https://github.com/psf/black/issues/2985.
NOT_YET_IMPLEMENTED_StmtClassDef
class Named(t.Protocol):
# fmt: off
@property
def this_wont_be_formatted(self) -> str:
...
NOT_YET_IMPLEMENTED_StmtClassDef
class Factory(t.Protocol):
def this_will_be_formatted(self, **kwargs) -> Named:
...
# fmt: on
# Regression test for https://github.com/psf/black/issues/3436.

View File

@@ -241,10 +241,10 @@ d={'a':1,
+ NOT_YET_IMPLEMENTED_StmtRaise
+ if False:
+ ...
+ for i in NOT_IMPLEMENTED_call():
+ NOT_IMPLEMENTED_call()
+ for i in NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg):
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+ continue
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+ return None
+
+
@@ -255,7 +255,7 @@ d={'a':1,
- await asyncio.sleep(1)
+ "NOT_YET_IMPLEMENTED_STRING"
+ NOT_YET_IMPLEMENTED_StmtAsyncWith
+ await NOT_IMPLEMENTED_call()
+ await NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+
+
@asyncio.coroutine
@@ -265,7 +265,7 @@ d={'a':1,
-)
-def function_signature_stress_test(number:int,no_annotation=None,text:str='default',* ,debug:bool=False,**kwargs) -> str:
- return text[number:-1]
+@NOT_IMPLEMENTED_call()
+@NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+def function_signature_stress_test(
+ number: int,
+ no_annotation=None,
@@ -292,7 +292,7 @@ d={'a':1,
+ h="NOT_YET_IMPLEMENTED_STRING",
+ i="NOT_YET_IMPLEMENTED_STRING",
+):
+ offset = NOT_IMPLEMENTED_call()
+ offset = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+ NOT_YET_IMPLEMENTED_StmtAssert
@@ -312,7 +312,7 @@ d={'a':1,
-def spaces2(result=_core.Value(None)):
+def spaces2(result=NOT_IMPLEMENTED_call()):
+def spaces2(result=NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)):
...
@@ -429,7 +429,7 @@ d={'a':1,
- implicit_default=True,
- )
- )
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# fmt: off
- a = (
- unnecessary_bracket()
@@ -460,7 +460,7 @@ d={'a':1,
- re.MULTILINE|re.VERBOSE
- # fmt: on
- )
+ _type_comment_re = NOT_IMPLEMENTED_call()
+ _type_comment_re = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
def single_literal_yapf_disable():
@@ -496,7 +496,7 @@ d={'a':1,
- # fmt: on
- xxxxxxxxxx_xxxxxxxxxxx_xxxxxxx_xxxxxxxxx=5,
-)
+NOT_IMPLEMENTED_call()
+NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# fmt: off
-yield 'hello'
+NOT_YET_IMPLEMENTED_ExprYield
@@ -536,21 +536,21 @@ def func_no_args():
NOT_YET_IMPLEMENTED_StmtRaise
if False:
...
for i in NOT_IMPLEMENTED_call():
NOT_IMPLEMENTED_call()
for i in NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg):
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
continue
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
return None
async def coroutine(arg, exec=False):
"NOT_YET_IMPLEMENTED_STRING"
NOT_YET_IMPLEMENTED_StmtAsyncWith
await NOT_IMPLEMENTED_call()
await NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
@asyncio.coroutine
@NOT_IMPLEMENTED_call()
@NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
def function_signature_stress_test(
number: int,
no_annotation=None,
@@ -574,7 +574,7 @@ def spaces(
h="NOT_YET_IMPLEMENTED_STRING",
i="NOT_YET_IMPLEMENTED_STRING",
):
offset = NOT_IMPLEMENTED_call()
offset = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
NOT_YET_IMPLEMENTED_StmtAssert
@@ -592,7 +592,7 @@ def spaces_types(
...
def spaces2(result=NOT_IMPLEMENTED_call()):
def spaces2(result=NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)):
...
@@ -674,11 +674,11 @@ def on_and_off_broken():
def long_lines():
if True:
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# fmt: off
a = NOT_IMPLEMENTED_call()
# fmt: on
_type_comment_re = NOT_IMPLEMENTED_call()
_type_comment_re = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
def single_literal_yapf_disable():
@@ -686,7 +686,7 @@ def single_literal_yapf_disable():
BAZ = {(1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12)} # yapf: disable
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# fmt: off
NOT_YET_IMPLEMENTED_ExprYield
# No formatting to the end of the file

View File

@@ -33,10 +33,10 @@ else:
+ and NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right
):
- print("I'm good!")
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
else:
- print("I'm bad")
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
```
## Ruff Output
@@ -48,9 +48,9 @@ if (
and NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right # fmt: skip
and NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right
):
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
else:
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
```
## Black Output

View File

@@ -18,19 +18,23 @@ class A:
```diff
--- Black
+++ Ruff
@@ -1,5 +1 @@
-class A:
- def f(self):
@@ -1,5 +1,5 @@
class A:
def f(self):
- for line in range(10):
- if True:
- pass # fmt: skip
+NOT_YET_IMPLEMENTED_StmtClassDef
+ for line in NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg):
if True:
pass # fmt: skip
```
## Ruff Output
```py
NOT_YET_IMPLEMENTED_StmtClassDef
class A:
def f(self):
for line in NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg):
if True:
pass # fmt: skip
```
## Black Output

View File

@@ -75,12 +75,12 @@ async def test_async_with():
```diff
--- Black
+++ Ruff
@@ -1,62 +1,47 @@
@@ -1,62 +1,54 @@
# Make sure a leading comment is not removed.
-def some_func( unformatted, args ): # fmt: skip
- print("I am some_func")
+def some_func(unformatted, args): # fmt: skip
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
return 0
# Make sure this comment is not removed.
@@ -90,48 +90,53 @@ async def test_async_with():
- print("I am some_async_func")
- await asyncio.sleep(1)
+async def some_async_func(unformatted, args): # fmt: skip
+ NOT_IMPLEMENTED_call()
+ await NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+ await NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# Make sure a leading comment is not removed.
-class SomeClass( Unformatted, SuperClasses ): # fmt: skip
- def some_method( self, unformatted, args ): # fmt: skip
- print("I am some_method")
- return 0
+NOT_YET_IMPLEMENTED_StmtClassDef
+class SomeClass(Unformatted, SuperClasses): # fmt: skip
+ def some_method(self, unformatted, args): # fmt: skip
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
return 0
- async def some_async_method( self, unformatted, args ): # fmt: skip
- print("I am some_async_method")
- await asyncio.sleep(1)
+ async def some_async_method(self, unformatted, args): # fmt: skip
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+ await NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
-
# Make sure a leading comment is not removed.
-if unformatted_call( args ): # fmt: skip
- print("First branch")
+if NOT_IMPLEMENTED_call(): # fmt: skip
+ NOT_IMPLEMENTED_call()
+if NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg): # fmt: skip
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# Make sure this is not removed.
-elif another_unformatted_call( args ): # fmt: skip
- print("Second branch")
-else : # fmt: skip
- print("Last branch")
+elif NOT_IMPLEMENTED_call(): # fmt: skip
+ NOT_IMPLEMENTED_call()
+elif NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg): # fmt: skip
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+else: # fmt: skip
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
-while some_condition( unformatted, args ): # fmt: skip
- print("Do something")
+while NOT_IMPLEMENTED_call(): # fmt: skip
+ NOT_IMPLEMENTED_call()
+while NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg): # fmt: skip
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
-for i in some_iter( unformatted, args ): # fmt: skip
- print("Do something")
+for i in NOT_IMPLEMENTED_call(): # fmt: skip
+ NOT_IMPLEMENTED_call()
+for i in NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg): # fmt: skip
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
async def test_async_for():
@@ -165,37 +170,44 @@ async def test_async_with():
```py
# Make sure a leading comment is not removed.
def some_func(unformatted, args): # fmt: skip
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
return 0
# Make sure this comment is not removed.
# Make sure a leading comment is not removed.
async def some_async_func(unformatted, args): # fmt: skip
NOT_IMPLEMENTED_call()
await NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
await NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# Make sure a leading comment is not removed.
NOT_YET_IMPLEMENTED_StmtClassDef
class SomeClass(Unformatted, SuperClasses): # fmt: skip
def some_method(self, unformatted, args): # fmt: skip
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
return 0
async def some_async_method(self, unformatted, args): # fmt: skip
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
await NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# Make sure a leading comment is not removed.
if NOT_IMPLEMENTED_call(): # fmt: skip
NOT_IMPLEMENTED_call()
if NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg): # fmt: skip
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# Make sure this is not removed.
elif NOT_IMPLEMENTED_call(): # fmt: skip
NOT_IMPLEMENTED_call()
elif NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg): # fmt: skip
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
else: # fmt: skip
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
while NOT_IMPLEMENTED_call(): # fmt: skip
NOT_IMPLEMENTED_call()
while NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg): # fmt: skip
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
for i in NOT_IMPLEMENTED_call(): # fmt: skip
NOT_IMPLEMENTED_call()
for i in NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg): # fmt: skip
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
async def test_async_for():

View File

@@ -66,7 +66,7 @@ with hmm_but_this_should_get_two_preceding_newlines():
```diff
--- Black
+++ Ruff
@@ -2,64 +2,39 @@
@@ -2,64 +2,41 @@
a,
**kwargs,
) -> A:
@@ -82,8 +82,8 @@ with hmm_but_this_should_get_two_preceding_newlines():
- **kwargs,
- )
+ NOT_YET_IMPLEMENTED_StmtWith
+ NOT_IMPLEMENTED_call() # negate top
+ return NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg) # negate top
+ return NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
def g():
@@ -94,7 +94,7 @@ with hmm_but_this_should_get_two_preceding_newlines():
pass
- print("Inner defs should breathe a little.")
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
def h():
@@ -102,7 +102,7 @@ with hmm_but_this_should_get_two_preceding_newlines():
pass
- print("Inner defs should breathe a little.")
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
-if os.name == "posix":
@@ -129,17 +129,17 @@ with hmm_but_this_should_get_two_preceding_newlines():
elif False:
-
- class IHopeYouAreHavingALovelyDay:
- def __call__(self):
class IHopeYouAreHavingALovelyDay:
def __call__(self):
- print("i_should_be_followed_by_only_one_newline")
-
+ NOT_YET_IMPLEMENTED_StmtClassDef
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
else:
-
def foo():
pass
-
-with hmm_but_this_should_get_two_preceding_newlines():
- pass
+NOT_YET_IMPLEMENTED_StmtWith
@@ -153,8 +153,8 @@ def f(
**kwargs,
) -> A:
NOT_YET_IMPLEMENTED_StmtWith
NOT_IMPLEMENTED_call() # negate top
return NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg) # negate top
return NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
def g():
@@ -163,14 +163,14 @@ def g():
def inner():
pass
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
def h():
def inner():
pass
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
if NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right:
@@ -182,7 +182,9 @@ elif NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right:
NOT_YET_IMPLEMENTED_StmtTry
elif False:
NOT_YET_IMPLEMENTED_StmtClassDef
class IHopeYouAreHavingALovelyDay:
def __call__(self):
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
else:
def foo():
pass

View File

@@ -136,11 +136,11 @@ def __await__(): return (yield)
...
- for i in range(10):
- print(i)
+ for i in NOT_IMPLEMENTED_call():
+ NOT_IMPLEMENTED_call()
+ for i in NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg):
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
continue
- exec("new-style exec", {}, {})
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
return None
@@ -151,12 +151,12 @@ def __await__(): return (yield)
- await asyncio.sleep(1)
+ "NOT_YET_IMPLEMENTED_STRING"
+ NOT_YET_IMPLEMENTED_StmtAsyncWith
+ await NOT_IMPLEMENTED_call()
+ await NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
@asyncio.coroutine
-@some_decorator(with_args=True, many_args=[1, 2, 3])
+@NOT_IMPLEMENTED_call()
+@NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
def function_signature_stress_test(
number: int,
no_annotation=None,
@@ -184,7 +184,7 @@ def __await__(): return (yield)
+ h="NOT_YET_IMPLEMENTED_STRING",
+ i="NOT_YET_IMPLEMENTED_STRING",
+):
+ offset = NOT_IMPLEMENTED_call()
+ offset = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+ NOT_YET_IMPLEMENTED_StmtAssert
@@ -205,7 +205,7 @@ def __await__(): return (yield)
-def spaces2(result=_core.Value(None)):
- assert fut is self._read_fut, (fut, self._read_fut)
+def spaces2(result=NOT_IMPLEMENTED_call()):
+def spaces2(result=NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)):
+ NOT_YET_IMPLEMENTED_StmtAssert
@@ -263,9 +263,9 @@ def __await__(): return (yield)
- """,
- re.MULTILINE | re.VERBOSE,
- )
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call()
+ _type_comment_re = NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+ _type_comment_re = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
def trailing_comma():
@@ -309,21 +309,21 @@ def func_no_args():
NOT_YET_IMPLEMENTED_StmtRaise
if False:
...
for i in NOT_IMPLEMENTED_call():
NOT_IMPLEMENTED_call()
for i in NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg):
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
continue
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
return None
async def coroutine(arg, exec=False):
"NOT_YET_IMPLEMENTED_STRING"
NOT_YET_IMPLEMENTED_StmtAsyncWith
await NOT_IMPLEMENTED_call()
await NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
@asyncio.coroutine
@NOT_IMPLEMENTED_call()
@NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
def function_signature_stress_test(
number: int,
no_annotation=None,
@@ -346,7 +346,7 @@ def spaces(
h="NOT_YET_IMPLEMENTED_STRING",
i="NOT_YET_IMPLEMENTED_STRING",
):
offset = NOT_IMPLEMENTED_call()
offset = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
NOT_YET_IMPLEMENTED_StmtAssert
@@ -364,7 +364,7 @@ def spaces_types(
...
def spaces2(result=NOT_IMPLEMENTED_call()):
def spaces2(result=NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)):
NOT_YET_IMPLEMENTED_StmtAssert
@@ -374,9 +374,9 @@ def example(session):
def long_lines():
if True:
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call()
_type_comment_re = NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
_type_comment_re = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
def trailing_comma():

View File

@@ -106,8 +106,8 @@ some_module.some_function(
- call2(
- arg=[1, 2, 3],
- )
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
x = {
- "a": 1,
- "b": 2,
@@ -161,7 +161,7 @@ some_module.some_function(
- this_shouldn_t_get_a_trailing_comma_too
- )
-):
+def func() -> NOT_IMPLEMENTED_call():
+def func() -> NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg):
pass
@@ -170,7 +170,7 @@ some_module.some_function(
- this_shouldn_t_get_a_trailing_comma_too
- )
-):
+def func() -> NOT_IMPLEMENTED_call():
+def func() -> NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg):
pass
@@ -178,7 +178,7 @@ some_module.some_function(
-some_module.some_function(
- argument1, (one_element_tuple,), argument4, argument5, argument6
-)
+NOT_IMPLEMENTED_call()
+NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# Inner trailing comma causes outer to explode
-some_module.some_function(
@@ -191,7 +191,7 @@ some_module.some_function(
- argument5,
- argument6,
-)
+NOT_IMPLEMENTED_call()
+NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
```
## Ruff Output
@@ -223,8 +223,8 @@ def f2(
def f(
a: int = 1,
):
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
x = {
"NOT_YET_IMPLEMENTED_STRING": 1,
"NOT_YET_IMPLEMENTED_STRING": 2,
@@ -257,19 +257,19 @@ def some_method_with_a_really_long_name(
pass
def func() -> NOT_IMPLEMENTED_call():
def func() -> NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg):
pass
def func() -> NOT_IMPLEMENTED_call():
def func() -> NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg):
pass
# Make sure inner one-element tuple won't explode
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# Inner trailing comma causes outer to explode
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
```
## Black Output

View File

@@ -87,7 +87,7 @@ return np.divide(
-e = lazy(lambda **kwargs: 5)
-f = f() ** 5
+d = 5 ** f["NOT_YET_IMPLEMENTED_STRING"]
+e = NOT_IMPLEMENTED_call()
+e = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+f = NOT_IMPLEMENTED_call() ** 5
g = a.b**c.d
-h = 5 ** funcs.f()
@@ -106,7 +106,7 @@ return np.divide(
-p = {(k, k**2): v**2 for k, v in pairs}
-q = [10**i for i in range(6)]
+n = NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right
+o = NOT_IMPLEMENTED_call()
+o = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+p = {NOT_IMPLEMENTED_dict_key: NOT_IMPLEMENTED_dict_value for key, value in NOT_IMPLEMENTED_dict}
+q = [i for i in []]
r = x**y
@@ -119,7 +119,7 @@ return np.divide(
-e = lazy(lambda **kwargs: 5)
-f = f() ** 5.0
+d = 5.0 ** f["NOT_YET_IMPLEMENTED_STRING"]
+e = NOT_IMPLEMENTED_call()
+e = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+f = NOT_IMPLEMENTED_call() ** 5.0
g = a.b**c.d
-h = 5.0 ** funcs.f()
@@ -138,7 +138,7 @@ return np.divide(
-p = {(k, k**2): v**2.0 for k, v in pairs}
-q = [10.5**i for i in range(6)]
+n = NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right
+o = NOT_IMPLEMENTED_call()
+o = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+p = {NOT_IMPLEMENTED_dict_key: NOT_IMPLEMENTED_dict_value for key, value in NOT_IMPLEMENTED_dict}
+q = [i for i in []]
@@ -151,13 +151,13 @@ return np.divide(
- out=np.full(view.sum_of_weights.shape, np.nan), # type: ignore[union-attr]
- where=view.sum_of_weights**2 > view.sum_of_weights_squared, # type: ignore[union-attr]
- )
+if NOT_IMPLEMENTED_call():
+ return NOT_IMPLEMENTED_call()
+if NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg):
+ return NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
-return np.divide(
- where=view.sum_of_weights_of_weight_long**2 > view.sum_of_weights_squared, # type: ignore
-)
+return NOT_IMPLEMENTED_call()
+return NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
```
## Ruff Output
@@ -180,7 +180,7 @@ a = 5**~4
b = 5 ** NOT_IMPLEMENTED_call()
c = -(5**2)
d = 5 ** f["NOT_YET_IMPLEMENTED_STRING"]
e = NOT_IMPLEMENTED_call()
e = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
f = NOT_IMPLEMENTED_call() ** 5
g = a.b**c.d
h = 5 ** NOT_IMPLEMENTED_call()
@@ -190,7 +190,7 @@ k = [i for i in []]
l = NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right
m = [([2**63], [1, 2**63])]
n = NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right
o = NOT_IMPLEMENTED_call()
o = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
p = {NOT_IMPLEMENTED_dict_key: NOT_IMPLEMENTED_dict_value for key, value in NOT_IMPLEMENTED_dict}
q = [i for i in []]
r = x**y
@@ -199,7 +199,7 @@ a = 5.0**~4.0
b = 5.0 ** NOT_IMPLEMENTED_call()
c = -(5.0**2.0)
d = 5.0 ** f["NOT_YET_IMPLEMENTED_STRING"]
e = NOT_IMPLEMENTED_call()
e = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
f = NOT_IMPLEMENTED_call() ** 5.0
g = a.b**c.d
h = 5.0 ** NOT_IMPLEMENTED_call()
@@ -209,16 +209,16 @@ k = [i for i in []]
l = NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right
m = [([2.0**63.0], [1.0, 2**63.0])]
n = NOT_IMPLEMENTED_left < NOT_IMPLEMENTED_right
o = NOT_IMPLEMENTED_call()
o = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
p = {NOT_IMPLEMENTED_dict_key: NOT_IMPLEMENTED_dict_value for key, value in NOT_IMPLEMENTED_dict}
q = [i for i in []]
# WE SHOULD DEFINITELY NOT EAT THESE COMMENTS (https://github.com/psf/black/issues/2873)
if NOT_IMPLEMENTED_call():
return NOT_IMPLEMENTED_call()
if NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg):
return NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
return NOT_IMPLEMENTED_call()
return NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
```
## Black Output

View File

@@ -25,7 +25,7 @@ xxxxxxxxx_yyy_zzzzzzzz[xx.xxxxxx(x_yyy_zzzzzz.xxxxx[0]), x_yyy_zzzzzz.xxxxxx(xxx
```diff
--- Black
+++ Ruff
@@ -9,13 +9,8 @@
@@ -9,13 +9,10 @@
m2,
),
third_value,
@@ -33,14 +33,14 @@ xxxxxxxxx_yyy_zzzzzzzz[xx.xxxxxx(x_yyy_zzzzzz.xxxxx[0]), x_yyy_zzzzzz.xxxxxx(xxx
- arg1,
- arg2,
-)
+) = NOT_IMPLEMENTED_call()
+) = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# Make when when the left side of assignment plus the opening paren "... = (" is
# exactly line length limit + 1, it won't be split like that.
-xxxxxxxxx_yyy_zzzzzzzz[
xxxxxxxxx_yyy_zzzzzzzz[
- xx.xxxxxx(x_yyy_zzzzzz.xxxxx[0]), x_yyy_zzzzzz.xxxxxx(xxxx=1)
-] = 1
+xxxxxxxxx_yyy_zzzzzzzz[NOT_IMPLEMENTED_call(), NOT_IMPLEMENTED_call()] = 1
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg), NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
] = 1
```
## Ruff Output
@@ -57,11 +57,13 @@ xxxxxxxxx_yyy_zzzzzzzz[xx.xxxxxx(x_yyy_zzzzzz.xxxxx[0]), x_yyy_zzzzzz.xxxxxx(xxx
m2,
),
third_value,
) = NOT_IMPLEMENTED_call()
) = NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# Make when when the left side of assignment plus the opening paren "... = (" is
# exactly line length limit + 1, it won't be split like that.
xxxxxxxxx_yyy_zzzzzzzz[NOT_IMPLEMENTED_call(), NOT_IMPLEMENTED_call()] = 1
xxxxxxxxx_yyy_zzzzzzzz[
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg), NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
] = 1
```
## Black Output

View File

@@ -102,23 +102,23 @@ async def main():
# Control example
async def main():
- await asyncio.sleep(1)
+ await NOT_IMPLEMENTED_call()
+ await NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# Remove brackets for short coroutine/task
async def main():
- await asyncio.sleep(1)
+ await (NOT_IMPLEMENTED_call())
+ await (NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg))
async def main():
- await asyncio.sleep(1)
+ await (NOT_IMPLEMENTED_call())
+ await (NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg))
async def main():
- await asyncio.sleep(1)
+ await (NOT_IMPLEMENTED_call())
+ await (NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg))
# Check comments
@@ -126,7 +126,7 @@ async def main():
- await asyncio.sleep(1) # Hello
+ (
+ await # Hello
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
+ )
@@ -134,14 +134,14 @@ async def main():
- await asyncio.sleep(1) # Hello
+ (
+ await (
+ NOT_IMPLEMENTED_call() # Hello
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg) # Hello
+ )
+ )
async def main():
- await asyncio.sleep(1) # Hello
+ await (NOT_IMPLEMENTED_call()) # Hello
+ await (NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)) # Hello
# Long lines
@@ -155,7 +155,7 @@ async def main():
- asyncio.sleep(1),
- asyncio.sleep(1),
- )
+ await NOT_IMPLEMENTED_call()
+ await NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# Same as above but with magic trailing comma in function
@@ -169,13 +169,13 @@ async def main():
- asyncio.sleep(1),
- asyncio.sleep(1),
- )
+ await NOT_IMPLEMENTED_call()
+ await NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# Cr@zY Br@ck3Tz
async def main():
- await black(1)
+ await (NOT_IMPLEMENTED_call())
+ await (NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg))
# Keep brackets around non power operations and nested awaits
@@ -184,7 +184,7 @@ async def main():
async def main():
- await (await asyncio.sleep(1))
+ await (await NOT_IMPLEMENTED_call())
+ await (await NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg))
# It's awaits all the way down...
@@ -198,12 +198,12 @@ async def main():
async def main():
- await (await asyncio.sleep(1))
+ await (await (NOT_IMPLEMENTED_call()))
+ await (await (NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)))
async def main():
- await (await (await (await (await asyncio.sleep(1)))))
+ await (await (await (await (await (NOT_IMPLEMENTED_call())))))
+ await (await (await (await (await (NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg))))))
async def main():
@@ -219,55 +219,55 @@ NOT_YET_IMPLEMENTED_StmtImport
# Control example
async def main():
await NOT_IMPLEMENTED_call()
await NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# Remove brackets for short coroutine/task
async def main():
await (NOT_IMPLEMENTED_call())
await (NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg))
async def main():
await (NOT_IMPLEMENTED_call())
await (NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg))
async def main():
await (NOT_IMPLEMENTED_call())
await (NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg))
# Check comments
async def main():
(
await # Hello
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
)
async def main():
(
await (
NOT_IMPLEMENTED_call() # Hello
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg) # Hello
)
)
async def main():
await (NOT_IMPLEMENTED_call()) # Hello
await (NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)) # Hello
# Long lines
async def main():
await NOT_IMPLEMENTED_call()
await NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# Same as above but with magic trailing comma in function
async def main():
await NOT_IMPLEMENTED_call()
await NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# Cr@zY Br@ck3Tz
async def main():
await (NOT_IMPLEMENTED_call())
await (NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg))
# Keep brackets around non power operations and nested awaits
@@ -276,7 +276,7 @@ async def main():
async def main():
await (await NOT_IMPLEMENTED_call())
await (await NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg))
# It's awaits all the way down...
@@ -289,11 +289,11 @@ async def main():
async def main():
await (await (NOT_IMPLEMENTED_call()))
await (await (NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)))
async def main():
await (await (await (await (await (NOT_IMPLEMENTED_call())))))
await (await (await (await (await (NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg))))))
async def main():

View File

@@ -37,13 +37,13 @@ for (((((k, v))))) in d.items():
-for k, v in d.items():
- print(k, v)
+for k, v in NOT_IMPLEMENTED_call():
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# Don't touch tuple brackets after `in`
for module in (core, _unicodefun):
- if hasattr(module, "_verify_python3_env"):
- module._verify_python3_env = lambda: None
+ if NOT_IMPLEMENTED_call():
+ if NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg):
+ module._verify_python3_env = lambda x: True
# Brackets remain for long for loop lines
@@ -53,7 +53,7 @@ for (((((k, v))))) in d.items():
-) in d.items():
- print(k, v)
+) in NOT_IMPLEMENTED_call():
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
-for (
- k,
@@ -63,13 +63,13 @@ for (((((k, v))))) in d.items():
-):
- print(k, v)
+for k, v in NOT_IMPLEMENTED_call():
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# Test deeply nested brackets
-for k, v in d.items():
- print(k, v)
+for k, v in NOT_IMPLEMENTED_call():
+ NOT_IMPLEMENTED_call()
+ NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
```
## Ruff Output
@@ -77,11 +77,11 @@ for (((((k, v))))) in d.items():
```py
# Only remove tuple brackets after `for`
for k, v in NOT_IMPLEMENTED_call():
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# Don't touch tuple brackets after `in`
for module in (core, _unicodefun):
if NOT_IMPLEMENTED_call():
if NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg):
module._verify_python3_env = lambda x: True
# Brackets remain for long for loop lines
@@ -89,14 +89,14 @@ for (
why_would_anyone_choose_to_name_a_loop_variable_with_a_name_this_long,
i_dont_know_but_we_should_still_check_the_behaviour_if_they_do,
) in NOT_IMPLEMENTED_call():
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
for k, v in NOT_IMPLEMENTED_call():
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
# Test deeply nested brackets
for k, v in NOT_IMPLEMENTED_call():
NOT_IMPLEMENTED_call()
NOT_IMPLEMENTED_call(NOT_IMPLEMENTED_arg)
```
## Black Output

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