Implement module formatting using JoinNodesBuilder (#4808)

* Implement module formatting using JoinNodesBuilder

This uses JoinNodesBuilder to implement module formatting for #4800

See the snapshots for the changed behaviour. See one PR up for a CLI that i used to verify the trailing new line behaviour
This commit is contained in:
konstin 2023-06-05 10:35:05 +02:00 committed by GitHub
parent c65f47d7c4
commit ff37d7af23
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
43 changed files with 1176 additions and 1524 deletions

View file

@ -1,8 +1,7 @@
use crate::AsFormat; use crate::statement::suite::SuiteLevel;
use crate::{FormatNodeRule, PyFormatter}; use crate::{AsFormat, FormatNodeRule, PyFormatter};
use ruff_formatter::prelude::hard_line_break; use ruff_formatter::prelude::hard_line_break;
use ruff_formatter::{write, Buffer, FormatResult}; use ruff_formatter::{write, Buffer, FormatResult};
use rustpython_parser::ast::ModModule; use rustpython_parser::ast::ModModule;
#[derive(Default)] #[derive(Default)]
@ -10,9 +9,13 @@ pub struct FormatModModule;
impl FormatNodeRule<ModModule> for FormatModModule { impl FormatNodeRule<ModModule> for FormatModModule {
fn fmt_fields(&self, item: &ModModule, f: &mut PyFormatter) -> FormatResult<()> { fn fmt_fields(&self, item: &ModModule, f: &mut PyFormatter) -> FormatResult<()> {
for stmt in &item.body { write!(
write!(f, [stmt.format(), hard_line_break()])?; f,
} [
Ok(()) item.body.format().with_options(SuiteLevel::TopLevel),
// Trailing newline at the end of the file
hard_line_break()
]
)
} }
} }

View file

@ -35,7 +35,7 @@ y = 100(no)
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,22 +1,20 @@ @@ -1,21 +1,21 @@
-x = (123456789).bit_count() -x = (123456789).bit_count()
+x = 123456789 .bit_count() +x = 123456789 .bit_count()
x = (123456).__abs__() x = (123456).__abs__()
@ -53,8 +53,6 @@ y = 100(no)
-x = 0o777.real -x = 0o777.real
-x = (0.000000006).hex() -x = (0.000000006).hex()
-x = -100.0000j -x = -100.0000j
-
-if (10).real:
+x = .1.is_integer() +x = .1.is_integer()
+x = 1. .imag +x = 1. .imag
+x = 1E+1.imag +x = 1E+1.imag
@ -69,11 +67,12 @@ y = 100(no)
+x = 0O777 .real +x = 0O777 .real
+x = 0.000000006 .hex() +x = 0.000000006 .hex()
+x = -100.0000J +x = -100.0000J
-if (10).real:
+if 10 .real: +if 10 .real:
... ...
-
y = 100[no] y = 100[no]
y = 100(no)
``` ```
## Ruff Output ## Ruff Output
@ -95,8 +94,10 @@ x = 0B1011 .conjugate()
x = 0O777 .real x = 0O777 .real
x = 0.000000006 .hex() x = 0.000000006 .hex()
x = -100.0000J x = -100.0000J
if 10 .real: if 10 .real:
... ...
y = 100[no] y = 100[no]
y = 100(no) y = 100(no)
``` ```

View file

@ -36,12 +36,12 @@ class NormalClass (
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,30 +1,21 @@ @@ -1,16 +1,16 @@
-class SimpleClassWithBlankParentheses: -class SimpleClassWithBlankParentheses:
+class SimpleClassWithBlankParentheses(): +class SimpleClassWithBlankParentheses():
pass pass
-
-
-class ClassWithSpaceParentheses: -class ClassWithSpaceParentheses:
+class ClassWithSpaceParentheses ( ): +class ClassWithSpaceParentheses ( ):
first_test_data = 90 first_test_data = 90
@ -49,24 +49,22 @@ class NormalClass (
- -
def test_func(self): def test_func(self):
return None return None
-
-
class ClassWithEmptyFunc(object): class ClassWithEmptyFunc(object):
+ +
def func_with_blank_parentheses(): def func_with_blank_parentheses():
return 5 return 5
-
- @@ -20,11 +20,12 @@
def public_func_with_blank_parentheses():
return None
-
-
def class_under_the_func_with_blank_parentheses(): def class_under_the_func_with_blank_parentheses():
- class InsideFunc: - class InsideFunc:
+ class InsideFunc(): + class InsideFunc():
pass pass
-
-
-class NormalClass: -class NormalClass:
+class NormalClass ( +class NormalClass (
+): +):
@ -80,20 +78,30 @@ class NormalClass (
```py ```py
class SimpleClassWithBlankParentheses(): class SimpleClassWithBlankParentheses():
pass pass
class ClassWithSpaceParentheses ( ): class ClassWithSpaceParentheses ( ):
first_test_data = 90 first_test_data = 90
second_test_data = 100 second_test_data = 100
def test_func(self): def test_func(self):
return None return None
class ClassWithEmptyFunc(object): class ClassWithEmptyFunc(object):
def func_with_blank_parentheses(): def func_with_blank_parentheses():
return 5 return 5
def public_func_with_blank_parentheses(): def public_func_with_blank_parentheses():
return None return None
def class_under_the_func_with_blank_parentheses(): def class_under_the_func_with_blank_parentheses():
class InsideFunc(): class InsideFunc():
pass pass
class NormalClass ( class NormalClass (
): ):
def func_for_testing(self, first, second): def func_for_testing(self, first, second):

View file

@ -113,38 +113,22 @@ class ClassWithDecoInitAndVarsAndDocstringWithInner2:
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,165 +1,100 @@ @@ -17,23 +17,19 @@
class ClassSimplest:
pass
-
-
class ClassWithSingleField:
a = 1
-
-
class ClassWithJustTheDocstring:
"""Just a docstring."""
-
-
class ClassWithInit:
def __init__(self):
pass
-
-
class ClassWithTheDocstringAndInit: class ClassWithTheDocstringAndInit:
"""Just a docstring.""" """Just a docstring."""
- -
def __init__(self): def __init__(self):
pass pass
-
-
class ClassWithInitAndVars: class ClassWithInitAndVars:
cls_var = 100 cls_var = 100
- -
def __init__(self): def __init__(self):
pass pass
-
-
class ClassWithInitAndVarsAndDocstring: class ClassWithInitAndVarsAndDocstring:
"""Test class""" """Test class"""
- -
@ -152,22 +136,17 @@ class ClassWithDecoInitAndVarsAndDocstringWithInner2:
- -
def __init__(self): def __init__(self):
pass pass
-
- @@ -46,7 +42,6 @@
class ClassWithDecoInit:
@deco
def __init__(self):
pass
-
-
class ClassWithDecoInitAndVars: class ClassWithDecoInitAndVars:
cls_var = 100 cls_var = 100
- -
@deco @deco
def __init__(self): def __init__(self):
pass pass
- @@ -54,9 +49,7 @@
-
class ClassWithDecoInitAndVarsAndDocstring: class ClassWithDecoInitAndVarsAndDocstring:
"""Test class""" """Test class"""
- -
@ -176,43 +155,37 @@ class ClassWithDecoInitAndVarsAndDocstringWithInner2:
@deco @deco
def __init__(self): def __init__(self):
pass pass
- @@ -70,21 +63,18 @@
-
class ClassSimplestWithInner:
class Inner:
pass
-
-
class ClassSimplestWithInnerWithDocstring: class ClassSimplestWithInnerWithDocstring:
class Inner: class Inner:
"""Just a docstring.""" """Just a docstring."""
- -
def __init__(self): def __init__(self):
pass pass
-
-
class ClassWithSingleFieldWithInner: class ClassWithSingleFieldWithInner:
a = 1 a = 1
- -
class Inner: class Inner:
pass pass
-
-
class ClassWithJustTheDocstringWithInner: class ClassWithJustTheDocstringWithInner:
"""Just a docstring.""" """Just a docstring."""
- -
class Inner: class Inner:
pass pass
-
- @@ -92,29 +82,23 @@
class ClassWithInitWithInner: class ClassWithInitWithInner:
class Inner: class Inner:
pass pass
- -
def __init__(self): def __init__(self):
pass pass
-
-
class ClassWithInitAndVarsWithInner: class ClassWithInitAndVarsWithInner:
cls_var = 100 cls_var = 100
- -
@ -221,8 +194,8 @@ class ClassWithDecoInitAndVarsAndDocstringWithInner2:
- -
def __init__(self): def __init__(self):
pass pass
-
-
class ClassWithInitAndVarsAndDocstringWithInner: class ClassWithInitAndVarsAndDocstringWithInner:
"""Test class""" """Test class"""
- -
@ -233,8 +206,8 @@ class ClassWithDecoInitAndVarsAndDocstringWithInner2:
- -
def __init__(self): def __init__(self):
pass pass
-
- @@ -122,7 +106,6 @@
class ClassWithDecoInitWithInner: class ClassWithDecoInitWithInner:
class Inner: class Inner:
pass pass
@ -242,8 +215,8 @@ class ClassWithDecoInitAndVarsAndDocstringWithInner2:
@deco @deco
def __init__(self): def __init__(self):
pass pass
- @@ -130,10 +113,8 @@
-
class ClassWithDecoInitAndVarsWithInner: class ClassWithDecoInitAndVarsWithInner:
cls_var = 100 cls_var = 100
- -
@ -253,8 +226,8 @@ class ClassWithDecoInitAndVarsAndDocstringWithInner2:
@deco @deco
def __init__(self): def __init__(self):
pass pass
- @@ -141,12 +122,9 @@
-
class ClassWithDecoInitAndVarsAndDocstringWithInner: class ClassWithDecoInitAndVarsAndDocstringWithInner:
"""Test class""" """Test class"""
- -
@ -266,8 +239,8 @@ class ClassWithDecoInitAndVarsAndDocstringWithInner2:
@deco @deco
def __init__(self): def __init__(self):
pass pass
- @@ -154,12 +132,9 @@
-
class ClassWithDecoInitAndVarsAndDocstringWithInner2: class ClassWithDecoInitAndVarsAndDocstringWithInner2:
"""Test class""" """Test class"""
- -
@ -286,68 +259,100 @@ class ClassWithDecoInitAndVarsAndDocstringWithInner2:
```py ```py
class ClassSimplest: class ClassSimplest:
pass pass
class ClassWithSingleField: class ClassWithSingleField:
a = 1 a = 1
class ClassWithJustTheDocstring: class ClassWithJustTheDocstring:
"""Just a docstring.""" """Just a docstring."""
class ClassWithInit: class ClassWithInit:
def __init__(self): def __init__(self):
pass pass
class ClassWithTheDocstringAndInit: class ClassWithTheDocstringAndInit:
"""Just a docstring.""" """Just a docstring."""
def __init__(self): def __init__(self):
pass pass
class ClassWithInitAndVars: class ClassWithInitAndVars:
cls_var = 100 cls_var = 100
def __init__(self): def __init__(self):
pass pass
class ClassWithInitAndVarsAndDocstring: class ClassWithInitAndVarsAndDocstring:
"""Test class""" """Test class"""
cls_var = 100 cls_var = 100
def __init__(self): def __init__(self):
pass pass
class ClassWithDecoInit: class ClassWithDecoInit:
@deco @deco
def __init__(self): def __init__(self):
pass pass
class ClassWithDecoInitAndVars: class ClassWithDecoInitAndVars:
cls_var = 100 cls_var = 100
@deco @deco
def __init__(self): def __init__(self):
pass pass
class ClassWithDecoInitAndVarsAndDocstring: class ClassWithDecoInitAndVarsAndDocstring:
"""Test class""" """Test class"""
cls_var = 100 cls_var = 100
@deco @deco
def __init__(self): def __init__(self):
pass pass
class ClassSimplestWithInner: class ClassSimplestWithInner:
class Inner: class Inner:
pass pass
class ClassSimplestWithInnerWithDocstring: class ClassSimplestWithInnerWithDocstring:
class Inner: class Inner:
"""Just a docstring.""" """Just a docstring."""
def __init__(self): def __init__(self):
pass pass
class ClassWithSingleFieldWithInner: class ClassWithSingleFieldWithInner:
a = 1 a = 1
class Inner: class Inner:
pass pass
class ClassWithJustTheDocstringWithInner: class ClassWithJustTheDocstringWithInner:
"""Just a docstring.""" """Just a docstring."""
class Inner: class Inner:
pass pass
class ClassWithInitWithInner: class ClassWithInitWithInner:
class Inner: class Inner:
pass pass
def __init__(self): def __init__(self):
pass pass
class ClassWithInitAndVarsWithInner: class ClassWithInitAndVarsWithInner:
cls_var = 100 cls_var = 100
class Inner: class Inner:
pass pass
def __init__(self): def __init__(self):
pass pass
class ClassWithInitAndVarsAndDocstringWithInner: class ClassWithInitAndVarsAndDocstringWithInner:
"""Test class""" """Test class"""
cls_var = 100 cls_var = 100
@ -355,12 +360,16 @@ class ClassWithInitAndVarsAndDocstringWithInner:
pass pass
def __init__(self): def __init__(self):
pass pass
class ClassWithDecoInitWithInner: class ClassWithDecoInitWithInner:
class Inner: class Inner:
pass pass
@deco @deco
def __init__(self): def __init__(self):
pass pass
class ClassWithDecoInitAndVarsWithInner: class ClassWithDecoInitAndVarsWithInner:
cls_var = 100 cls_var = 100
class Inner: class Inner:
@ -368,6 +377,8 @@ class ClassWithDecoInitAndVarsWithInner:
@deco @deco
def __init__(self): def __init__(self):
pass pass
class ClassWithDecoInitAndVarsAndDocstringWithInner: class ClassWithDecoInitAndVarsAndDocstringWithInner:
"""Test class""" """Test class"""
cls_var = 100 cls_var = 100
@ -376,6 +387,8 @@ class ClassWithDecoInitAndVarsAndDocstringWithInner:
@deco @deco
def __init__(self): def __init__(self):
pass pass
class ClassWithDecoInitAndVarsAndDocstringWithInner2: class ClassWithDecoInitAndVarsAndDocstringWithInner2:
"""Test class""" """Test class"""
class Inner: class Inner:

View file

@ -84,9 +84,9 @@ if True:
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,99 +1,61 @@ @@ -1,75 +1,49 @@
import core, time, a import core, time, a
-
from . import A, B, C from . import A, B, C
- -
# keeps existing trailing comma # keeps existing trailing comma
@ -104,7 +104,7 @@ if True:
from foo import ( from foo import (
xyzzy as magic, xyzzy as magic,
) )
-
-a = { -a = {
- 1, - 1,
- 2, - 2,
@ -162,24 +162,22 @@ if True:
pass pass
for (x,) in (1,), (2,), (3,): for (x,) in (1,), (2,), (3,):
pass pass
-
-[ -[
- 1, - 1,
- 2, - 2,
- 3, - 3,
-] -]
-
-division_result_tuple = (6 / 2,)
+[1, 2, 3,] +[1, 2, 3,]
-division_result_tuple = (6 / 2,)
+division_result_tuple = (6/2,) +division_result_tuple = (6/2,)
print("foo %r", (foo.bar,)) print("foo %r", (foo.bar,))
-
if True: if True:
IGNORED_TYPES_FOR_ATTRIBUTE_CHECKING = ( @@ -79,21 +53,15 @@
Config.IGNORED_TYPES_FOR_ATTRIBUTE_CHECKING
| {pylons.controllers.WSGIController}
) )
-
if True: if True:
- ec2client.get_waiter("instance_stopped").wait( - ec2client.get_waiter("instance_stopped").wait(
+ ec2client.get_waiter('instance_stopped').wait( + ec2client.get_waiter('instance_stopped').wait(
@ -210,6 +208,7 @@ if True:
```py ```py
import core, time, a import core, time, a
from . import A, B, C from . import A, B, C
# keeps existing trailing comma # keeps existing trailing comma
from foo import ( from foo import (
@ -224,6 +223,7 @@ from foo import (
from foo import ( from foo import (
xyzzy as magic, xyzzy as magic,
) )
a = {1,2,3,} a = {1,2,3,}
b = { b = {
1,2, 1,2,
@ -249,14 +249,18 @@ for x in (1,):
pass pass
for (x,) in (1,), (2,), (3,): for (x,) in (1,), (2,), (3,):
pass pass
[1, 2, 3,] [1, 2, 3,]
division_result_tuple = (6/2,) division_result_tuple = (6/2,)
print("foo %r", (foo.bar,)) print("foo %r", (foo.bar,))
if True: if True:
IGNORED_TYPES_FOR_ATTRIBUTE_CHECKING = ( IGNORED_TYPES_FOR_ATTRIBUTE_CHECKING = (
Config.IGNORED_TYPES_FOR_ATTRIBUTE_CHECKING Config.IGNORED_TYPES_FOR_ATTRIBUTE_CHECKING
| {pylons.controllers.WSGIController} | {pylons.controllers.WSGIController}
) )
if True: if True:
ec2client.get_waiter('instance_stopped').wait( ec2client.get_waiter('instance_stopped').wait(
InstanceIds=[instance.id], InstanceIds=[instance.id],

View file

@ -22,13 +22,13 @@ def bobtwo(): \
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,6 +1,7 @@ @@ -1,6 +1,9 @@
-def bob(): # pylint: disable=W9016 -def bob(): # pylint: disable=W9016
+def bob(): \ +def bob(): \
+ # pylint: disable=W9016 + # pylint: disable=W9016
pass pass
-
-
-def bobtwo(): # some comment here -def bobtwo(): # some comment here
+def bobtwo(): \ +def bobtwo(): \
+ \ + \
@ -42,6 +42,8 @@ def bobtwo(): \
def bob(): \ def bob(): \
# pylint: disable=W9016 # pylint: disable=W9016
pass pass
def bobtwo(): \ def bobtwo(): \
\ \
# some comment here # some comment here

View file

@ -178,7 +178,7 @@ instruction()#comment with bad spacing
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,39 +1,38 @@ @@ -1,39 +1,40 @@
from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import ( from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import (
- MyLovelyCompanyTeamProjectComponent, # NOT DRY - MyLovelyCompanyTeamProjectComponent, # NOT DRY
+ MyLovelyCompanyTeamProjectComponent # NOT DRY + MyLovelyCompanyTeamProjectComponent # NOT DRY
@ -187,7 +187,7 @@ instruction()#comment with bad spacing
- MyLovelyCompanyTeamProjectComponent as component, # DRY - MyLovelyCompanyTeamProjectComponent as component, # DRY
+ MyLovelyCompanyTeamProjectComponent as component # DRY + MyLovelyCompanyTeamProjectComponent as component # DRY
) )
-
# Please keep __all__ alphabetized within each category. # Please keep __all__ alphabetized within each category.
__all__ = [ __all__ = [
@ -227,7 +227,7 @@ instruction()#comment with bad spacing
+ 'NamedTuple', # Not really a type. + 'NamedTuple', # Not really a type.
+ 'Generator', + 'Generator',
] ]
-
not_shareables = [ not_shareables = [
# singletons # singletons
True, True,
@ -238,11 +238,10 @@ instruction()#comment with bad spacing
# builtin types and objects # builtin types and objects
type, type,
object, object,
@@ -47,21 +46,21 @@ @@ -48,20 +49,23 @@
Cheese("Wensleydale"),
SubBytes(b"spam"), SubBytes(b"spam"),
] ]
-
-if "PYTHON" in os.environ: -if "PYTHON" in os.environ:
+if 'PYTHON' in os.environ: +if 'PYTHON' in os.environ:
add_compiler(compiler_from_env()) add_compiler(compiler_from_env())
@ -252,8 +251,8 @@ instruction()#comment with bad spacing
+ # add_compiler(compiler) + # add_compiler(compiler)
add_compiler(compilers[(7.0, 32)]) add_compiler(compilers[(7.0, 32)])
- # add_compiler(compilers[(7.1, 64)]) - # add_compiler(compilers[(7.1, 64)])
-
-
# Comment before function. # Comment before function.
def inline_comments_in_brackets_ruin_everything(): def inline_comments_in_brackets_ruin_everything():
if typedargslist: if typedargslist:
@ -267,7 +266,7 @@ instruction()#comment with bad spacing
children[0], children[0],
body, body,
children[-1], # type: ignore children[-1], # type: ignore
@@ -73,49 +72,42 @@ @@ -73,49 +77,42 @@
parameters.children[-1], # )2 parameters.children[-1], # )2
] ]
parameters.children = [parameters.what_if_this_was_actually_long.children[0], body, parameters.children[-1]] # type: ignore parameters.children = [parameters.what_if_this_was_actually_long.children[0], body, parameters.children[-1]] # type: ignore
@ -340,7 +339,7 @@ instruction()#comment with bad spacing
] ]
lcomp2 = [ lcomp2 = [
# hello # hello
@@ -127,7 +119,7 @@ @@ -127,7 +124,7 @@
] ]
lcomp3 = [ lcomp3 = [
# This one is actually too long to fit in a single line. # This one is actually too long to fit in a single line.
@ -349,7 +348,7 @@ instruction()#comment with bad spacing
# yup # yup
for element in collection.select_elements() for element in collection.select_elements()
# right # right
@@ -140,28 +132,20 @@ @@ -140,25 +137,23 @@
# and round and round we go # and round and round we go
# and round and round we go # and round and round we go
@ -363,8 +362,8 @@ instruction()#comment with bad spacing
+ Leaf(token.NEWLINE, '\n') # FIXME: \r\n? + Leaf(token.NEWLINE, '\n') # FIXME: \r\n?
+ ], + ],
) )
-
-
-CONFIG_FILES = ( -CONFIG_FILES = (
- [ - [
- CONFIG_FILE, - CONFIG_FILE,
@ -372,20 +371,17 @@ instruction()#comment with bad spacing
- + SHARED_CONFIG_FILES - + SHARED_CONFIG_FILES
- + USER_CONFIG_FILES - + USER_CONFIG_FILES
-) # type: Final -) # type: Final
-
-
+CONFIG_FILES = [CONFIG_FILE, ] + SHARED_CONFIG_FILES + USER_CONFIG_FILES # type: Final +CONFIG_FILES = [CONFIG_FILE, ] + SHARED_CONFIG_FILES + USER_CONFIG_FILES # type: Final
class Test: class Test:
def _init_host(self, parsed) -> None: def _init_host(self, parsed) -> None:
- if parsed.hostname is None or not parsed.hostname.strip(): # type: ignore - if parsed.hostname is None or not parsed.hostname.strip(): # type: ignore
+ if (parsed.hostname is None or # type: ignore + if (parsed.hostname is None or # type: ignore
+ not parsed.hostname.strip()): + not parsed.hostname.strip()):
pass pass
-
-
#######################
### SECTION COMMENT ###
#######################
``` ```
## Ruff Output ## Ruff Output
@ -397,6 +393,7 @@ from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component
from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import ( from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import (
MyLovelyCompanyTeamProjectComponent as component # DRY MyLovelyCompanyTeamProjectComponent as component # DRY
) )
# Please keep __all__ alphabetized within each category. # Please keep __all__ alphabetized within each category.
__all__ = [ __all__ = [
@ -421,6 +418,7 @@ __all__ = [
'NamedTuple', # Not really a type. 'NamedTuple', # Not really a type.
'Generator', 'Generator',
] ]
not_shareables = [ not_shareables = [
# singletons # singletons
True, True,
@ -439,12 +437,15 @@ not_shareables = [
Cheese("Wensleydale"), Cheese("Wensleydale"),
SubBytes(b"spam"), SubBytes(b"spam"),
] ]
if 'PYTHON' in os.environ: if 'PYTHON' in os.environ:
add_compiler(compiler_from_env()) add_compiler(compiler_from_env())
else: else:
# for compiler in compilers.values(): # for compiler in compilers.values():
# add_compiler(compiler) # add_compiler(compiler)
add_compiler(compilers[(7.0, 32)]) add_compiler(compilers[(7.0, 32)])
# Comment before function. # Comment before function.
def inline_comments_in_brackets_ruin_everything(): def inline_comments_in_brackets_ruin_everything():
if typedargslist: if typedargslist:
@ -533,12 +534,18 @@ short
Leaf(token.NEWLINE, '\n') # FIXME: \r\n? Leaf(token.NEWLINE, '\n') # FIXME: \r\n?
], ],
) )
CONFIG_FILES = [CONFIG_FILE, ] + SHARED_CONFIG_FILES + USER_CONFIG_FILES # type: Final CONFIG_FILES = [CONFIG_FILE, ] + SHARED_CONFIG_FILES + USER_CONFIG_FILES # type: Final
class Test: class Test:
def _init_host(self, parsed) -> None: def _init_host(self, parsed) -> None:
if (parsed.hostname is None or # type: ignore if (parsed.hostname is None or # type: ignore
not parsed.hostname.strip()): not parsed.hostname.strip()):
pass pass
####################### #######################
### SECTION COMMENT ### ### SECTION COMMENT ###
####################### #######################

View file

@ -1,338 +0,0 @@
---
source: crates/ruff_python_formatter/src/lib.rs
expression: snapshot
input_file: crates/ruff_python_formatter/resources/test/fixtures/black/simple_cases/comments4.py
---
## Input
```py
from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import (
MyLovelyCompanyTeamProjectComponent, # NOT DRY
)
from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import (
MyLovelyCompanyTeamProjectComponent as component, # DRY
)
class C:
@pytest.mark.parametrize(
("post_data", "message"),
[
# metadata_version errors.
(
{},
"None is an invalid value for Metadata-Version. Error: This field is"
" required. see"
" https://packaging.python.org/specifications/core-metadata",
),
(
{"metadata_version": "-1"},
"'-1' is an invalid value for Metadata-Version. Error: Unknown Metadata"
" Version see"
" https://packaging.python.org/specifications/core-metadata",
),
# name errors.
(
{"metadata_version": "1.2"},
"'' is an invalid value for Name. Error: This field is required. see"
" https://packaging.python.org/specifications/core-metadata",
),
(
{"metadata_version": "1.2", "name": "foo-"},
"'foo-' is an invalid value for Name. Error: Must start and end with a"
" letter or numeral and contain only ascii numeric and '.', '_' and"
" '-'. see https://packaging.python.org/specifications/core-metadata",
),
# version errors.
(
{"metadata_version": "1.2", "name": "example"},
"'' is an invalid value for Version. Error: This field is required. see"
" https://packaging.python.org/specifications/core-metadata",
),
(
{"metadata_version": "1.2", "name": "example", "version": "dog"},
"'dog' is an invalid value for Version. Error: Must start and end with"
" a letter or numeral and contain only ascii numeric and '.', '_' and"
" '-'. see https://packaging.python.org/specifications/core-metadata",
),
],
)
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)
def foo(list_a, list_b):
results = (
User.query.filter(User.foo == "bar")
.filter( # Because foo.
db.or_(User.field_a.astext.in_(list_a), User.field_b.astext.in_(list_b))
)
.filter(User.xyz.is_(None))
# Another comment about the filtering on is_quux goes here.
.filter(db.not_(User.is_pending.astext.cast(db.Boolean).is_(True)))
.order_by(User.created_at.desc())
.with_for_update(key_share=True)
.all()
)
return results
def foo2(list_a, list_b):
# Standalone comment reasonably placed.
return (
User.query.filter(User.foo == "bar")
.filter(
db.or_(User.field_a.astext.in_(list_a), User.field_b.astext.in_(list_b))
)
.filter(User.xyz.is_(None))
)
def foo3(list_a, list_b):
return (
# Standalone comment but weirdly placed.
User.query.filter(User.foo == "bar")
.filter(
db.or_(User.field_a.astext.in_(list_a), User.field_b.astext.in_(list_b))
)
.filter(User.xyz.is_(None))
)
```
## Black Differences
```diff
--- Black
+++ Ruff
@@ -4,8 +4,6 @@
from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import (
MyLovelyCompanyTeamProjectComponent as component, # DRY
)
-
-
class C:
@pytest.mark.parametrize(
("post_data", "message"),
@@ -54,8 +52,6 @@
):
pyramid_config.testing_securitypolicy(userid=1)
db_request.POST = MultiDict(post_data)
-
-
def foo(list_a, list_b):
results = (
User.query.filter(User.foo == "bar")
@@ -70,8 +66,6 @@
.all()
)
return results
-
-
def foo2(list_a, list_b):
# Standalone comment reasonably placed.
return (
@@ -81,8 +75,6 @@
)
.filter(User.xyz.is_(None))
)
-
-
def foo3(list_a, list_b):
return (
# Standalone comment but weirdly placed.
```
## Ruff Output
```py
from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import (
MyLovelyCompanyTeamProjectComponent, # NOT DRY
)
from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import (
MyLovelyCompanyTeamProjectComponent as component, # DRY
)
class C:
@pytest.mark.parametrize(
("post_data", "message"),
[
# metadata_version errors.
(
{},
"None is an invalid value for Metadata-Version. Error: This field is"
" required. see"
" https://packaging.python.org/specifications/core-metadata",
),
(
{"metadata_version": "-1"},
"'-1' is an invalid value for Metadata-Version. Error: Unknown Metadata"
" Version see"
" https://packaging.python.org/specifications/core-metadata",
),
# name errors.
(
{"metadata_version": "1.2"},
"'' is an invalid value for Name. Error: This field is required. see"
" https://packaging.python.org/specifications/core-metadata",
),
(
{"metadata_version": "1.2", "name": "foo-"},
"'foo-' is an invalid value for Name. Error: Must start and end with a"
" letter or numeral and contain only ascii numeric and '.', '_' and"
" '-'. see https://packaging.python.org/specifications/core-metadata",
),
# version errors.
(
{"metadata_version": "1.2", "name": "example"},
"'' is an invalid value for Version. Error: This field is required. see"
" https://packaging.python.org/specifications/core-metadata",
),
(
{"metadata_version": "1.2", "name": "example", "version": "dog"},
"'dog' is an invalid value for Version. Error: Must start and end with"
" a letter or numeral and contain only ascii numeric and '.', '_' and"
" '-'. see https://packaging.python.org/specifications/core-metadata",
),
],
)
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)
def foo(list_a, list_b):
results = (
User.query.filter(User.foo == "bar")
.filter( # Because foo.
db.or_(User.field_a.astext.in_(list_a), User.field_b.astext.in_(list_b))
)
.filter(User.xyz.is_(None))
# Another comment about the filtering on is_quux goes here.
.filter(db.not_(User.is_pending.astext.cast(db.Boolean).is_(True)))
.order_by(User.created_at.desc())
.with_for_update(key_share=True)
.all()
)
return results
def foo2(list_a, list_b):
# Standalone comment reasonably placed.
return (
User.query.filter(User.foo == "bar")
.filter(
db.or_(User.field_a.astext.in_(list_a), User.field_b.astext.in_(list_b))
)
.filter(User.xyz.is_(None))
)
def foo3(list_a, list_b):
return (
# Standalone comment but weirdly placed.
User.query.filter(User.foo == "bar")
.filter(
db.or_(User.field_a.astext.in_(list_a), User.field_b.astext.in_(list_b))
)
.filter(User.xyz.is_(None))
)
```
## Black Output
```py
from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import (
MyLovelyCompanyTeamProjectComponent, # NOT DRY
)
from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import (
MyLovelyCompanyTeamProjectComponent as component, # DRY
)
class C:
@pytest.mark.parametrize(
("post_data", "message"),
[
# metadata_version errors.
(
{},
"None is an invalid value for Metadata-Version. Error: This field is"
" required. see"
" https://packaging.python.org/specifications/core-metadata",
),
(
{"metadata_version": "-1"},
"'-1' is an invalid value for Metadata-Version. Error: Unknown Metadata"
" Version see"
" https://packaging.python.org/specifications/core-metadata",
),
# name errors.
(
{"metadata_version": "1.2"},
"'' is an invalid value for Name. Error: This field is required. see"
" https://packaging.python.org/specifications/core-metadata",
),
(
{"metadata_version": "1.2", "name": "foo-"},
"'foo-' is an invalid value for Name. Error: Must start and end with a"
" letter or numeral and contain only ascii numeric and '.', '_' and"
" '-'. see https://packaging.python.org/specifications/core-metadata",
),
# version errors.
(
{"metadata_version": "1.2", "name": "example"},
"'' is an invalid value for Version. Error: This field is required. see"
" https://packaging.python.org/specifications/core-metadata",
),
(
{"metadata_version": "1.2", "name": "example", "version": "dog"},
"'dog' is an invalid value for Version. Error: Must start and end with"
" a letter or numeral and contain only ascii numeric and '.', '_' and"
" '-'. see https://packaging.python.org/specifications/core-metadata",
),
],
)
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)
def foo(list_a, list_b):
results = (
User.query.filter(User.foo == "bar")
.filter( # Because foo.
db.or_(User.field_a.astext.in_(list_a), User.field_b.astext.in_(list_b))
)
.filter(User.xyz.is_(None))
# Another comment about the filtering on is_quux goes here.
.filter(db.not_(User.is_pending.astext.cast(db.Boolean).is_(True)))
.order_by(User.created_at.desc())
.with_for_update(key_share=True)
.all()
)
return results
def foo2(list_a, list_b):
# Standalone comment reasonably placed.
return (
User.query.filter(User.foo == "bar")
.filter(
db.or_(User.field_a.astext.in_(list_a), User.field_b.astext.in_(list_b))
)
.filter(User.xyz.is_(None))
)
def foo3(list_a, list_b):
return (
# Standalone comment but weirdly placed.
User.query.filter(User.foo == "bar")
.filter(
db.or_(User.field_a.astext.in_(list_a), User.field_b.astext.in_(list_b))
)
.filter(User.xyz.is_(None))
)
```

View file

@ -86,7 +86,7 @@ if __name__ == "__main__":
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,11 +1,9 @@ @@ -1,7 +1,6 @@
while True: while True:
if something.changed: if something.changed:
- do.stuff() # trailing comment - do.stuff() # trailing comment
@ -95,66 +95,22 @@ if __name__ == "__main__":
# This one belongs to the `while` block. # This one belongs to the `while` block.
# Should this one, too? I guess so. # Should this one, too? I guess so.
- @@ -15,7 +14,6 @@
# This one is properly standalone now.
for i in range(100):
@@ -15,27 +13,18 @@
# then we do this # then we do this
print(i) print(i)
- # and finally we loop around - # and finally we loop around
-
with open(some_temp_file) as f: with open(some_temp_file) as f:
data = f.read() data = f.read()
- @@ -33,7 +31,6 @@
try:
with open(some_other_file) as w:
w.write(data)
except OSError:
print("problems")
-
import sys
-
-
# leading function comment # leading function comment
def wat(): def wat():
... ...
- # trailing function comment - # trailing function comment
-
-
# SECTION COMMENT # SECTION COMMENT
@@ -47,8 +36,6 @@
@deco3
def decorated1():
...
-
-
# leading 1
@deco1
# leading 2
@@ -56,18 +43,12 @@
# leading function comment
def decorated1():
...
-
-
# Note: this is fixed in
# Preview.empty_lines_before_class_or_def_with_leading_comments.
# In the current style, the user will have to split those lines by hand.
some_instruction
-
-
# This comment should be split from `some_instruction` by two lines but isn't.
def g():
...
-
-
if __name__ == "__main__":
main()
``` ```
## Ruff Output ## Ruff Output
@ -166,6 +122,7 @@ while True:
# This one belongs to the `while` block. # This one belongs to the `while` block.
# Should this one, too? I guess so. # Should this one, too? I guess so.
# This one is properly standalone now. # This one is properly standalone now.
for i in range(100): for i in range(100):
@ -175,18 +132,25 @@ for i in range(100):
# then we do this # then we do this
print(i) print(i)
with open(some_temp_file) as f: with open(some_temp_file) as f:
data = f.read() data = f.read()
try: try:
with open(some_other_file) as w: with open(some_other_file) as w:
w.write(data) w.write(data)
except OSError: except OSError:
print("problems") print("problems")
import sys import sys
# leading function comment # leading function comment
def wat(): def wat():
... ...
# SECTION COMMENT # SECTION COMMENT
@ -198,6 +162,8 @@ def wat():
@deco3 @deco3
def decorated1(): def decorated1():
... ...
# leading 1 # leading 1
@deco1 @deco1
# leading 2 # leading 2
@ -205,13 +171,19 @@ def decorated1():
# leading function comment # leading function comment
def decorated1(): def decorated1():
... ...
# Note: this is fixed in # Note: this is fixed in
# Preview.empty_lines_before_class_or_def_with_leading_comments. # Preview.empty_lines_before_class_or_def_with_leading_comments.
# In the current style, the user will have to split those lines by hand. # In the current style, the user will have to split those lines by hand.
some_instruction some_instruction
# This comment should be split from `some_instruction` by two lines but isn't. # This comment should be split from `some_instruction` by two lines but isn't.
def g(): def g():
... ...
if __name__ == "__main__": if __name__ == "__main__":
main() main()
``` ```

View file

@ -131,100 +131,35 @@ aaaaaaaaaaaaa, bbbbbbbbb = map(list, map(itertools.chain.from_iterable, zip(*ite
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,18 +1,12 @@ @@ -66,7 +66,7 @@
from typing import Any, Tuple
-
-
def f(
a, # type: int
):
pass
-
-
# test type comments
def f(a, b, c, d, e, f, g, h, i):
# type: (int, int, int, int, int, int, int, int, int) -> None
pass
-
-
def f(
a, # type: int
b, # type: int
@@ -26,8 +20,6 @@
):
# type: (...) -> None
pass
-
-
def f(
arg, # type: int
*args, # type: *Any
@@ -36,8 +28,6 @@
):
# type: (...) -> None
pass
-
-
def f(
a, # type: int
b, # type: int
@@ -66,23 +56,17 @@
+ element + element
+ another_element + another_element
+ another_element_with_long_name + another_element_with_long_name
- ) # type: int - ) # type: int
-
-
+ ) + )
def f( def f(
x, # not a type comment
y, # type: int
):
# type: (...) -> None
pass
-
-
def f(
x, # not a type comment
): # type: (int) -> None
pass
-
-
def func(
a=some_list[0], # type: int
): # type: () -> int
@@ -102,17 +86,12 @@
c = call(
"aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa" # type: ignore
)
-
-
result = ( # aaa
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
)
-
AAAAAAAAAAAAA = [AAAAAAAAAAAAA] + SHARED_AAAAAAAAAAAAA + USER_AAAAAAAAAAAAA + AAAAAAAAAAAAA # type: ignore
-
call_to_some_function_asdf(
foo,
[AAAAAAAAAAAAAAAAAAAAAAA, AAAAAAAAAAAAAAAAAAAAAAA, AAAAAAAAAAAAAAAAAAAAAAA, BBBBBBBBBBBB], # type: ignore
)
-
aaaaaaaaaaaaa, bbbbbbbbb = map(list, map(itertools.chain.from_iterable, zip(*items))) # type: ignore[arg-type]
``` ```
## Ruff Output ## Ruff Output
```py ```py
from typing import Any, Tuple from typing import Any, Tuple
def f( def f(
a, # type: int a, # type: int
): ):
pass pass
# test type comments # test type comments
def f(a, b, c, d, e, f, g, h, i): def f(a, b, c, d, e, f, g, h, i):
# type: (int, int, int, int, int, int, int, int, int) -> None # type: (int, int, int, int, int, int, int, int, int) -> None
pass pass
def f( def f(
a, # type: int a, # type: int
b, # type: int b, # type: int
@ -238,6 +173,8 @@ def f(
): ):
# type: (...) -> None # type: (...) -> None
pass pass
def f( def f(
arg, # type: int arg, # type: int
*args, # type: *Any *args, # type: *Any
@ -246,6 +183,8 @@ def f(
): ):
# type: (...) -> None # type: (...) -> None
pass pass
def f( def f(
a, # type: int a, # type: int
b, # type: int b, # type: int
@ -275,16 +214,22 @@ def f(
+ another_element + another_element
+ another_element_with_long_name + another_element_with_long_name
) )
def f( def f(
x, # not a type comment x, # not a type comment
y, # type: int y, # type: int
): ):
# type: (...) -> None # type: (...) -> None
pass pass
def f( def f(
x, # not a type comment x, # not a type comment
): # type: (int) -> None ): # type: (int) -> None
pass pass
def func( def func(
a=some_list[0], # type: int a=some_list[0], # type: int
): # type: () -> int ): # type: () -> int
@ -304,14 +249,19 @@ def func(
c = call( c = call(
"aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa" # type: ignore "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa" # type: ignore
) )
result = ( # aaa result = ( # aaa
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
) )
AAAAAAAAAAAAA = [AAAAAAAAAAAAA] + SHARED_AAAAAAAAAAAAA + USER_AAAAAAAAAAAAA + AAAAAAAAAAAAA # type: ignore AAAAAAAAAAAAA = [AAAAAAAAAAAAA] + SHARED_AAAAAAAAAAAAA + USER_AAAAAAAAAAAAA + AAAAAAAAAAAAA # type: ignore
call_to_some_function_asdf( call_to_some_function_asdf(
foo, foo,
[AAAAAAAAAAAAAAAAAAAAAAA, AAAAAAAAAAAAAAAAAAAAAAA, AAAAAAAAAAAAAAAAAAAAAAA, BBBBBBBBBBBB], # type: ignore [AAAAAAAAAAAAAAAAAAAAAAA, AAAAAAAAAAAAAAAAAAAAAAA, AAAAAAAAAAAAAAAAAAAAAAA, BBBBBBBBBBBB], # type: ignore
) )
aaaaaaaaaaaaa, bbbbbbbbb = map(list, map(itertools.chain.from_iterable, zip(*items))) # type: ignore[arg-type] aaaaaaaaaaaaa, bbbbbbbbb = map(list, map(itertools.chain.from_iterable, zip(*items))) # type: ignore[arg-type]
``` ```

View file

@ -152,99 +152,19 @@ def bar():
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,60 +1,35 @@ @@ -35,9 +35,10 @@
# Test for https://github.com/psf/black/issues/246.
some = statement some = statement
- -# This should be stick to the statement above
-
# This comment should be split from the statement above by two lines.
def function():
pass
-
-
some = statement
-
-
# This multiline comments section
# should be split from the statement
# above by two lines.
def function():
pass
-
-
some = statement
-
-
# This comment should be split from the statement above by two lines.
async def async_function():
pass
-
-
some = statement
-
-
# This comment should be split from the statement above by two lines.
class MyClass:
pass
-
-
some = statement
# This should be stick to the statement above
-
+# This should be stick to the statement above
+
# This should be split from the above by two lines # This should be split from the above by two lines
class MyClassWithComplexLeadingComments: class MyClassWithComplexLeadingComments:
pass pass
- @@ -102,11 +103,9 @@
-
class ClassWithDocstring:
"""A docstring."""
-
-
# Leading comment after a class with just a docstring
class MyClassAfterAnotherClassWithDocstring:
pass
-
-
some = statement
-
-
# leading 1
@deco1
# leading 2
@@ -65,11 +40,7 @@
# leading 4
def decorated():
pass
-
-
some = statement
-
-
# leading 1
@deco1
# leading 2
@@ -80,11 +51,7 @@
# leading 4
def decorated_with_split_leading_comments():
pass
-
-
some = statement
-
-
# leading 1
@deco1
# leading 2
@@ -95,66 +62,44 @@
# leading 4 that already has an empty line
def decorated_with_split_leading_comments():
pass
-
-
def main():
if a:
# Leading comment before inline function # Leading comment before inline function
def inline(): def inline():
pass pass
@ -256,10 +176,7 @@ def bar():
else: else:
# More leading comments # More leading comments
def inline_after_else(): def inline_after_else():
pass @@ -117,11 +116,9 @@
-
-
if a:
# Leading comment before "top-level inline" function # Leading comment before "top-level inline" function
def top_level_quote_inline(): def top_level_quote_inline():
pass pass
@ -271,39 +188,24 @@ def bar():
else: else:
# More leading comments # More leading comments
def top_level_quote_inline_after_else(): def top_level_quote_inline_after_else():
pass @@ -138,7 +135,6 @@
-
-
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. # Regression test for https://github.com/psf/black/issues/3454.
def foo(): def foo():
pass pass
- # Trailing comment that belongs to this function - # Trailing comment that belongs to this function
-
-
@decorator1 @decorator1
@decorator2 # fmt: skip @@ -150,9 +146,6 @@
def bar():
pass
-
-
# Regression test for https://github.com/psf/black/issues/3454. # Regression test for https://github.com/psf/black/issues/3454.
def foo(): def foo():
pass pass
- # Trailing comment that belongs to this function. - # Trailing comment that belongs to this function.
- # NOTE this comment only has one empty line below, and the formatter - # NOTE this comment only has one empty line below, and the formatter
- # should enforce two blank lines. - # should enforce two blank lines.
-
-
@decorator1 @decorator1
# A standalone comment
def bar():
``` ```
## Ruff Output ## Ruff Output
@ -312,35 +214,61 @@ def bar():
# Test for https://github.com/psf/black/issues/246. # Test for https://github.com/psf/black/issues/246.
some = statement some = statement
# This comment should be split from the statement above by two lines. # This comment should be split from the statement above by two lines.
def function(): def function():
pass pass
some = statement some = statement
# This multiline comments section # This multiline comments section
# should be split from the statement # should be split from the statement
# above by two lines. # above by two lines.
def function(): def function():
pass pass
some = statement some = statement
# This comment should be split from the statement above by two lines. # This comment should be split from the statement above by two lines.
async def async_function(): async def async_function():
pass pass
some = statement some = statement
# This comment should be split from the statement above by two lines. # This comment should be split from the statement above by two lines.
class MyClass: class MyClass:
pass pass
some = statement some = statement
# This should be stick to the statement above # This should be stick to the statement above
# This should be split from the above by two lines # This should be split from the above by two lines
class MyClassWithComplexLeadingComments: class MyClassWithComplexLeadingComments:
pass pass
class ClassWithDocstring: class ClassWithDocstring:
"""A docstring.""" """A docstring."""
# Leading comment after a class with just a docstring # Leading comment after a class with just a docstring
class MyClassAfterAnotherClassWithDocstring: class MyClassAfterAnotherClassWithDocstring:
pass pass
some = statement some = statement
# leading 1 # leading 1
@deco1 @deco1
# leading 2 # leading 2
@ -351,7 +279,11 @@ some = statement
# leading 4 # leading 4
def decorated(): def decorated():
pass pass
some = statement some = statement
# leading 1 # leading 1
@deco1 @deco1
# leading 2 # leading 2
@ -362,7 +294,11 @@ some = statement
# leading 4 # leading 4
def decorated_with_split_leading_comments(): def decorated_with_split_leading_comments():
pass pass
some = statement some = statement
# leading 1 # leading 1
@deco1 @deco1
# leading 2 # leading 2
@ -373,6 +309,8 @@ some = statement
# leading 4 that already has an empty line # leading 4 that already has an empty line
def decorated_with_split_leading_comments(): def decorated_with_split_leading_comments():
pass pass
def main(): def main():
if a: if a:
# Leading comment before inline function # Leading comment before inline function
@ -385,6 +323,8 @@ def main():
# More leading comments # More leading comments
def inline_after_else(): def inline_after_else():
pass pass
if a: if a:
# Leading comment before "top-level inline" function # Leading comment before "top-level inline" function
def top_level_quote_inline(): def top_level_quote_inline():
@ -396,21 +336,31 @@ else:
# More leading comments # More leading comments
def top_level_quote_inline_after_else(): def top_level_quote_inline_after_else():
pass pass
class MyClass: class MyClass:
# First method has no empty lines between bare class def. # First method has no empty lines between bare class def.
# More comments. # More comments.
def first_method(self): def first_method(self):
pass pass
# Regression test for https://github.com/psf/black/issues/3454. # Regression test for https://github.com/psf/black/issues/3454.
def foo(): def foo():
pass pass
@decorator1 @decorator1
@decorator2 # fmt: skip @decorator2 # fmt: skip
def bar(): def bar():
pass pass
# Regression test for https://github.com/psf/black/issues/3454. # Regression test for https://github.com/psf/black/issues/3454.
def foo(): def foo():
pass pass
@decorator1 @decorator1
# A standalone comment # A standalone comment
def bar(): def bar():

View file

@ -32,7 +32,7 @@ def function(a:int=42):
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,23 +1,16 @@ @@ -1,23 +1,20 @@
-from .config import ( -from .config import (
- ConfigTypeAttributes, - ConfigTypeAttributes,
- Int, - Int,
@ -41,16 +41,16 @@ def function(a:int=42):
+from .config import ( ConfigTypeAttributes, Int, Path, # String, +from .config import ( ConfigTypeAttributes, Int, Path, # String,
+ # DEFAULT_TYPE_ATTRIBUTES, + # DEFAULT_TYPE_ATTRIBUTES,
) )
-
result = 1 # A simple comment result = 1 # A simple comment
-result = (1,) # Another one -result = (1,) # Another one
-
+result = ( 1, ) # Another one +result = ( 1, ) # Another one
result = 1 #  type: ignore result = 1 #  type: ignore
result = 1 # This comment is talking about type: ignore result = 1 # This comment is talking about type: ignore
square = Square(4) #  type: Optional[Square] square = Square(4) #  type: Optional[Square]
-
-
-def function(a: int = 42): -def function(a: int = 42):
- """This docstring is already formatted - """This docstring is already formatted
- a - a
@ -72,11 +72,15 @@ def function(a:int=42):
from .config import ( ConfigTypeAttributes, Int, Path, # String, from .config import ( ConfigTypeAttributes, Int, Path, # String,
# DEFAULT_TYPE_ATTRIBUTES, # DEFAULT_TYPE_ATTRIBUTES,
) )
result = 1 # A simple comment result = 1 # A simple comment
result = ( 1, ) # Another one result = ( 1, ) # Another one
result = 1 #  type: ignore result = 1 #  type: ignore
result = 1 # This comment is talking about type: ignore result = 1 # This comment is talking about type: ignore
square = Square(4) #  type: Optional[Square] square = Square(4) #  type: Optional[Square]
def function(a:int=42): def function(a:int=42):
""" This docstring is already formatted """ This docstring is already formatted
a a

View file

@ -109,18 +109,7 @@ async def wat():
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -8,27 +8,17 @@ @@ -19,14 +19,9 @@
Possibly also many, many lines.
"""
-
import os.path
import sys
-
import a
from b.c import X # some noqa comment
-
try:
import fast import fast
except ImportError: except ImportError:
import slow as fast import slow as fast
@ -132,36 +121,12 @@ async def wat():
- # some strings - # some strings
- y # type: ignore - y # type: ignore
-) -)
-
-
+# some strings +# some strings
+y # type: ignore +y # type: ignore
def function(default=None): def function(default=None):
"""Docstring comes first. @@ -93,4 +88,4 @@
@@ -45,12 +35,8 @@
# This return is also commented for some reason.
return default
-
-
# Explains why we use global state.
GLOBAL_STATE = {"a": a(1), "b": a(2), "c": a(3)}
-
-
# Another comment!
# This time two lines.
@@ -73,8 +59,6 @@
self.spam = 4
"""Docstring for instance attribute spam."""
-
-
#' <h1>This is pweave!</h1>
@@ -93,4 +77,4 @@
# Some closing comments. # Some closing comments.
# Maybe Vim or Emacs directives for formatting. # Maybe Vim or Emacs directives for formatting.
@ -183,10 +148,13 @@ async def wat():
Possibly also many, many lines. Possibly also many, many lines.
""" """
import os.path import os.path
import sys import sys
import a import a
from b.c import X # some noqa comment from b.c import X # some noqa comment
try: try:
import fast import fast
except ImportError: except ImportError:
@ -194,6 +162,8 @@ except ImportError:
y = 1 y = 1
# some strings # some strings
y # type: ignore y # type: ignore
def function(default=None): def function(default=None):
"""Docstring comes first. """Docstring comes first.
@ -210,8 +180,12 @@ def function(default=None):
# This return is also commented for some reason. # This return is also commented for some reason.
return default return default
# Explains why we use global state. # Explains why we use global state.
GLOBAL_STATE = {"a": a(1), "b": a(2), "c": a(3)} GLOBAL_STATE = {"a": a(1), "b": a(2), "c": a(3)}
# Another comment! # Another comment!
# This time two lines. # This time two lines.
@ -234,6 +208,8 @@ class Foo:
self.spam = 4 self.spam = 4
"""Docstring for instance attribute spam.""" """Docstring for instance attribute spam."""
#' <h1>This is pweave!</h1> #' <h1>This is pweave!</h1>

View file

@ -63,57 +63,23 @@ def single_quote_docstring_over_line_limit2():
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,48 +1,32 @@ @@ -1,9 +1,11 @@
def docstring_almost_at_line_limit(): def docstring_almost_at_line_limit():
- """long docstring.................................................................""" - """long docstring................................................................."""
-
-
+ """long docstring................................................................. + """long docstring.................................................................
+ """ + """
def docstring_almost_at_line_limit_with_prefix(): def docstring_almost_at_line_limit_with_prefix():
- f"""long docstring................................................................""" - f"""long docstring................................................................"""
-
-
+ f"""long docstring................................................................ + f"""long docstring................................................................
+ """ + """
def mulitline_docstring_almost_at_line_limit(): def mulitline_docstring_almost_at_line_limit():
"""long docstring................................................................. @@ -45,4 +47,4 @@
..................................................................................
"""
-
-
def mulitline_docstring_almost_at_line_limit_with_prefix():
f"""long docstring................................................................
..................................................................................
"""
-
-
def docstring_at_line_limit():
"""long docstring................................................................"""
-
-
def docstring_at_line_limit_with_prefix():
f"""long docstring..............................................................."""
-
-
def multiline_docstring_at_line_limit():
"""first line-----------------------------------------------------------------------
second line----------------------------------------------------------------------"""
-
-
def multiline_docstring_at_line_limit_with_prefix():
f"""first line----------------------------------------------------------------------
second line----------------------------------------------------------------------"""
-
-
def single_quote_docstring_over_line_limit():
"We do not want to put the closing quote on a new line as that is invalid (see GH-3141)."
-
-
def single_quote_docstring_over_line_limit2(): def single_quote_docstring_over_line_limit2():
- "We do not want to put the closing quote on a new line as that is invalid (see GH-3141)." - "We do not want to put the closing quote on a new line as that is invalid (see GH-3141)."
+ 'We do not want to put the closing quote on a new line as that is invalid (see GH-3141).' + 'We do not want to put the closing quote on a new line as that is invalid (see GH-3141).'
@ -125,33 +91,51 @@ def single_quote_docstring_over_line_limit2():
def docstring_almost_at_line_limit(): def docstring_almost_at_line_limit():
"""long docstring................................................................. """long docstring.................................................................
""" """
def docstring_almost_at_line_limit_with_prefix(): def docstring_almost_at_line_limit_with_prefix():
f"""long docstring................................................................ f"""long docstring................................................................
""" """
def mulitline_docstring_almost_at_line_limit(): def mulitline_docstring_almost_at_line_limit():
"""long docstring................................................................. """long docstring.................................................................
.................................................................................. ..................................................................................
""" """
def mulitline_docstring_almost_at_line_limit_with_prefix(): def mulitline_docstring_almost_at_line_limit_with_prefix():
f"""long docstring................................................................ f"""long docstring................................................................
.................................................................................. ..................................................................................
""" """
def docstring_at_line_limit(): def docstring_at_line_limit():
"""long docstring................................................................""" """long docstring................................................................"""
def docstring_at_line_limit_with_prefix(): def docstring_at_line_limit_with_prefix():
f"""long docstring...............................................................""" f"""long docstring..............................................................."""
def multiline_docstring_at_line_limit(): def multiline_docstring_at_line_limit():
"""first line----------------------------------------------------------------------- """first line-----------------------------------------------------------------------
second line----------------------------------------------------------------------""" second line----------------------------------------------------------------------"""
def multiline_docstring_at_line_limit_with_prefix(): def multiline_docstring_at_line_limit_with_prefix():
f"""first line---------------------------------------------------------------------- f"""first line----------------------------------------------------------------------
second line----------------------------------------------------------------------""" second line----------------------------------------------------------------------"""
def single_quote_docstring_over_line_limit(): def single_quote_docstring_over_line_limit():
"We do not want to put the closing quote on a new line as that is invalid (see GH-3141)." "We do not want to put the closing quote on a new line as that is invalid (see GH-3141)."
def single_quote_docstring_over_line_limit2(): def single_quote_docstring_over_line_limit2():
'We do not want to put the closing quote on a new line as that is invalid (see GH-3141).' 'We do not want to put the closing quote on a new line as that is invalid (see GH-3141).'
``` ```

View file

@ -234,7 +234,7 @@ def stable_quote_normalization_with_immediate_inner_single_quote(self):
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,219 +1,157 @@ @@ -1,83 +1,85 @@
class MyClass: class MyClass:
+ """ Multiline + """ Multiline
+ class docstring + class docstring
@ -251,64 +251,64 @@ def stable_quote_normalization_with_immediate_inner_single_quote(self):
- method docstring - method docstring
- """ - """
- pass - pass
-
-
+ pass + pass
def foo(): def foo():
- """This is a docstring with - """This is a docstring with
- some lines of text here - some lines of text here
- """ - """
- return - return
-
-
+ """This is a docstring with + """This is a docstring with
+ some lines of text here + some lines of text here
+ """ + """
+ return + return
def bar(): def bar():
- """This is another docstring - """This is another docstring
- with more lines of text - with more lines of text
- """ - """
- return - return
-
-
+ '''This is another docstring + '''This is another docstring
+ with more lines of text + with more lines of text
+ ''' + '''
+ return + return
def baz(): def baz():
- '''"This" is a string with some - '''"This" is a string with some
- embedded "quotes"''' - embedded "quotes"'''
- return - return
-
-
+ '''"This" is a string with some + '''"This" is a string with some
+ embedded "quotes"''' + embedded "quotes"'''
+ return + return
def troz(): def troz():
- """Indentation with tabs - """Indentation with tabs
- is just as OK - is just as OK
- """ - """
- return - return
-
-
+ '''Indentation with tabs + '''Indentation with tabs
+ is just as OK + is just as OK
+ ''' + '''
+ return + return
def zort(): def zort():
- """Another - """Another
- multiline - multiline
- docstring - docstring
- """ - """
- pass - pass
-
-
+ """Another + """Another
+ multiline + multiline
+ docstring + docstring
+ """ + """
+ pass + pass
def poit(): def poit():
- """ - """
- Lorem ipsum dolor sit amet. - Lorem ipsum dolor sit amet.
@ -323,8 +323,6 @@ def stable_quote_normalization_with_immediate_inner_single_quote(self):
- - aliquip ex ea commodo consequat - - aliquip ex ea commodo consequat
- """ - """
- pass - pass
-
-
+ Consectetur adipiscing elit: + Consectetur adipiscing elit:
+ - sed do eiusmod tempor incididunt ut labore + - sed do eiusmod tempor incididunt ut labore
+ - dolore magna aliqua + - dolore magna aliqua
@ -333,16 +331,26 @@ def stable_quote_normalization_with_immediate_inner_single_quote(self):
+ - aliquip ex ea commodo consequat + - aliquip ex ea commodo consequat
+ """ + """
+ pass + pass
def under_indent(): def under_indent():
- """ - """
- These lines are indented in a way that does not - These lines are indented in a way that does not
- make sense. - make sense.
- """
- pass
+ """ + """
+ These lines are indented in a way that does not + These lines are indented in a way that does not
+make sense. +make sense.
+ """ + """
+ pass + pass
+def over_indent():
def over_indent():
- """
- This has a shallow indent
- - But some lines are deeper
- - And the closing quote is too deep
+ """ + """
+ This has a shallow indent + This has a shallow indent
+ - But some lines are deeper + - But some lines are deeper
@ -350,90 +358,78 @@ def stable_quote_normalization_with_immediate_inner_single_quote(self):
""" """
- pass - pass
+ pass + pass
+def single_line():
+ """But with a newline after it!
-
-def over_indent(): def single_line():
- """
- This has a shallow indent
- - But some lines are deeper
- - And the closing quote is too deep
"""
pass
-
-
-def single_line():
- """But with a newline after it!""" - """But with a newline after it!"""
- pass + """But with a newline after it!
- +
- + """
def this(): pass
r"""
'hey ho'
""" @@ -88,25 +90,30 @@
-
-
def that(): def that():
- """ "hey yah" """ - """ "hey yah" """
-
-
+ """ "hey yah" """ + """ "hey yah" """
def and_that(): def and_that():
- """ - """
- "hey yah" """ - "hey yah" """
-
-
+ """ + """
+ "hey yah" """ + "hey yah" """
def and_this(): def and_this():
- '''
- "hey yah"'''
+ ''' + '''
+ "hey yah"''' + "hey yah"'''
+def multiline_whitespace():
def multiline_whitespace():
- """ """
+ ''' + '''
+ +
+ +
+ +
+ +
''' + '''
- "hey yah"'''
-
-
-def multiline_whitespace():
- """ """
-
-
def oneline_whitespace(): def oneline_whitespace():
- """ """ - """ """
-
-
+ ''' ''' + ''' '''
def empty(): def empty():
"""""" @@ -114,12 +121,11 @@
-
-
def single_quotes(): def single_quotes():
- "testing" - "testing"
- + 'testing'
-
-def believe_it_or_not_this_is_in_the_py_stdlib(): -def believe_it_or_not_this_is_in_the_py_stdlib():
- ''' - '''
- "hey yah"''' - "hey yah"'''
-
-
+ 'testing'
+def believe_it_or_not_this_is_in_the_py_stdlib(): ''' +def believe_it_or_not_this_is_in_the_py_stdlib(): '''
+"hey yah"''' +"hey yah"'''
def ignored_docstring(): def ignored_docstring():
"""a => \ @@ -128,32 +134,32 @@
b"""
-
-
def single_line_docstring_with_whitespace(): def single_line_docstring_with_whitespace():
- """This should be stripped""" - """This should be stripped"""
-
-
+ """ This should be stripped """ + """ This should be stripped """
def docstring_with_inline_tabs_and_space_indentation(): def docstring_with_inline_tabs_and_space_indentation():
"""hey """hey
@ -449,8 +445,8 @@ def stable_quote_normalization_with_immediate_inner_single_quote(self):
+ +
+ line ends with some tabs + line ends with some tabs
""" """
-
-
def docstring_with_inline_tabs_and_tab_indentation(): def docstring_with_inline_tabs_and_tab_indentation():
- """hey - """hey
+ """hey + """hey
@ -463,8 +459,6 @@ def stable_quote_normalization_with_immediate_inner_single_quote(self):
- line ends with some tabs - line ends with some tabs
- """ - """
- pass - pass
-
-
+ tab separated value + tab separated value
+ tab at start of line and then a tab separated value + tab at start of line and then a tab separated value
+ multiple tabs at the beginning and inline + multiple tabs at the beginning and inline
@ -473,69 +467,51 @@ def stable_quote_normalization_with_immediate_inner_single_quote(self):
+ line ends with some tabs + line ends with some tabs
+ """ + """
+ pass + pass
def backslash_space(): def backslash_space():
"""\ """ @@ -161,14 +167,14 @@
-
-
def multiline_backslash_1(): def multiline_backslash_1():
- """ - """
+ ''' + '''
hey\there\ hey\there\
- \ """ - \ """
-
-
+ \ ''' + \ '''
def multiline_backslash_2(): def multiline_backslash_2():
- """ - """
- hey there \ """ - hey there \ """
-
-
+ ''' + '''
+ hey there \ ''' + hey there \ '''
# Regression test for #3425 # Regression test for #3425
def multiline_backslash_really_long_dont_crash(): @@ -178,8 +184,8 @@
"""
hey there hello guten tag hi hoow are you ola zdravstvuyte ciao como estas ca va \ """
-
-
def multiline_backslash_3(): def multiline_backslash_3():
- """ - """
- already escaped \\""" - already escaped \\"""
-
-
+ ''' + '''
+ already escaped \\ ''' + already escaped \\ '''
def my_god_its_full_of_stars_1(): def my_god_its_full_of_stars_1():
"I'm sorry Dave\u2001" @@ -188,7 +194,7 @@
-
-
# the space below is actually a \u2001, removed in output # the space below is actually a \u2001, removed in output
def my_god_its_full_of_stars_2(): def my_god_its_full_of_stars_2():
- "I'm sorry Dave" - "I'm sorry Dave"
-
-
+ "I'm sorry Dave" + "I'm sorry Dave"
def docstring_almost_at_line_limit(): def docstring_almost_at_line_limit():
"""long docstring.................................................................""" @@ -213,7 +219,7 @@
-
-
def docstring_almost_at_line_limit2():
"""long docstring.................................................................
..................................................................................
"""
-
-
def docstring_at_line_limit():
"""long docstring................................................................"""
-
-
def multiline_docstring_at_line_limit():
"""first line-----------------------------------------------------------------------
second line----------------------------------------------------------------------"""
-
-
def stable_quote_normalization_with_immediate_inner_single_quote(self): def stable_quote_normalization_with_immediate_inner_single_quote(self):
- """'<text here> - """'<text here>
+ ''''<text here> + ''''<text here>
@ -558,31 +534,43 @@ class MyClass:
method docstring method docstring
""" """
pass pass
def foo(): def foo():
"""This is a docstring with """This is a docstring with
some lines of text here some lines of text here
""" """
return return
def bar(): def bar():
'''This is another docstring '''This is another docstring
with more lines of text with more lines of text
''' '''
return return
def baz(): def baz():
'''"This" is a string with some '''"This" is a string with some
embedded "quotes"''' embedded "quotes"'''
return return
def troz(): def troz():
'''Indentation with tabs '''Indentation with tabs
is just as OK is just as OK
''' '''
return return
def zort(): def zort():
"""Another """Another
multiline multiline
docstring docstring
""" """
pass pass
def poit(): def poit():
""" """
Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.
@ -595,12 +583,16 @@ def poit():
- aliquip ex ea commodo consequat - aliquip ex ea commodo consequat
""" """
pass pass
def under_indent(): def under_indent():
""" """
These lines are indented in a way that does not These lines are indented in a way that does not
make sense. make sense.
""" """
pass pass
def over_indent(): def over_indent():
""" """
This has a shallow indent This has a shallow indent
@ -608,23 +600,35 @@ def over_indent():
- And the closing quote is too deep - And the closing quote is too deep
""" """
pass pass
def single_line(): def single_line():
"""But with a newline after it! """But with a newline after it!
""" """
pass pass
def this(): def this():
r""" r"""
'hey ho' 'hey ho'
""" """
def that(): def that():
""" "hey yah" """ """ "hey yah" """
def and_that(): def and_that():
""" """
"hey yah" """ "hey yah" """
def and_this(): def and_this():
''' '''
"hey yah"''' "hey yah"'''
def multiline_whitespace(): def multiline_whitespace():
''' '''
@ -632,19 +636,33 @@ def multiline_whitespace():
''' '''
def oneline_whitespace(): def oneline_whitespace():
''' ''' ''' '''
def empty(): def empty():
"""""" """"""
def single_quotes(): def single_quotes():
'testing' 'testing'
def believe_it_or_not_this_is_in_the_py_stdlib(): ''' def believe_it_or_not_this_is_in_the_py_stdlib(): '''
"hey yah"''' "hey yah"'''
def ignored_docstring(): def ignored_docstring():
"""a => \ """a => \
b""" b"""
def single_line_docstring_with_whitespace(): def single_line_docstring_with_whitespace():
""" This should be stripped """ """ This should be stripped """
def docstring_with_inline_tabs_and_space_indentation(): def docstring_with_inline_tabs_and_space_indentation():
"""hey """hey
@ -655,6 +673,8 @@ def docstring_with_inline_tabs_and_space_indentation():
line ends with some tabs line ends with some tabs
""" """
def docstring_with_inline_tabs_and_tab_indentation(): def docstring_with_inline_tabs_and_tab_indentation():
"""hey """hey
@ -666,40 +686,64 @@ def docstring_with_inline_tabs_and_tab_indentation():
line ends with some tabs line ends with some tabs
""" """
pass pass
def backslash_space(): def backslash_space():
"""\ """ """\ """
def multiline_backslash_1(): def multiline_backslash_1():
''' '''
hey\there\ hey\there\
\ ''' \ '''
def multiline_backslash_2(): def multiline_backslash_2():
''' '''
hey there \ ''' hey there \ '''
# Regression test for #3425 # Regression test for #3425
def multiline_backslash_really_long_dont_crash(): def multiline_backslash_really_long_dont_crash():
""" """
hey there hello guten tag hi hoow are you ola zdravstvuyte ciao como estas ca va \ """ hey there hello guten tag hi hoow are you ola zdravstvuyte ciao como estas ca va \ """
def multiline_backslash_3(): def multiline_backslash_3():
''' '''
already escaped \\ ''' already escaped \\ '''
def my_god_its_full_of_stars_1(): def my_god_its_full_of_stars_1():
"I'm sorry Dave\u2001" "I'm sorry Dave\u2001"
# the space below is actually a \u2001, removed in output # the space below is actually a \u2001, removed in output
def my_god_its_full_of_stars_2(): def my_god_its_full_of_stars_2():
"I'm sorry Dave" "I'm sorry Dave"
def docstring_almost_at_line_limit(): def docstring_almost_at_line_limit():
"""long docstring.................................................................""" """long docstring................................................................."""
def docstring_almost_at_line_limit2(): def docstring_almost_at_line_limit2():
"""long docstring................................................................. """long docstring.................................................................
.................................................................................. ..................................................................................
""" """
def docstring_at_line_limit(): def docstring_at_line_limit():
"""long docstring................................................................""" """long docstring................................................................"""
def multiline_docstring_at_line_limit(): def multiline_docstring_at_line_limit():
"""first line----------------------------------------------------------------------- """first line-----------------------------------------------------------------------
second line----------------------------------------------------------------------""" second line----------------------------------------------------------------------"""
def stable_quote_normalization_with_immediate_inner_single_quote(self): def stable_quote_normalization_with_immediate_inner_single_quote(self):
''''<text here> ''''<text here>

View file

@ -105,10 +105,8 @@ def g():
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,11 +1,9 @@ @@ -3,9 +3,9 @@
"""Docstring."""
-
-
# leading comment # leading comment
def f(): def f():
- NO = "" - NO = ""
@ -120,7 +118,7 @@ def g():
t = leaf.type t = leaf.type
p = leaf.parent # trailing comment p = leaf.parent # trailing comment
@@ -16,14 +14,19 @@ @@ -16,14 +16,19 @@
if t == token.COMMENT: # another trailing comment if t == token.COMMENT: # another trailing comment
return DOUBLESPACE return DOUBLESPACE
@ -140,17 +138,12 @@ def g():
if prevp.type == token.EQUAL: if prevp.type == token.EQUAL:
if prevp.parent and prevp.parent.type in { if prevp.parent and prevp.parent.type in {
syms.typedargslist, syms.typedargslist,
@@ -43,17 +46,14 @@ @@ -48,12 +53,11 @@
syms.dictsetmaker,
}:
return NO
-
-
############################################################################### ###############################################################################
# SECTION BECAUSE SECTIONS # SECTION BECAUSE SECTIONS
############################################################################### ###############################################################################
- -
def g(): def g():
- NO = "" - NO = ""
- SPACE = " " - SPACE = " "
@ -161,7 +154,7 @@ def g():
t = leaf.type t = leaf.type
p = leaf.parent p = leaf.parent
@@ -67,7 +67,7 @@ @@ -67,7 +71,7 @@
return DOUBLESPACE return DOUBLESPACE
# Another comment because more comments # Another comment because more comments
@ -176,6 +169,8 @@ def g():
```py ```py
"""Docstring.""" """Docstring."""
# leading comment # leading comment
def f(): def f():
NO = '' NO = ''
@ -223,6 +218,8 @@ def f():
syms.dictsetmaker, syms.dictsetmaker,
}: }:
return NO return NO
############################################################################### ###############################################################################
# SECTION BECAUSE SECTIONS # SECTION BECAUSE SECTIONS
############################################################################### ###############################################################################

View file

@ -511,26 +511,22 @@ last_call()
Ø = set() Ø = set()
authors.łukasz.say_thanks() authors.łukasz.say_thanks()
mapping = { mapping = {
@@ -233,138 +170,84 @@ @@ -237,134 +174,86 @@
C: 0.1 * (10.0 / 12),
D: 0.1 * (10.0 / 12),
}
-
-
def gen(): def gen():
yield from outside_of_generator yield from outside_of_generator
- a = yield - a = yield
- b = yield - b = yield
- c = yield - c = yield
-
-
+ a = (yield) + a = (yield)
+ b = ((yield)) + b = ((yield))
+ c = (((yield))) + c = (((yield)))
async def f(): async def f():
await some.complicated[0].call(with_args=(True or (1 is not 1))) await some.complicated[0].call(with_args=(True or (1 is not 1)))
-
-
-print(*[] or [1]) -print(*[] or [1])
+print(* [] or [1]) +print(* [] or [1])
print(**{1: 3} if False else {x: x for x in range(3)}) print(**{1: 3} if False else {x: x for x in range(3)})
@ -860,13 +856,19 @@ mapping = {
C: 0.1 * (10.0 / 12), C: 0.1 * (10.0 / 12),
D: 0.1 * (10.0 / 12), D: 0.1 * (10.0 / 12),
} }
def gen(): def gen():
yield from outside_of_generator yield from outside_of_generator
a = (yield) a = (yield)
b = ((yield)) b = ((yield))
c = (((yield))) c = (((yield)))
async def f(): async def f():
await some.complicated[0].call(with_args=(True or (1 is not 1))) await some.complicated[0].call(with_args=(True or (1 is not 1)))
print(* [] or [1]) print(* [] or [1])
print(**{1: 3} if False else {x: x for x in range(3)}) print(**{1: 3} if False else {x: x for x in range(3)})
print(* lambda x: x) print(* lambda x: x)

View file

@ -53,32 +53,34 @@ def test_calculate_fades():
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,8 +1,6 @@ @@ -3,6 +3,7 @@
import pytest
-
TmSt = 1 TmSt = 1
TmEx = 2 TmEx = 2
-
+
# fmt: off # fmt: off
# Test data: # Test data:
@@ -17,19 +15,15 @@ @@ -18,18 +19,22 @@
])
def test_fader(test): def test_fader(test):
pass pass
-
+
def check_fader(test): def check_fader(test):
pass pass
-
+
def verify_fader(test): def verify_fader(test):
# misaligned comment # misaligned comment
pass pass
-
+
def verify_fader(test): def verify_fader(test):
"""Hey, ho.""" """Hey, ho."""
assert test.passed() assert test.passed()
-
+
def test_calculate_fades(): def test_calculate_fades():
calcs = [ calcs = [
# one is zero/none # one is zero/none
@ -88,8 +90,11 @@ def test_calculate_fades():
```py ```py
import pytest import pytest
TmSt = 1 TmSt = 1
TmEx = 2 TmEx = 2
# fmt: off # fmt: off
# Test data: # Test data:
@ -104,15 +109,23 @@ TmEx = 2
]) ])
def test_fader(test): def test_fader(test):
pass pass
def check_fader(test): def check_fader(test):
pass pass
def verify_fader(test): def verify_fader(test):
# misaligned comment # misaligned comment
pass pass
def verify_fader(test): def verify_fader(test):
"""Hey, ho.""" """Hey, ho."""
assert test.passed() assert test.passed()
def test_calculate_fades(): def test_calculate_fades():
calcs = [ calcs = [
# one is zero/none # one is zero/none

View file

@ -30,8 +30,11 @@ x = [
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -12,4 +12,6 @@ @@ -10,6 +10,9 @@
1, 2,
3, 4,
] ]
+
# fmt: on # fmt: on
-x = [1, 2, 3, 4] -x = [1, 2, 3, 4]
@ -55,6 +58,7 @@ x = [
1, 2, 1, 2,
3, 4, 3, 4,
] ]
# fmt: on # fmt: on
x = [ x = [

View file

@ -26,14 +26,15 @@ def f(): pass
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -4,17 +4,9 @@ @@ -4,17 +4,11 @@
3, 4, 3, 4,
]) ])
# fmt: on # fmt: on
-def f(): -def f():
- pass - pass
- +def f(): pass
-
-@test( -@test(
- [ - [
- 1, - 1,
@ -44,7 +45,6 @@ def f(): pass
-) -)
-def f(): -def f():
- pass - pass
+def f(): pass
+@test([ +@test([
+ 1, 2, + 1, 2,
+ 3, 4, + 3, 4,
@ -62,6 +62,8 @@ def f(): pass
]) ])
# fmt: on # fmt: on
def f(): pass def f(): pass
@test([ @test([
1, 2, 1, 2,
3, 4, 3, 4,

View file

@ -106,60 +106,37 @@ elif unformatted:
# Regression test for https://github.com/psf/black/issues/2015. # Regression test for https://github.com/psf/black/issues/2015.
run( run(
# fmt: off # fmt: off
@@ -22,8 +20,6 @@ @@ -44,7 +42,7 @@
+ path,
check=True,
)
-
-
# Regression test for https://github.com/psf/black/issues/3026.
def test_func():
# yapf: disable
@@ -34,8 +30,6 @@
return True
return False
-
-
# Regression test for https://github.com/psf/black/issues/2567.
if True:
# fmt: off
@@ -44,9 +38,7 @@
print ( "This won't be formatted" ) print ( "This won't be formatted" )
print ( "This won't be formatted either" ) print ( "This won't be formatted either" )
else: else:
- print("This will be formatted") - print("This will be formatted")
-
-
+ print ( "This will be formatted" ) + print ( "This will be formatted" )
# Regression test for https://github.com/psf/black/issues/3184. # Regression test for https://github.com/psf/black/issues/3184.
class A: @@ -61,7 +59,7 @@
async def call(param):
@@ -61,27 +53,18 @@
elif param[0:4] in ("ZZZZ",): elif param[0:4] in ("ZZZZ",):
print ( "This won't be formatted either" ) print ( "This won't be formatted either" )
- print("This will be formatted") - print("This will be formatted")
-
-
+ print ( "This will be formatted" ) + print ( "This will be formatted" )
# Regression test for https://github.com/psf/black/issues/2985. # Regression test for https://github.com/psf/black/issues/2985.
class Named(t.Protocol): @@ -72,10 +70,7 @@
# fmt: off
@property
def this_wont_be_formatted ( self ) -> str: ...
-
-
class Factory(t.Protocol): class Factory(t.Protocol):
- def this_will_be_formatted(self, **kwargs) -> Named: - def this_will_be_formatted(self, **kwargs) -> Named:
- ... - ...
- -
- # fmt: on - # fmt: on
-
-
+ def this_will_be_formatted ( self, **kwargs ) -> Named: ... + def this_will_be_formatted ( self, **kwargs ) -> Named: ...
# Regression test for https://github.com/psf/black/issues/3436. # Regression test for https://github.com/psf/black/issues/3436.
if x: @@ -83,5 +78,5 @@
return x return x
# fmt: off # fmt: off
elif unformatted: elif unformatted:
@ -194,6 +171,8 @@ run(
+ path, + path,
check=True, check=True,
) )
# Regression test for https://github.com/psf/black/issues/3026. # Regression test for https://github.com/psf/black/issues/3026.
def test_func(): def test_func():
# yapf: disable # yapf: disable
@ -204,6 +183,8 @@ def test_func():
return True return True
return False return False
# Regression test for https://github.com/psf/black/issues/2567. # Regression test for https://github.com/psf/black/issues/2567.
if True: if True:
# fmt: off # fmt: off
@ -213,6 +194,8 @@ if True:
print ( "This won't be formatted either" ) print ( "This won't be formatted either" )
else: else:
print ( "This will be formatted" ) print ( "This will be formatted" )
# Regression test for https://github.com/psf/black/issues/3184. # Regression test for https://github.com/psf/black/issues/3184.
class A: class A:
async def call(param): async def call(param):
@ -228,13 +211,19 @@ class A:
print ( "This won't be formatted either" ) print ( "This won't be formatted either" )
print ( "This will be formatted" ) print ( "This will be formatted" )
# Regression test for https://github.com/psf/black/issues/2985. # Regression test for https://github.com/psf/black/issues/2985.
class Named(t.Protocol): class Named(t.Protocol):
# fmt: off # fmt: off
@property @property
def this_wont_be_formatted ( self ) -> str: ... def this_wont_be_formatted ( self ) -> str: ...
class Factory(t.Protocol): class Factory(t.Protocol):
def this_will_be_formatted ( self, **kwargs ) -> Named: ... def this_will_be_formatted ( self, **kwargs ) -> Named: ...
# Regression test for https://github.com/psf/black/issues/3436. # Regression test for https://github.com/psf/black/issues/3436.
if x: if x:
return x return x

View file

@ -199,13 +199,10 @@ d={'a':1,
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,20 +1,17 @@ @@ -4,17 +4,18 @@
#!/usr/bin/env python3
import asyncio
import sys
-
from third_party import X, Y, Z from third_party import X, Y, Z
-
-from library import some_connection, some_decorator -from library import some_connection, some_decorator
- -
+from library import some_connection, \ +from library import some_connection, \
@ -216,6 +213,8 @@ d={'a':1,
# fmt: on # fmt: on
-f"trigger 3.6 mode" -f"trigger 3.6 mode"
+f'trigger 3.6 mode' +f'trigger 3.6 mode'
+
+
# Comment 1 # Comment 1
# Comment 2 # Comment 2
@ -223,15 +222,37 @@ d={'a':1,
# fmt: off # fmt: off
def func_no_args(): def func_no_args():
@@ -39,72 +36,41 @@ @@ -26,11 +27,15 @@
continue
exec('new-style exec', {}, {})
return None
+
+
async def coroutine(arg, exec=False):
'Single-line docstring. Multiline is harder to reformat.'
async with some_connection() as conn:
await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', timeout=2)
await asyncio.sleep(1)
+
+
@asyncio.coroutine
@some_decorator(
with_args=True,
@@ -38,28 +43,19 @@
)
def function_signature_stress_test(number:int,no_annotation=None,text:str='default',* ,debug:bool=False,**kwargs) -> str: def function_signature_stress_test(number:int,no_annotation=None,text:str='default',* ,debug:bool=False,**kwargs) -> str:
return text[number:-1] return text[number:-1]
+
+
# fmt: on # fmt: on
-def spaces(a=1, b=(), c=[], d={}, e=True, f=-1, g=1 if False else 2, h="", i=r""): -def spaces(a=1, b=(), c=[], d={}, e=True, f=-1, g=1 if False else 2, h="", i=r""):
- offset = attr.ib(default=attr.Factory(lambda: _r.uniform(1, 2))) - offset = attr.ib(default=attr.Factory(lambda: _r.uniform(1, 2)))
- assert task._cancel_stack[: len(old_stack)] == old_stack - assert task._cancel_stack[: len(old_stack)] == old_stack
- +def spaces(a=1, b=(), c=[], d={}, e=True, f=-1, g=1 if False else 2, h="", i=r''):
- + offset = attr.ib(default=attr.Factory( lambda: _r.uniform(1, 2)))
+ assert task._cancel_stack[:len(old_stack)] == old_stack
-def spaces_types( -def spaces_types(
- a: int = 1, - a: int = 1,
- b: tuple = (), - b: tuple = (),
@ -244,53 +265,43 @@ d={'a':1,
- i: str = r"", - i: str = r"",
-): -):
- ... - ...
- +def spaces_types(a: int = 1, b: tuple = (), c: list = [], d: dict = {}, e: bool = True, f: int = -1, g: int = 1 if False else 2, h: str = "", i: str = r''): ...
-
-def spaces2(result=_core.Value(None)): -def spaces2(result=_core.Value(None)):
- ... - ...
-
-
+def spaces(a=1, b=(), c=[], d={}, e=True, f=-1, g=1 if False else 2, h="", i=r''):
+ offset = attr.ib(default=attr.Factory( lambda: _r.uniform(1, 2)))
+ assert task._cancel_stack[:len(old_stack)] == old_stack
+def spaces_types(a: int = 1, b: tuple = (), c: list = [], d: dict = {}, e: bool = True, f: int = -1, g: int = 1 if False else 2, h: str = "", i: str = r''): ...
+def spaces2(result= _core.Value(None)): +def spaces2(result= _core.Value(None)):
+ ... + ...
something = { something = {
# fmt: off @@ -74,23 +70,20 @@
key: 'value',
}
-
-
def subscriptlist():
atom[
# fmt: off
'some big and', 'some big and',
'complex subscript', 'complex subscript',
# fmt: on # fmt: on
- goes + here, - goes + here,
- andhere, - andhere,
- ] - ]
-
-
+ goes + here, andhere, + goes + here, andhere,
+ ] + ]
def import_as_names(): def import_as_names():
# fmt: off # fmt: off
from hello import a, b from hello import a, b
'unformatted' 'unformatted'
- # fmt: on - # fmt: on
-
-
def testlist_star_expr(): def testlist_star_expr():
# fmt: off # fmt: off
a , b = *hello a , b = *hello
'unformatted' 'unformatted'
- # fmt: on - # fmt: on
-
-
def yield_expr(): def yield_expr():
# fmt: off @@ -98,11 +91,10 @@
yield hello yield hello
'unformatted' 'unformatted'
# fmt: on # fmt: on
@ -300,22 +311,18 @@ d={'a':1,
( yield hello ) ( yield hello )
'unformatted' 'unformatted'
- # fmt: on - # fmt: on
-
-
def example(session): def example(session):
# fmt: off @@ -113,7 +105,6 @@
result = session\
@@ -113,9 +79,6 @@
models.Customer.email == email_address)\ models.Customer.email == email_address)\
.order_by(models.Customer.id.asc())\ .order_by(models.Customer.id.asc())\
.all() .all()
- # fmt: on - # fmt: on
-
-
def off_and_on_without_data():
"""All comments here are technically on the same prefix.
@@ -123,12 +86,12 @@
def off_and_on_without_data():
@@ -123,8 +114,10 @@
""" """
# fmt: off # fmt: off
@ -326,12 +333,8 @@ d={'a':1,
+ +
# fmt: on # fmt: on
pass pass
-
- @@ -137,21 +130,12 @@
def on_and_off_broken():
"""Another known limitation."""
# fmt: on
@@ -137,21 +100,10 @@
and_=indeed . it is not formatted and_=indeed . it is not formatted
because . the . handling . inside . generate_ignored_nodes() because . the . handling . inside . generate_ignored_nodes()
now . considers . multiple . fmt . directives . within . one . prefix now . considers . multiple . fmt . directives . within . one . prefix
@ -339,8 +342,8 @@ d={'a':1,
- # fmt: off - # fmt: off
- # ...but comments still get reformatted even though they should not be - # ...but comments still get reformatted even though they should not be
- # fmt: on - # fmt: on
-
-
def long_lines(): def long_lines():
if True: if True:
typedargslist.extend( typedargslist.extend(
@ -354,22 +357,18 @@ d={'a':1,
) )
# fmt: off # fmt: off
a = ( a = (
@@ -182,24 +134,19 @@ @@ -186,20 +170,19 @@
re.MULTILINE|re.VERBOSE
# fmt: on
)
-
-
def single_literal_yapf_disable(): def single_literal_yapf_disable():
"""Black does not support this.""" """Black does not support this."""
- BAZ = {(1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12)} # yapf: disable - BAZ = {(1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12)} # yapf: disable
-
-
+ BAZ = { + BAZ = {
+ (1, 2, 3, 4), + (1, 2, 3, 4),
+ (5, 6, 7, 8), + (5, 6, 7, 8),
+ (9, 10, 11, 12) + (9, 10, 11, 12)
+ } + }
cfg.rule( cfg.rule(
- "Default", - "Default",
- "address", - "address",
@ -388,7 +387,7 @@ d={'a':1,
# fmt: off # fmt: off
xxxxxxx_xxxxxxxxxxxx={ xxxxxxx_xxxxxxxxxxxx={
"xxxxxxxx": { "xxxxxxxx": {
@@ -214,7 +161,7 @@ @@ -214,7 +197,7 @@
}, },
}, },
# fmt: on # fmt: on
@ -405,7 +404,9 @@ d={'a':1,
#!/usr/bin/env python3 #!/usr/bin/env python3
import asyncio import asyncio
import sys import sys
from third_party import X, Y, Z from third_party import X, Y, Z
from library import some_connection, \ from library import some_connection, \
some_decorator some_decorator
# fmt: off # fmt: off
@ -413,6 +414,8 @@ from third_party import (X,
Y, Z) Y, Z)
# fmt: on # fmt: on
f'trigger 3.6 mode' f'trigger 3.6 mode'
# Comment 1 # Comment 1
# Comment 2 # Comment 2
@ -427,11 +430,15 @@ def func_no_args():
continue continue
exec('new-style exec', {}, {}) exec('new-style exec', {}, {})
return None return None
async def coroutine(arg, exec=False): async def coroutine(arg, exec=False):
'Single-line docstring. Multiline is harder to reformat.' 'Single-line docstring. Multiline is harder to reformat.'
async with some_connection() as conn: async with some_connection() as conn:
await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', timeout=2) await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', timeout=2)
await asyncio.sleep(1) await asyncio.sleep(1)
@asyncio.coroutine @asyncio.coroutine
@some_decorator( @some_decorator(
with_args=True, with_args=True,
@ -439,17 +446,27 @@ many_args=[1,2,3]
) )
def function_signature_stress_test(number:int,no_annotation=None,text:str='default',* ,debug:bool=False,**kwargs) -> str: def function_signature_stress_test(number:int,no_annotation=None,text:str='default',* ,debug:bool=False,**kwargs) -> str:
return text[number:-1] return text[number:-1]
# fmt: on # fmt: on
def spaces(a=1, b=(), c=[], d={}, e=True, f=-1, g=1 if False else 2, h="", i=r''): def spaces(a=1, b=(), c=[], d={}, e=True, f=-1, g=1 if False else 2, h="", i=r''):
offset = attr.ib(default=attr.Factory( lambda: _r.uniform(1, 2))) offset = attr.ib(default=attr.Factory( lambda: _r.uniform(1, 2)))
assert task._cancel_stack[:len(old_stack)] == old_stack assert task._cancel_stack[:len(old_stack)] == old_stack
def spaces_types(a: int = 1, b: tuple = (), c: list = [], d: dict = {}, e: bool = True, f: int = -1, g: int = 1 if False else 2, h: str = "", i: str = r''): ... def spaces_types(a: int = 1, b: tuple = (), c: list = [], d: dict = {}, e: bool = True, f: int = -1, g: int = 1 if False else 2, h: str = "", i: str = r''): ...
def spaces2(result= _core.Value(None)): def spaces2(result= _core.Value(None)):
... ...
something = { something = {
# fmt: off # fmt: off
key: 'value', key: 'value',
} }
def subscriptlist(): def subscriptlist():
atom[ atom[
# fmt: off # fmt: off
@ -458,14 +475,20 @@ def subscriptlist():
# fmt: on # fmt: on
goes + here, andhere, goes + here, andhere,
] ]
def import_as_names(): def import_as_names():
# fmt: off # fmt: off
from hello import a, b from hello import a, b
'unformatted' 'unformatted'
def testlist_star_expr(): def testlist_star_expr():
# fmt: off # fmt: off
a , b = *hello a , b = *hello
'unformatted' 'unformatted'
def yield_expr(): def yield_expr():
# fmt: off # fmt: off
yield hello yield hello
@ -475,6 +498,8 @@ def yield_expr():
# fmt: off # fmt: off
( yield hello ) ( yield hello )
'unformatted' 'unformatted'
def example(session): def example(session):
# fmt: off # fmt: off
result = session\ result = session\
@ -483,6 +508,8 @@ def example(session):
models.Customer.email == email_address)\ models.Customer.email == email_address)\
.order_by(models.Customer.id.asc())\ .order_by(models.Customer.id.asc())\
.all() .all()
def off_and_on_without_data(): def off_and_on_without_data():
"""All comments here are technically on the same prefix. """All comments here are technically on the same prefix.
@ -496,6 +523,8 @@ def off_and_on_without_data():
# fmt: on # fmt: on
pass pass
def on_and_off_broken(): def on_and_off_broken():
"""Another known limitation.""" """Another known limitation."""
# fmt: on # fmt: on
@ -504,6 +533,8 @@ def on_and_off_broken():
and_=indeed . it is not formatted and_=indeed . it is not formatted
because . the . handling . inside . generate_ignored_nodes() because . the . handling . inside . generate_ignored_nodes()
now . considers . multiple . fmt . directives . within . one . prefix now . considers . multiple . fmt . directives . within . one . prefix
def long_lines(): def long_lines():
if True: if True:
typedargslist.extend( typedargslist.extend(
@ -538,6 +569,8 @@ def long_lines():
re.MULTILINE|re.VERBOSE re.MULTILINE|re.VERBOSE
# fmt: on # fmt: on
) )
def single_literal_yapf_disable(): def single_literal_yapf_disable():
"""Black does not support this.""" """Black does not support this."""
BAZ = { BAZ = {
@ -545,6 +578,8 @@ def single_literal_yapf_disable():
(5, 6, 7, 8), (5, 6, 7, 8),
(9, 10, 11, 12) (9, 10, 11, 12)
} }
cfg.rule( cfg.rule(
"Default", "address", "Default", "address",
xxxx_xxxx=["xxx-xxxxxx-xxxxxxxxxx"], xxxx_xxxx=["xxx-xxxxxx-xxxxxxxxxx"],

View file

@ -75,70 +75,42 @@ async def test_async_with():
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -2,15 +2,10 @@ @@ -2,7 +2,6 @@
def some_func( unformatted, args ): # fmt: skip def some_func( unformatted, args ): # fmt: skip
print("I am some_func") print("I am some_func")
return 0 return 0
- # Make sure this comment is not removed. - # Make sure this comment is not removed.
-
-
# Make sure a leading comment is not removed. # Make sure a leading comment is not removed.
async def some_async_func( unformatted, args): # fmt: skip @@ -29,15 +28,15 @@
print("I am some_async_func")
await asyncio.sleep(1)
-
-
# Make sure a leading comment is not removed.
class SomeClass( Unformatted, SuperClasses ): # fmt: skip
def some_method( self, unformatted, args ): # fmt: skip
@@ -20,8 +15,6 @@
async def some_async_method( self, unformatted, args ): # fmt: skip
print("I am some_async_method")
await asyncio.sleep(1)
-
-
# Make sure a leading comment is not removed.
if unformatted_call( args ): # fmt: skip
print("First branch")
@@ -29,34 +22,22 @@
elif another_unformatted_call( args ): # fmt: skip elif another_unformatted_call( args ): # fmt: skip
print("Second branch") print("Second branch")
else : # fmt: skip else : # fmt: skip
- print("Last branch") - print("Last branch")
-
-
-while some_condition( unformatted, args ): # fmt: skip
+ print("Last branch") # fmt: skip + print("Last branch") # fmt: skip
-while some_condition( unformatted, args ): # fmt: skip
+while some_condition( unformatted, args ): # fmt: skip +while some_condition( unformatted, args ): # fmt: skip
print("Do something") print("Do something")
-
-
for i in some_iter( unformatted, args ): # fmt: skip for i in some_iter( unformatted, args ): # fmt: skip
- print("Do something") - print("Do something")
-
-
+ print("Do something") # fmt: skip + print("Do something") # fmt: skip
async def test_async_for(): async def test_async_for():
async for i in some_async_iter( unformatted, args ): # fmt: skip @@ -54,7 +53,7 @@
print("Do something")
-
-
try : # fmt: skip
some_call()
except UnformattedError as ex: # fmt: skip
handle_exception()
finally : # fmt: skip
finally_call()
-
-
with give_me_context( unformatted, args ): # fmt: skip with give_me_context( unformatted, args ): # fmt: skip
- print("Do something") - print("Do something")
-
-
+ print("Do something") # fmt: skip + print("Do something") # fmt: skip
async def test_async_with(): async def test_async_with():
async with give_me_async_context( unformatted, args ): # fmt: skip
print("Do something")
``` ```
## Ruff Output ## Ruff Output
@ -148,10 +120,14 @@ async def test_async_with():
def some_func( unformatted, args ): # fmt: skip def some_func( unformatted, args ): # fmt: skip
print("I am some_func") print("I am some_func")
return 0 return 0
# Make sure a leading comment is not removed. # Make sure a leading comment is not removed.
async def some_async_func( unformatted, args): # fmt: skip async def some_async_func( unformatted, args): # fmt: skip
print("I am some_async_func") print("I am some_async_func")
await asyncio.sleep(1) await asyncio.sleep(1)
# Make sure a leading comment is not removed. # Make sure a leading comment is not removed.
class SomeClass( Unformatted, SuperClasses ): # fmt: skip class SomeClass( Unformatted, SuperClasses ): # fmt: skip
def some_method( self, unformatted, args ): # fmt: skip def some_method( self, unformatted, args ): # fmt: skip
@ -161,6 +137,8 @@ class SomeClass( Unformatted, SuperClasses ): # fmt: skip
async def some_async_method( self, unformatted, args ): # fmt: skip async def some_async_method( self, unformatted, args ): # fmt: skip
print("I am some_async_method") print("I am some_async_method")
await asyncio.sleep(1) await asyncio.sleep(1)
# Make sure a leading comment is not removed. # Make sure a leading comment is not removed.
if unformatted_call( args ): # fmt: skip if unformatted_call( args ): # fmt: skip
print("First branch") print("First branch")
@ -169,21 +147,33 @@ elif another_unformatted_call( args ): # fmt: skip
print("Second branch") print("Second branch")
else : # fmt: skip else : # fmt: skip
print("Last branch") # fmt: skip print("Last branch") # fmt: skip
while some_condition( unformatted, args ): # fmt: skip while some_condition( unformatted, args ): # fmt: skip
print("Do something") print("Do something")
for i in some_iter( unformatted, args ): # fmt: skip for i in some_iter( unformatted, args ): # fmt: skip
print("Do something") # fmt: skip print("Do something") # fmt: skip
async def test_async_for(): async def test_async_for():
async for i in some_async_iter( unformatted, args ): # fmt: skip async for i in some_async_iter( unformatted, args ): # fmt: skip
print("Do something") print("Do something")
try : # fmt: skip try : # fmt: skip
some_call() some_call()
except UnformattedError as ex: # fmt: skip except UnformattedError as ex: # fmt: skip
handle_exception() handle_exception()
finally : # fmt: skip finally : # fmt: skip
finally_call() finally_call()
with give_me_context( unformatted, args ): # fmt: skip with give_me_context( unformatted, args ): # fmt: skip
print("Do something") # fmt: skip print("Do something") # fmt: skip
async def test_async_with(): async def test_async_with():
async with give_me_async_context( unformatted, args ): # fmt: skip async with give_me_async_context( unformatted, args ): # fmt: skip
print("Do something") print("Do something")

View file

@ -82,12 +82,8 @@ with hmm_but_this_should_get_two_preceding_newlines():
) )
limited.append(-limited.pop()) # negate top limited.append(-limited.pop()) # negate top
return A( return A(
@@ -13,34 +13,22 @@ @@ -17,30 +17,24 @@
very_long_argument_name2=-very.long.value.for_the_argument,
**kwargs,
)
-
-
def g(): def g():
"Docstring." "Docstring."
- -
@ -95,15 +91,15 @@ with hmm_but_this_should_get_two_preceding_newlines():
pass pass
- -
print("Inner defs should breathe a little.") print("Inner defs should breathe a little.")
-
-
def h(): def h():
def inner(): def inner():
pass pass
- -
print("Inner defs should breathe a little.") print("Inner defs should breathe a little.")
-
-
if os.name == "posix": if os.name == "posix":
import termios import termios
- -
@ -117,7 +113,7 @@ with hmm_but_this_should_get_two_preceding_newlines():
def i_should_be_followed_by_only_one_newline(): def i_should_be_followed_by_only_one_newline():
pass pass
@@ -54,12 +42,9 @@ @@ -54,12 +48,10 @@
class IHopeYouAreHavingALovelyDay: class IHopeYouAreHavingALovelyDay:
def __call__(self): def __call__(self):
print("i_should_be_followed_by_only_one_newline") print("i_should_be_followed_by_only_one_newline")
@ -127,7 +123,7 @@ with hmm_but_this_should_get_two_preceding_newlines():
def foo(): def foo():
pass pass
- -
-
with hmm_but_this_should_get_two_preceding_newlines(): with hmm_but_this_should_get_two_preceding_newlines():
pass pass
``` ```
@ -150,15 +146,21 @@ def f(
very_long_argument_name2=-very.long.value.for_the_argument, very_long_argument_name2=-very.long.value.for_the_argument,
**kwargs, **kwargs,
) )
def g(): def g():
"Docstring." "Docstring."
def inner(): def inner():
pass pass
print("Inner defs should breathe a little.") print("Inner defs should breathe a little.")
def h(): def h():
def inner(): def inner():
pass pass
print("Inner defs should breathe a little.") print("Inner defs should breathe a little.")
if os.name == "posix": if os.name == "posix":
import termios import termios
def i_should_be_followed_by_only_one_newline(): def i_should_be_followed_by_only_one_newline():
@ -183,6 +185,7 @@ else:
def foo(): def foo():
pass pass
with hmm_but_this_should_get_two_preceding_newlines(): with hmm_but_this_should_get_two_preceding_newlines():
pass pass
``` ```

View file

@ -108,21 +108,18 @@ def __await__(): return (yield)
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,100 +1,52 @@ @@ -4,97 +4,67 @@
#!/usr/bin/env python3
import asyncio
import sys
-
from third_party import X, Y, Z from third_party import X, Y, Z
-
-from library import some_connection, some_decorator -from library import some_connection, some_decorator
-
-f"trigger 3.6 mode"
-
-
+from library import some_connection, \ +from library import some_connection, \
+ some_decorator + some_decorator
+f'trigger 3.6 mode' +f'trigger 3.6 mode'
-f"trigger 3.6 mode"
-
def func_no_args(): def func_no_args():
- a - a
- b - b
@ -136,8 +133,6 @@ def __await__(): return (yield)
- continue - continue
- exec("new-style exec", {}, {}) - exec("new-style exec", {}, {})
- return None - return None
-
-
+ a; b; c + a; b; c
+ if True: raise RuntimeError + if True: raise RuntimeError
+ if False: ... + if False: ...
@ -146,17 +141,19 @@ def __await__(): return (yield)
+ continue + continue
+ exec("new-style exec", {}, {}) + exec("new-style exec", {}, {})
+ return None + return None
async def coroutine(arg, exec=False): async def coroutine(arg, exec=False):
- "Single-line docstring. Multiline is harder to reformat." - "Single-line docstring. Multiline is harder to reformat."
- async with some_connection() as conn: - async with some_connection() as conn:
- await conn.do_what_i_mean("SELECT bobby, tables FROM xkcd", timeout=2) - await conn.do_what_i_mean("SELECT bobby, tables FROM xkcd", timeout=2)
- await asyncio.sleep(1) - await asyncio.sleep(1)
-
-
+ "Single-line docstring. Multiline is harder to reformat." + "Single-line docstring. Multiline is harder to reformat."
+ async with some_connection() as conn: + async with some_connection() as conn:
+ await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', timeout=2) + await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', timeout=2)
+ await asyncio.sleep(1) + await asyncio.sleep(1)
@asyncio.coroutine @asyncio.coroutine
-@some_decorator(with_args=True, many_args=[1, 2, 3]) -@some_decorator(with_args=True, many_args=[1, 2, 3])
-def function_signature_stress_test( -def function_signature_stress_test(
@ -168,13 +165,22 @@ def __await__(): return (yield)
- **kwargs, - **kwargs,
-) -> str: -) -> str:
- return text[number:-1] - return text[number:-1]
- +@some_decorator(
- +with_args=True,
+many_args=[1,2,3]
+)
+def function_signature_stress_test(number:int,no_annotation=None,text:str="default",* ,debug:bool=False,**kwargs) -> str:
+ return text[number:-1]
-def spaces(a=1, b=(), c=[], d={}, e=True, f=-1, g=1 if False else 2, h="", i=r""): -def spaces(a=1, b=(), c=[], d={}, e=True, f=-1, g=1 if False else 2, h="", i=r""):
- offset = attr.ib(default=attr.Factory(lambda: _r.uniform(10000, 200000))) - offset = attr.ib(default=attr.Factory(lambda: _r.uniform(10000, 200000)))
- assert task._cancel_stack[: len(old_stack)] == old_stack - assert task._cancel_stack[: len(old_stack)] == old_stack
- +def spaces(a=1, b=(), c=[], d={}, e=True, f=-1, g=1 if False else 2, h="", i=r''):
- + offset = attr.ib(default=attr.Factory( lambda: _r.uniform(10000, 200000)))
+ assert task._cancel_stack[:len(old_stack)] == old_stack
-def spaces_types( -def spaces_types(
- a: int = 1, - a: int = 1,
- b: tuple = (), - b: tuple = (),
@ -187,24 +193,15 @@ def __await__(): return (yield)
- i: str = r"", - i: str = r"",
-): -):
- ... - ...
- +def spaces_types(a: int = 1, b: tuple = (), c: list = [], d: dict = {}, e: bool = True, f: int = -1, g: int = 1 if False else 2, h: str = "", i: str = r''): ...
-
-def spaces2(result=_core.Value(None)): -def spaces2(result=_core.Value(None)):
- assert fut is self._read_fut, (fut, self._read_fut) - assert fut is self._read_fut, (fut, self._read_fut)
-
-
+@some_decorator(
+with_args=True,
+many_args=[1,2,3]
+)
+def function_signature_stress_test(number:int,no_annotation=None,text:str="default",* ,debug:bool=False,**kwargs) -> str:
+ return text[number:-1]
+def spaces(a=1, b=(), c=[], d={}, e=True, f=-1, g=1 if False else 2, h="", i=r''):
+ offset = attr.ib(default=attr.Factory( lambda: _r.uniform(10000, 200000)))
+ assert task._cancel_stack[:len(old_stack)] == old_stack
+def spaces_types(a: int = 1, b: tuple = (), c: list = [], d: dict = {}, e: bool = True, f: int = -1, g: int = 1 if False else 2, h: str = "", i: str = r''): ...
+def spaces2(result= _core.Value(None)): +def spaces2(result= _core.Value(None)):
+ assert fut is self._read_fut, (fut, self._read_fut) + assert fut is self._read_fut, (fut, self._read_fut)
def example(session): def example(session):
- result = ( - result = (
- session.query(models.Customer.id) - session.query(models.Customer.id)
@ -215,14 +212,14 @@ def __await__(): return (yield)
- .order_by(models.Customer.id.asc()) - .order_by(models.Customer.id.asc())
- .all() - .all()
- ) - )
-
-
+ result = session.query(models.Customer.id).filter( + result = session.query(models.Customer.id).filter(
+ models.Customer.account_id == account_id, + models.Customer.account_id == account_id,
+ models.Customer.email == email_address, + models.Customer.email == email_address,
+ ).order_by( + ).order_by(
+ models.Customer.id.asc() + models.Customer.id.asc()
+ ).all() + ).all()
def long_lines(): def long_lines():
if True: if True:
typedargslist.extend( typedargslist.extend(
@ -244,7 +241,7 @@ def __await__(): return (yield)
# trailing standalone comment # trailing standalone comment
) )
) )
@@ -117,23 +69,18 @@ @@ -117,23 +87,22 @@
\n? \n?
) )
$ $
@ -252,8 +249,8 @@ def __await__(): return (yield)
- re.MULTILINE | re.VERBOSE, - re.MULTILINE | re.VERBOSE,
+ """, re.MULTILINE | re.VERBOSE + """, re.MULTILINE | re.VERBOSE
) )
-
-
def trailing_comma(): def trailing_comma():
mapping = { mapping = {
- A: 0.25 * (10.0 / 12), - A: 0.25 * (10.0 / 12),
@ -261,13 +258,13 @@ def __await__(): return (yield)
- C: 0.1 * (10.0 / 12), - C: 0.1 * (10.0 / 12),
- D: 0.1 * (10.0 / 12), - D: 0.1 * (10.0 / 12),
- } - }
-
-
+ A: 0.25 * (10.0 / 12), + A: 0.25 * (10.0 / 12),
+ B: 0.1 * (10.0 / 12), + B: 0.1 * (10.0 / 12),
+ C: 0.1 * (10.0 / 12), + C: 0.1 * (10.0 / 12),
+ D: 0.1 * (10.0 / 12), + D: 0.1 * (10.0 / 12),
+} +}
def f( def f(
- a, - a,
- **kwargs, - **kwargs,
@ -276,12 +273,10 @@ def __await__(): return (yield)
) -> A: ) -> A:
return ( return (
yield from A( yield from A(
@@ -142,7 +89,4 @@ @@ -144,5 +113,4 @@
**kwargs,
) )
)
-
-
-def __await__(): -def __await__():
- return (yield) - return (yield)
+def __await__(): return (yield) +def __await__(): return (yield)
@ -293,10 +288,14 @@ def __await__(): return (yield)
#!/usr/bin/env python3 #!/usr/bin/env python3
import asyncio import asyncio
import sys import sys
from third_party import X, Y, Z from third_party import X, Y, Z
from library import some_connection, \ from library import some_connection, \
some_decorator some_decorator
f'trigger 3.6 mode' f'trigger 3.6 mode'
def func_no_args(): def func_no_args():
a; b; c a; b; c
if True: raise RuntimeError if True: raise RuntimeError
@ -306,11 +305,15 @@ def func_no_args():
continue continue
exec("new-style exec", {}, {}) exec("new-style exec", {}, {})
return None return None
async def coroutine(arg, exec=False): async def coroutine(arg, exec=False):
"Single-line docstring. Multiline is harder to reformat." "Single-line docstring. Multiline is harder to reformat."
async with some_connection() as conn: async with some_connection() as conn:
await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', timeout=2) await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', timeout=2)
await asyncio.sleep(1) await asyncio.sleep(1)
@asyncio.coroutine @asyncio.coroutine
@some_decorator( @some_decorator(
with_args=True, with_args=True,
@ -318,12 +321,20 @@ many_args=[1,2,3]
) )
def function_signature_stress_test(number:int,no_annotation=None,text:str="default",* ,debug:bool=False,**kwargs) -> str: def function_signature_stress_test(number:int,no_annotation=None,text:str="default",* ,debug:bool=False,**kwargs) -> str:
return text[number:-1] return text[number:-1]
def spaces(a=1, b=(), c=[], d={}, e=True, f=-1, g=1 if False else 2, h="", i=r''): def spaces(a=1, b=(), c=[], d={}, e=True, f=-1, g=1 if False else 2, h="", i=r''):
offset = attr.ib(default=attr.Factory( lambda: _r.uniform(10000, 200000))) offset = attr.ib(default=attr.Factory( lambda: _r.uniform(10000, 200000)))
assert task._cancel_stack[:len(old_stack)] == old_stack assert task._cancel_stack[:len(old_stack)] == old_stack
def spaces_types(a: int = 1, b: tuple = (), c: list = [], d: dict = {}, e: bool = True, f: int = -1, g: int = 1 if False else 2, h: str = "", i: str = r''): ... def spaces_types(a: int = 1, b: tuple = (), c: list = [], d: dict = {}, e: bool = True, f: int = -1, g: int = 1 if False else 2, h: str = "", i: str = r''): ...
def spaces2(result= _core.Value(None)): def spaces2(result= _core.Value(None)):
assert fut is self._read_fut, (fut, self._read_fut) assert fut is self._read_fut, (fut, self._read_fut)
def example(session): def example(session):
result = session.query(models.Customer.id).filter( result = session.query(models.Customer.id).filter(
models.Customer.account_id == account_id, models.Customer.account_id == account_id,
@ -331,6 +342,8 @@ def example(session):
).order_by( ).order_by(
models.Customer.id.asc() models.Customer.id.asc()
).all() ).all()
def long_lines(): def long_lines():
if True: if True:
typedargslist.extend( typedargslist.extend(
@ -363,6 +376,8 @@ def long_lines():
$ $
""", re.MULTILINE | re.VERBOSE """, re.MULTILINE | re.VERBOSE
) )
def trailing_comma(): def trailing_comma():
mapping = { mapping = {
A: 0.25 * (10.0 / 12), A: 0.25 * (10.0 / 12),
@ -370,6 +385,8 @@ def trailing_comma():
C: 0.1 * (10.0 / 12), C: 0.1 * (10.0 / 12),
D: 0.1 * (10.0 / 12), D: 0.1 * (10.0 / 12),
} }
def f( def f(
a, a,
**kwargs, **kwargs,
@ -381,6 +398,8 @@ def f(
**kwargs, **kwargs,
) )
) )
def __await__(): return (yield) def __await__(): return (yield)
``` ```

View file

@ -74,7 +74,7 @@ some_module.some_function(
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,114 +1,46 @@ @@ -1,69 +1,28 @@
-def f( -def f(
- a, - a,
-): -):
@ -84,8 +84,8 @@ some_module.some_function(
+def f(a,): +def f(a,):
+ d = {'key': 'value',} + d = {'key': 'value',}
tup = (1,) tup = (1,)
-
-
-def f2( -def f2(
- a, - a,
- b, - b,
@ -98,8 +98,11 @@ some_module.some_function(
- 1, - 1,
- 2, - 2,
- ) - )
- +def f2(a,b,):
- + d = {'key': 'value', 'key2': 'value2',}
+ tup = (1,2,)
-def f( -def f(
- a: int = 1, - a: int = 1,
-): -):
@ -111,9 +114,6 @@ some_module.some_function(
- call2( - call2(
- arg=[1, 2, 3], - arg=[1, 2, 3],
- ) - )
+def f2(a,b,):
+ d = {'key': 'value', 'key2': 'value2',}
+ tup = (1,2,)
+def f(a:int=1,): +def f(a:int=1,):
+ call(arg={'explode': 'this',}) + call(arg={'explode': 'this',})
+ call2(arg=[1,2,3],) + call2(arg=[1,2,3],)
@ -136,8 +136,8 @@ some_module.some_function(
- ): - ):
+ if a == {"a": 1,"b": 2,"c": 3,"d": 4,"e": 5,"f": 6,"g": 7,"h": 8,}["a"]: + if a == {"a": 1,"b": 2,"c": 3,"d": 4,"e": 5,"f": 6,"g": 7,"h": 8,}["a"]:
pass pass
-
-
-def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> ( -def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> (
- Set["xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"] - Set["xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"]
-): -):
@ -150,20 +150,17 @@ some_module.some_function(
- } - }
- } - }
- } - }
-
-
+def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> Set[ +def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> Set[
+ "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+]: +]:
+ json = {"k": {"k2": {"k3": [1,]}}} + json = {"k": {"k2": {"k3": [1,]}}}
# The type annotation shouldn't get a trailing comma since that would change its type. # The type annotation shouldn't get a trailing comma since that would change its type.
# Relevant bug report: https://github.com/psf/black/issues/2381. @@ -74,24 +33,21 @@
def some_function_with_a_really_long_name() -> (
returning_a_deeply_nested_import_of_a_type_i_suppose
):
pass pass
-
-
-def some_method_with_a_really_long_name( -def some_method_with_a_really_long_name(
- very_long_parameter_so_yeah: str, another_long_parameter: int - very_long_parameter_so_yeah: str, another_long_parameter: int
-) -> another_case_of_returning_a_deeply_nested_import_of_a_type_i_suppose_cause_why_not: -) -> another_case_of_returning_a_deeply_nested_import_of_a_type_i_suppose_cause_why_not:
@ -171,8 +168,8 @@ some_module.some_function(
+ another_case_of_returning_a_deeply_nested_import_of_a_type_i_suppose_cause_why_not + another_case_of_returning_a_deeply_nested_import_of_a_type_i_suppose_cause_why_not
+): +):
pass pass
-
-
def func() -> ( def func() -> (
- also_super_long_type_annotation_that_may_cause_an_AST_related_crash_in_black( - also_super_long_type_annotation_that_may_cause_an_AST_related_crash_in_black(
- this_shouldn_t_get_a_trailing_comma_too - this_shouldn_t_get_a_trailing_comma_too
@ -180,8 +177,8 @@ some_module.some_function(
+ also_super_long_type_annotation_that_may_cause_an_AST_related_crash_in_black(this_shouldn_t_get_a_trailing_comma_too) + also_super_long_type_annotation_that_may_cause_an_AST_related_crash_in_black(this_shouldn_t_get_a_trailing_comma_too)
): ):
pass pass
-
-
-def func() -> ( -def func() -> (
- also_super_long_type_annotation_that_may_cause_an_AST_related_crash_in_black( - also_super_long_type_annotation_that_may_cause_an_AST_related_crash_in_black(
+def func() -> ((also_super_long_type_annotation_that_may_cause_an_AST_related_crash_in_black( +def func() -> ((also_super_long_type_annotation_that_may_cause_an_AST_related_crash_in_black(
@ -190,9 +187,8 @@ some_module.some_function(
+ )) + ))
): ):
pass pass
-
- @@ -100,15 +56,7 @@
# Make sure inner one-element tuple won't explode
some_module.some_function( some_module.some_function(
argument1, (one_element_tuple,), argument4, argument5, argument6 argument1, (one_element_tuple,), argument4, argument5, argument6
) )
@ -217,9 +213,13 @@ some_module.some_function(
def f(a,): def f(a,):
d = {'key': 'value',} d = {'key': 'value',}
tup = (1,) tup = (1,)
def f2(a,b,): def f2(a,b,):
d = {'key': 'value', 'key2': 'value2',} d = {'key': 'value', 'key2': 'value2',}
tup = (1,2,) tup = (1,2,)
def f(a:int=1,): def f(a:int=1,):
call(arg={'explode': 'this',}) call(arg={'explode': 'this',})
call2(arg=[1,2,3],) call2(arg=[1,2,3],)
@ -229,29 +229,41 @@ def f(a:int=1,):
}["a"] }["a"]
if a == {"a": 1,"b": 2,"c": 3,"d": 4,"e": 5,"f": 6,"g": 7,"h": 8,}["a"]: if a == {"a": 1,"b": 2,"c": 3,"d": 4,"e": 5,"f": 6,"g": 7,"h": 8,}["a"]:
pass pass
def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> Set[ def xxxxxxxxxxxxxxxxxxxxxxxxxxxx() -> Set[
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
]: ]:
json = {"k": {"k2": {"k3": [1,]}}} json = {"k": {"k2": {"k3": [1,]}}}
# The type annotation shouldn't get a trailing comma since that would change its type. # The type annotation shouldn't get a trailing comma since that would change its type.
# Relevant bug report: https://github.com/psf/black/issues/2381. # Relevant bug report: https://github.com/psf/black/issues/2381.
def some_function_with_a_really_long_name() -> ( def some_function_with_a_really_long_name() -> (
returning_a_deeply_nested_import_of_a_type_i_suppose returning_a_deeply_nested_import_of_a_type_i_suppose
): ):
pass pass
def some_method_with_a_really_long_name(very_long_parameter_so_yeah: str, another_long_parameter: int) -> ( def some_method_with_a_really_long_name(very_long_parameter_so_yeah: str, another_long_parameter: int) -> (
another_case_of_returning_a_deeply_nested_import_of_a_type_i_suppose_cause_why_not another_case_of_returning_a_deeply_nested_import_of_a_type_i_suppose_cause_why_not
): ):
pass pass
def func() -> ( def func() -> (
also_super_long_type_annotation_that_may_cause_an_AST_related_crash_in_black(this_shouldn_t_get_a_trailing_comma_too) also_super_long_type_annotation_that_may_cause_an_AST_related_crash_in_black(this_shouldn_t_get_a_trailing_comma_too)
): ):
pass pass
def func() -> ((also_super_long_type_annotation_that_may_cause_an_AST_related_crash_in_black( def func() -> ((also_super_long_type_annotation_that_may_cause_an_AST_related_crash_in_black(
this_shouldn_t_get_a_trailing_comma_too this_shouldn_t_get_a_trailing_comma_too
)) ))
): ):
pass pass
# Make sure inner one-element tuple won't explode # Make sure inner one-element tuple won't explode
some_module.some_function( some_module.some_function(
argument1, (one_element_tuple,), argument4, argument5, argument6 argument1, (one_element_tuple,), argument4, argument5, argument6

View file

@ -62,9 +62,8 @@ __all__ = (
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,55 +1,33 @@ @@ -2,12 +2,13 @@
"""The asyncio package, tracking PEP 3156."""
-
# flake8: noqa # flake8: noqa
-from logging import WARNING -from logging import WARNING
@ -79,16 +78,9 @@ __all__ = (
# This relies on each of the submodules having an __all__ variable. # This relies on each of the submodules having an __all__ variable.
from .base_events import * from .base_events import *
from .coroutines import * from .coroutines import *
from .events import * # comment here @@ -22,33 +23,16 @@
-
from .futures import *
from .locks import * # comment here
from .protocols import *
-
from ..runners import * # comment here
from ..queues import *
from ..streams import * from ..streams import *
-
from some_library import ( from some_library import (
- Just, - Just,
- Enough, - Enough,
@ -111,7 +103,7 @@ __all__ = (
-) -)
+from name_of_a_company.extremely_long_project_name.component.ttypes import CuteLittleServiceHandlerFactoryyy +from name_of_a_company.extremely_long_project_name.component.ttypes import CuteLittleServiceHandlerFactoryyy
from name_of_a_company.extremely_long_project_name.extremely_long_component_name.ttypes import * from name_of_a_company.extremely_long_project_name.extremely_long_component_name.ttypes import *
-
from .a.b.c.subprocess import * from .a.b.c.subprocess import *
-from . import tasks -from . import tasks
-from . import A, B, C -from . import A, B, C
@ -119,20 +111,20 @@ __all__ = (
- SomeVeryLongNameAndAllOfItsAdditionalLetters1, - SomeVeryLongNameAndAllOfItsAdditionalLetters1,
- SomeVeryLongNameAndAllOfItsAdditionalLetters2, - SomeVeryLongNameAndAllOfItsAdditionalLetters2,
-) -)
-
+from . import (tasks) +from . import (tasks)
+from . import (A, B, C) +from . import (A, B, C)
+from . import SomeVeryLongNameAndAllOfItsAdditionalLetters1, \ +from . import SomeVeryLongNameAndAllOfItsAdditionalLetters1, \
+ SomeVeryLongNameAndAllOfItsAdditionalLetters2 + SomeVeryLongNameAndAllOfItsAdditionalLetters2
__all__ = ( __all__ = (
base_events.__all__ base_events.__all__
+ coroutines.__all__
``` ```
## Ruff Output ## Ruff Output
```py ```py
"""The asyncio package, tracking PEP 3156.""" """The asyncio package, tracking PEP 3156."""
# flake8: noqa # flake8: noqa
from logging import ( from logging import (
@ -146,22 +138,27 @@ import sys
from .base_events import * from .base_events import *
from .coroutines import * from .coroutines import *
from .events import * # comment here from .events import * # comment here
from .futures import * from .futures import *
from .locks import * # comment here from .locks import * # comment here
from .protocols import * from .protocols import *
from ..runners import * # comment here from ..runners import * # comment here
from ..queues import * from ..queues import *
from ..streams import * from ..streams import *
from some_library import ( from some_library import (
Just, Enough, Libraries, To, Fit, In, This, Nice, Split, Which, We, No, Longer, Use Just, Enough, Libraries, To, Fit, In, This, Nice, Split, Which, We, No, Longer, Use
) )
from name_of_a_company.extremely_long_project_name.component.ttypes import CuteLittleServiceHandlerFactoryyy from name_of_a_company.extremely_long_project_name.component.ttypes import CuteLittleServiceHandlerFactoryyy
from name_of_a_company.extremely_long_project_name.extremely_long_component_name.ttypes import * from name_of_a_company.extremely_long_project_name.extremely_long_component_name.ttypes import *
from .a.b.c.subprocess import * from .a.b.c.subprocess import *
from . import (tasks) from . import (tasks)
from . import (A, B, C) from . import (A, B, C)
from . import SomeVeryLongNameAndAllOfItsAdditionalLetters1, \ from . import SomeVeryLongNameAndAllOfItsAdditionalLetters1, \
SomeVeryLongNameAndAllOfItsAdditionalLetters2 SomeVeryLongNameAndAllOfItsAdditionalLetters2
__all__ = ( __all__ = (
base_events.__all__ base_events.__all__
+ coroutines.__all__ + coroutines.__all__

View file

@ -76,34 +76,20 @@ return np.divide(
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,16 +1,10 @@ @@ -1,10 +1,10 @@
def function(**kwargs): def function(**kwargs):
t = a**2 + b**3 t = a**2 + b**3
- return t**2 - return t**2
-
-
+ return t ** 2 + return t ** 2
def function_replace_spaces(**kwargs): def function_replace_spaces(**kwargs):
- t = a**2 + b**3 + c**4 - t = a**2 + b**3 + c**4
-
-
+ t = a **2 + b** 3 + c ** 4 + t = a **2 + b** 3 + c ** 4
def function_dont_replace_spaces(): def function_dont_replace_spaces():
{**a, **b, **c} @@ -47,8 +47,6 @@
-
-
a = 5**~4
b = 5 ** f()
c = -(5**2)
@@ -29,7 +23,6 @@
p = {(k, k**2): v**2 for k, v in pairs}
q = [10**i for i in range(6)]
r = x**y
-
a = 5.0**~4.0
b = 5.0 ** f()
c = -(5.0**2.0)
@@ -47,8 +40,6 @@
o = settings(max_examples=10**6.0) o = settings(max_examples=10**6.0)
p = {(k, k**2): v**2.0 for k, v in pairs} p = {(k, k**2): v**2.0 for k, v in pairs}
q = [10.5**i for i in range(6)] q = [10.5**i for i in range(6)]
@ -112,14 +98,6 @@ return np.divide(
# WE SHOULD DEFINITELY NOT EAT THESE COMMENTS (https://github.com/psf/black/issues/2873) # WE SHOULD DEFINITELY NOT EAT THESE COMMENTS (https://github.com/psf/black/issues/2873)
if hasattr(view, "sum_of_weights"): if hasattr(view, "sum_of_weights"):
return np.divide( # type: ignore[no-any-return] return np.divide( # type: ignore[no-any-return]
@@ -57,7 +48,6 @@
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]
)
-
return np.divide(
where=view.sum_of_weights_of_weight_long**2 > view.sum_of_weights_squared, # type: ignore
)
``` ```
## Ruff Output ## Ruff Output
@ -128,10 +106,16 @@ return np.divide(
def function(**kwargs): def function(**kwargs):
t = a**2 + b**3 t = a**2 + b**3
return t ** 2 return t ** 2
def function_replace_spaces(**kwargs): def function_replace_spaces(**kwargs):
t = a **2 + b** 3 + c ** 4 t = a **2 + b** 3 + c ** 4
def function_dont_replace_spaces(): def function_dont_replace_spaces():
{**a, **b, **c} {**a, **b, **c}
a = 5**~4 a = 5**~4
b = 5 ** f() b = 5 ** f()
c = -(5**2) c = -(5**2)
@ -150,6 +134,7 @@ o = settings(max_examples=10**6)
p = {(k, k**2): v**2 for k, v in pairs} p = {(k, k**2): v**2 for k, v in pairs}
q = [10**i for i in range(6)] q = [10**i for i in range(6)]
r = x**y r = x**y
a = 5.0**~4.0 a = 5.0**~4.0
b = 5.0 ** f() b = 5.0 ** f()
c = -(5.0**2.0) c = -(5.0**2.0)
@ -175,6 +160,7 @@ if hasattr(view, "sum_of_weights"):
out=np.full(view.sum_of_weights.shape, np.nan), # type: ignore[union-attr] 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] where=view.sum_of_weights**2 > view.sum_of_weights_squared, # type: ignore[union-attr]
) )
return np.divide( return np.divide(
where=view.sum_of_weights_of_weight_long**2 > view.sum_of_weights_squared, # type: ignore where=view.sum_of_weights_of_weight_long**2 > view.sum_of_weights_squared, # type: ignore
) )

View file

@ -94,56 +94,49 @@ async def main():
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,93 +1,64 @@ @@ -8,59 +8,64 @@
import asyncio
-
-
# Control example
async def main():
await asyncio.sleep(1)
-
-
# Remove brackets for short coroutine/task # Remove brackets for short coroutine/task
async def main(): async def main():
- await asyncio.sleep(1) - await asyncio.sleep(1)
-
-
+ await (asyncio.sleep(1)) + await (asyncio.sleep(1))
async def main(): async def main():
- await asyncio.sleep(1) - await asyncio.sleep(1)
-
-
+ await ( + await (
+ asyncio.sleep(1) + asyncio.sleep(1)
+ ) + )
async def main(): async def main():
- await asyncio.sleep(1) - await asyncio.sleep(1)
-
-
+ await (asyncio.sleep(1) + await (asyncio.sleep(1)
+ ) + )
# Check comments # Check comments
async def main(): async def main():
- await asyncio.sleep(1) # Hello - await asyncio.sleep(1) # Hello
-
-
+ await ( # Hello + await ( # Hello
+ asyncio.sleep(1) + asyncio.sleep(1)
+ ) + )
async def main(): async def main():
- await asyncio.sleep(1) # Hello - await asyncio.sleep(1) # Hello
-
-
+ await ( + await (
+ asyncio.sleep(1) # Hello + asyncio.sleep(1) # Hello
+ ) + )
async def main(): async def main():
- await asyncio.sleep(1) # Hello - await asyncio.sleep(1) # Hello
-
-
+ await ( + await (
+ asyncio.sleep(1) + asyncio.sleep(1)
+ ) + )
# Long lines # Long lines
async def main(): async def main():
- await asyncio.gather( - await asyncio.gather(
@ -155,9 +148,9 @@ async def main():
- asyncio.sleep(1), - asyncio.sleep(1),
- asyncio.sleep(1), - asyncio.sleep(1),
- ) - )
-
-
+ await asyncio.gather(asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1)) + await asyncio.gather(asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1))
# Same as above but with magic trailing comma in function # Same as above but with magic trailing comma in function
async def main(): async def main():
- await asyncio.gather( - await asyncio.gather(
@ -169,14 +162,12 @@ async def main():
- asyncio.sleep(1), - asyncio.sleep(1),
- asyncio.sleep(1), - asyncio.sleep(1),
- ) - )
-
-
+ await asyncio.gather(asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1),) + await asyncio.gather(asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1),)
# Cr@zY Br@ck3Tz # Cr@zY Br@ck3Tz
async def main(): async def main():
- await black(1) - await black(1)
-
-
+ await ( + await (
+ ((((((((((((( + (((((((((((((
+ ((( ((( + ((( (((
@ -190,74 +181,81 @@ async def main():
+ ))) ))) + ))) )))
+ ))))))))))))) + )))))))))))))
+ ) + )
# Keep brackets around non power operations and nested awaits # Keep brackets around non power operations and nested awaits
async def main(): @@ -82,11 +87,11 @@
await (set_of_tasks | other_set)
-
-
async def main():
await (await asyncio.sleep(1))
-
-
# It's awaits all the way down...
async def main():
await (await x)
-
-
async def main():
await (yield x)
-
-
async def main(): async def main():
- await (await asyncio.sleep(1)) - await (await asyncio.sleep(1))
-
-
+ await (await (asyncio.sleep(1))) + await (await (asyncio.sleep(1)))
async def main(): async def main():
- await (await (await (await (await asyncio.sleep(1))))) - await (await (await (await (await asyncio.sleep(1)))))
-
-
+ await (await (await (await (await (asyncio.sleep(1)))))) + await (await (await (await (await (asyncio.sleep(1))))))
async def main(): async def main():
await (yield)
``` ```
## Ruff Output ## Ruff Output
```py ```py
import asyncio import asyncio
# Control example # Control example
async def main(): async def main():
await asyncio.sleep(1) await asyncio.sleep(1)
# Remove brackets for short coroutine/task # Remove brackets for short coroutine/task
async def main(): async def main():
await (asyncio.sleep(1)) await (asyncio.sleep(1))
async def main(): async def main():
await ( await (
asyncio.sleep(1) asyncio.sleep(1)
) )
async def main(): async def main():
await (asyncio.sleep(1) await (asyncio.sleep(1)
) )
# Check comments # Check comments
async def main(): async def main():
await ( # Hello await ( # Hello
asyncio.sleep(1) asyncio.sleep(1)
) )
async def main(): async def main():
await ( await (
asyncio.sleep(1) # Hello asyncio.sleep(1) # Hello
) )
async def main(): async def main():
await ( await (
asyncio.sleep(1) asyncio.sleep(1)
) )
# Long lines # Long lines
async def main(): async def main():
await asyncio.gather(asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1)) await asyncio.gather(asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1))
# Same as above but with magic trailing comma in function # Same as above but with magic trailing comma in function
async def main(): async def main():
await asyncio.gather(asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1),) await asyncio.gather(asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1),)
# Cr@zY Br@ck3Tz # Cr@zY Br@ck3Tz
async def main(): async def main():
await ( await (
@ -273,20 +271,34 @@ async def main():
))) ))) ))) )))
))))))))))))) )))))))))))))
) )
# Keep brackets around non power operations and nested awaits # Keep brackets around non power operations and nested awaits
async def main(): async def main():
await (set_of_tasks | other_set) await (set_of_tasks | other_set)
async def main(): async def main():
await (await asyncio.sleep(1)) await (await asyncio.sleep(1))
# It's awaits all the way down... # It's awaits all the way down...
async def main(): async def main():
await (await x) await (await x)
async def main(): async def main():
await (yield x) await (yield x)
async def main(): async def main():
await (await (asyncio.sleep(1))) await (await (asyncio.sleep(1)))
async def main(): async def main():
await (await (await (await (await (asyncio.sleep(1)))))) await (await (await (await (await (asyncio.sleep(1))))))
async def main(): async def main():
await (yield) await (yield)
``` ```

View file

@ -48,7 +48,7 @@ except (some.really.really.really.looooooooooooooooooooooooooooooooong.module.ov
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,42 +1,25 @@ @@ -1,42 +1,27 @@
# These brackets are redundant, therefore remove. # These brackets are redundant, therefore remove.
try: try:
a.something a.something
@ -78,7 +78,7 @@ except (some.really.really.really.looooooooooooooooooooooooooooooooong.module.ov
-) as err: -) as err:
+except (some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error) as err: +except (some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error) as err:
raise err raise err
-
try: try:
a.something a.something
-except ( -except (
@ -86,7 +86,7 @@ except (some.really.really.really.looooooooooooooooooooooooooooooooong.module.ov
-) as err: -) as err:
+except (some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error,) as err: +except (some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error,) as err:
raise err raise err
-
try: try:
a.something a.something
-except ( -except (
@ -117,10 +117,12 @@ try:
a.something a.something
except (some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error) as err: except (some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error) as err:
raise err raise err
try: try:
a.something a.something
except (some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error,) as err: except (some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error,) as err:
raise err raise err
try: try:
a.something a.something
except (some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error, some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error) as err: except (some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error, some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error) as err:

View file

@ -32,7 +32,7 @@ for (((((k, v))))) in d.items():
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,27 +1,15 @@ @@ -1,27 +1,16 @@
# Only remove tuple brackets after `for` # Only remove tuple brackets after `for`
-for k, v in d.items(): -for k, v in d.items():
+for (k, v) in d.items(): +for (k, v) in d.items():
@ -50,7 +50,7 @@ for (((((k, v))))) in d.items():
-) in d.items(): -) in d.items():
+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 d.items(): +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 d.items():
print(k, v) print(k, v)
-
-for ( -for (
- k, - k,
- v, - v,
@ -79,6 +79,7 @@ for module in (core, _unicodefun):
# Brackets remain for long for loop lines # Brackets remain for long for loop lines
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 d.items(): 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 d.items():
print(k, v) print(k, v)
for (k, v) in dfkasdjfldsjflkdsjflkdsjfdslkfjldsjfgkjdshgkljjdsfldgkhsdofudsfudsofajdslkfjdslkfjldisfjdffjsdlkfjdlkjjkdflskadjldkfjsalkfjdasj.items(): for (k, v) in dfkasdjfldsjflkdsjflkdsjfdslkfjldsjfgkjdshgkljjdsfldgkhsdofudsfudsofajdslkfjdslkfjldisfjdffjsdlkfjdlkjjkdflskadjldkfjsalkfjdasj.items():
print(k, v) print(k, v)
# Test deeply nested brackets # Test deeply nested brackets

View file

@ -121,101 +121,90 @@ with open("/path/to/file.txt", mode="r") as read_file:
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,78 +1,68 @@ @@ -2,20 +2,26 @@
import random
+def foo1():
+ print("The newline above me should be deleted!")
+def foo2():
-def foo1():
- print("The newline above me should be deleted!")
-def foo2(): def foo1():
+
print("The newline above me should be deleted!")
def foo2():
+
+
+
print("All the newlines above me should be deleted!") print("All the newlines above me should be deleted!")
-
-
def foo3(): def foo3():
+ +
print("No newline above me!") print("No newline above me!")
print("There is a newline above me, and that's OK!") print("There is a newline above me, and that's OK!")
-
-
def foo4(): def foo4():
+ +
# There is a comment here # There is a comment here
print("The newline above me should not be deleted!") print("The newline above me should not be deleted!")
- @@ -23,27 +29,39 @@
-
class Foo: class Foo:
def bar(self): def bar(self):
+ +
print("The newline above me should be deleted!") print("The newline above me should be deleted!")
+for i in range(5):
+ print(f"{i}) The line above me should be removed!")
+for i in range(5):
-for i in range(5):
- print(f"{i}) The line above me should be removed!")
+ print(f"{i}) The lines above me should be removed!")
for i in range(5): for i in range(5):
- print(f"{i}) The lines above me should be removed!") +
print(f"{i}) The line above me should be removed!")
+ for j in range(7):
-for i in range(5): for i in range(5):
- for j in range(7): +
+
+
print(f"{i}) The lines above me should be removed!") print(f"{i}) The lines above me should be removed!")
+if random.randint(0, 3) == 0:
-
+ print("The new line above me is about to be removed!") for i in range(5):
+
for j in range(7):
+
print(f"{i}) The lines above me should be removed!")
if random.randint(0, 3) == 0: if random.randint(0, 3) == 0:
- print("The new line above me is about to be removed!") +
print("The new line above me is about to be removed!")
-if random.randint(0, 3) == 0:
- print("The new lines above me is about to be removed!")
+ print("The new lines above me is about to be removed!")
if random.randint(0, 3) == 0: if random.randint(0, 3) == 0:
if random.uniform(0, 1) > 0.5: +
print("Two lines above me are about to be removed!") +
- +
- +
while True: print("The new lines above me is about to be removed!")
print("The newline above me should be deleted!")
-
- @@ -66,13 +84,19 @@
while True:
print("The newlines above me should be deleted!")
-
-
while True:
while False:
print("The newlines above me should be deleted!")
+with open("/path/to/file.txt", mode="w") as file:
-
+ file.write("The new line above me is about to be removed!")
with open("/path/to/file.txt", mode="w") as file: with open("/path/to/file.txt", mode="w") as file:
- file.write("The new line above me is about to be removed!") +
file.write("The new line above me is about to be removed!")
-with open("/path/to/file.txt", mode="w") as file: with open("/path/to/file.txt", mode="w") as file:
+
+
+ +
file.write("The new lines above me is about to be removed!") file.write("The new lines above me is about to be removed!")
+with open("/path/to/file.txt", mode="r") as read_file:
-
-with open("/path/to/file.txt", mode="r") as read_file: with open("/path/to/file.txt", mode="r") as read_file:
+
with open("/path/to/output_file.txt", mode="w") as write_file: with open("/path/to/output_file.txt", mode="w") as write_file:
+ +
write_file.writelines(read_file.readlines()) write_file.writelines(read_file.readlines())
@ -225,68 +214,102 @@ with open("/path/to/file.txt", mode="r") as read_file:
```py ```py
import random import random
def foo1(): def foo1():
print("The newline above me should be deleted!") print("The newline above me should be deleted!")
def foo2(): def foo2():
print("All the newlines above me should be deleted!") print("All the newlines above me should be deleted!")
def foo3(): def foo3():
print("No newline above me!") print("No newline above me!")
print("There is a newline above me, and that's OK!") print("There is a newline above me, and that's OK!")
def foo4(): def foo4():
# There is a comment here # There is a comment here
print("The newline above me should not be deleted!") print("The newline above me should not be deleted!")
class Foo: class Foo:
def bar(self): def bar(self):
print("The newline above me should be deleted!") print("The newline above me should be deleted!")
for i in range(5): for i in range(5):
print(f"{i}) The line above me should be removed!") print(f"{i}) The line above me should be removed!")
for i in range(5): for i in range(5):
print(f"{i}) The lines above me should be removed!") print(f"{i}) The lines above me should be removed!")
for i in range(5): for i in range(5):
for j in range(7): for j in range(7):
print(f"{i}) The lines above me should be removed!") print(f"{i}) The lines above me should be removed!")
if random.randint(0, 3) == 0: if random.randint(0, 3) == 0:
print("The new line above me is about to be removed!") print("The new line above me is about to be removed!")
if random.randint(0, 3) == 0: if random.randint(0, 3) == 0:
print("The new lines above me is about to be removed!") print("The new lines above me is about to be removed!")
if random.randint(0, 3) == 0: if random.randint(0, 3) == 0:
if random.uniform(0, 1) > 0.5: if random.uniform(0, 1) > 0.5:
print("Two lines above me are about to be removed!") print("Two lines above me are about to be removed!")
while True: while True:
print("The newline above me should be deleted!") print("The newline above me should be deleted!")
while True: while True:
print("The newlines above me should be deleted!") print("The newlines above me should be deleted!")
while True: while True:
while False: while False:
print("The newlines above me should be deleted!") print("The newlines above me should be deleted!")
with open("/path/to/file.txt", mode="w") as file: with open("/path/to/file.txt", mode="w") as file:
file.write("The new line above me is about to be removed!") file.write("The new line above me is about to be removed!")
with open("/path/to/file.txt", mode="w") as file: with open("/path/to/file.txt", mode="w") as file:
file.write("The new lines above me is about to be removed!") file.write("The new lines above me is about to be removed!")
with open("/path/to/file.txt", mode="r") as read_file: with open("/path/to/file.txt", mode="r") as read_file:
with open("/path/to/output_file.txt", mode="w") as write_file: with open("/path/to/output_file.txt", mode="w") as write_file:

View file

@ -68,19 +68,15 @@ def example8():
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,85 +1,34 @@ @@ -1,5 +1,5 @@
-x = 1 -x = 1
-x = 1.2 -x = 1.2
-
+x = (1) +x = (1)
+x = (1.2) +x = (1.2)
data = ( data = (
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
).encode() @@ -11,75 +11,47 @@
-
-
async def show_status():
while True:
try: try:
if report_host: if report_host:
data = ( data = (
@ -90,52 +86,52 @@ def example8():
+ ).encode() + ).encode()
except Exception as e: except Exception as e:
pass pass
-
-
def example(): def example():
- return "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" - return "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
-
-
+ return (("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")) + return (("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"))
def example1(): def example1():
- return 1111111111111111111111111111111111111111111111111111111111111111111111111111111111111 - return 1111111111111111111111111111111111111111111111111111111111111111111111111111111111111
-
-
+ return ((1111111111111111111111111111111111111111111111111111111111111111111111111111111111111)) + return ((1111111111111111111111111111111111111111111111111111111111111111111111111111111111111))
def example1point5(): def example1point5():
- return 1111111111111111111111111111111111111111111111111111111111111111111111111111111111111 - return 1111111111111111111111111111111111111111111111111111111111111111111111111111111111111
-
-
+ return ((((((1111111111111111111111111111111111111111111111111111111111111111111111111111111111111)))))) + return ((((((1111111111111111111111111111111111111111111111111111111111111111111111111111111111111))))))
def example2(): def example2():
- return ( - return (
- "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
- ) - )
-
-
+ return (("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")) + return (("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"))
def example3(): def example3():
- return ( - return (
- 1111111111111111111111111111111111111111111111111111111111111111111111111111111 - 1111111111111111111111111111111111111111111111111111111111111111111111111111111
- ) - )
-
-
+ return ((1111111111111111111111111111111111111111111111111111111111111111111111111111111)) + return ((1111111111111111111111111111111111111111111111111111111111111111111111111111111))
def example4(): def example4():
- return True - return True
-
-
+ return ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((True)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) + return ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((True))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
def example5(): def example5():
- return () - return ()
-
-
+ return ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) + return ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((()))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
def example6(): def example6():
- return {a: a for a in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]} - return {a: a for a in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]}
-
-
+ return ((((((((({a:a for a in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]}))))))))) + return ((((((((({a:a for a in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]})))))))))
def example7(): def example7():
- return { - return {
- a: a - a: a
@ -162,9 +158,9 @@ def example8():
- 20000000000000000000, - 20000000000000000000,
- ] - ]
- } - }
-
-
+ return ((((((((({a:a for a in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20000000000000000000]}))))))))) + return ((((((((({a:a for a in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20000000000000000000]})))))))))
def example8(): def example8():
- return None - return None
+ return (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((None))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) + return (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((None)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
@ -175,9 +171,12 @@ def example8():
```py ```py
x = (1) x = (1)
x = (1.2) x = (1.2)
data = ( data = (
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
).encode() ).encode()
async def show_status(): async def show_status():
while True: while True:
try: try:
@ -187,24 +186,44 @@ async def show_status():
).encode() ).encode()
except Exception as e: except Exception as e:
pass pass
def example(): def example():
return (("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")) return (("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"))
def example1(): def example1():
return ((1111111111111111111111111111111111111111111111111111111111111111111111111111111111111)) return ((1111111111111111111111111111111111111111111111111111111111111111111111111111111111111))
def example1point5(): def example1point5():
return ((((((1111111111111111111111111111111111111111111111111111111111111111111111111111111111111)))))) return ((((((1111111111111111111111111111111111111111111111111111111111111111111111111111111111111))))))
def example2(): def example2():
return (("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")) return (("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"))
def example3(): def example3():
return ((1111111111111111111111111111111111111111111111111111111111111111111111111111111)) return ((1111111111111111111111111111111111111111111111111111111111111111111111111111111))
def example4(): def example4():
return ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((True)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) return ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((True))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
def example5(): def example5():
return ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) return ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((()))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
def example6(): def example6():
return ((((((((({a:a for a in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]}))))))))) return ((((((((({a:a for a in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]})))))))))
def example7(): def example7():
return ((((((((({a:a for a in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20000000000000000000]}))))))))) return ((((((((({a:a for a in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20000000000000000000]})))))))))
def example8(): def example8():
return (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((None))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) return (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((None)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
``` ```

View file

@ -101,82 +101,80 @@ def foo() -> tuple[int, int, int,]:
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,120 +1,70 @@ @@ -1,33 +1,41 @@
# Control # Control
def double(a: int) -> int: def double(a: int) -> int:
- return 2 * a - return 2 * a
-
-
+ return 2*a + return 2*a
# Remove the brackets # Remove the brackets
-def double(a: int) -> int: -def double(a: int) -> int:
- return 2 * a - return 2 * a
-
-
+def double(a: int) -> (int): +def double(a: int) -> (int):
+ return 2*a + return 2*a
# Some newline variations # Some newline variations
-def double(a: int) -> int: -def double(a: int) -> int:
- return 2 * a - return 2 * a
-
-
-def double(a: int) -> int:
- return 2 * a
-
-
-def double(a: int) -> int:
- return 2 * a
-
-
+def double(a: int) -> ( +def double(a: int) -> (
+ int): + int):
+ return 2*a + return 2*a
-def double(a: int) -> int:
- return 2 * a
+def double(a: int) -> (int +def double(a: int) -> (int
+): +):
+ return 2*a + return 2*a
-def double(a: int) -> int:
- return 2 * a
+def double(a: int) -> ( +def double(a: int) -> (
+ int + int
+): +):
+ return 2*a + return 2*a
# Don't lose the comments # Don't lose the comments
-def double(a: int) -> int: # Hello -def double(a: int) -> int: # Hello
- return 2 * a - return 2 * a
-
-
-def double(a: int) -> int: # Hello
- return 2 * a
-
-
+def double(a: int) -> ( # Hello +def double(a: int) -> ( # Hello
+ int + int
+): +):
+ return 2*a + return 2*a
-def double(a: int) -> int: # Hello
- return 2 * a
+def double(a: int) -> ( +def double(a: int) -> (
+ int # Hello + int # Hello
+): +):
+ return 2*a + return 2*a
# Really long annotations # Really long annotations
def foo() -> ( @@ -37,84 +45,62 @@
intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds
):
return 2 return 2
-
-
-def foo() -> ( -def foo() -> (
- intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds - intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds
-): -):
+def foo() -> intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds: +def foo() -> intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds:
return 2 return 2
-
-
-def foo() -> ( -def foo() -> (
- intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds - intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds
- | intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds - | intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds
-): -):
+def foo() -> intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds | intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds: +def foo() -> intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds | intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds:
return 2 return 2
-
-
-def foo( -def foo(
- a: int, - a: int,
- b: int, - b: int,
@ -184,8 +182,8 @@ def foo() -> tuple[int, int, int,]:
-) -> intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds: -) -> intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds:
+def foo(a: int, b: int, c: int,) -> intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds: +def foo(a: int, b: int, c: int,) -> intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds:
return 2 return 2
-
-
-def foo( -def foo(
- a: int, - a: int,
- b: int, - b: int,
@ -196,8 +194,8 @@ def foo() -> tuple[int, int, int,]:
-): -):
+def foo(a: int, b: int, c: int,) -> intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds | intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds: +def foo(a: int, b: int, c: int,) -> intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds | intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds:
return 2 return 2
-
-
# Split args but no need to split return # Split args but no need to split return
-def foo( -def foo(
- a: int, - a: int,
@ -206,20 +204,18 @@ def foo() -> tuple[int, int, int,]:
-) -> int: -) -> int:
+def foo(a: int, b: int, c: int,) -> int: +def foo(a: int, b: int, c: int,) -> int:
return 2 return 2
-
-
# Deeply nested brackets # Deeply nested brackets
# with *interesting* spacing # with *interesting* spacing
-def double(a: int) -> int: -def double(a: int) -> int:
- return 2 * a - return 2 * a
-
-
-def double(a: int) -> int:
- return 2 * a
-
-
+def double(a: int) -> (((((int))))): +def double(a: int) -> (((((int))))):
+ return 2*a + return 2*a
-def double(a: int) -> int:
- return 2 * a
+def double(a: int) -> ( +def double(a: int) -> (
+ ( ( + ( (
+ ((int) + ((int)
@ -228,6 +224,8 @@ def foo() -> tuple[int, int, int,]:
+ ) + )
+ ): + ):
+ return 2*a + return 2*a
def foo() -> ( def foo() -> (
+ ( ( + ( (
intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds
@ -235,26 +233,27 @@ def foo() -> tuple[int, int, int,]:
+) +)
+)): +)):
return 2 return 2
-
-
# Return type with commas # Return type with commas
-def foo() -> tuple[int, int, int]: -def foo() -> tuple[int, int, int]:
- return 2 +def foo() -> (
- + tuple[int, int, int]
- +):
def foo() -> ( return 2
-def foo() -> (
- tuple[ - tuple[
- loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong, - loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong,
- loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong, - loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong,
- loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong, - loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong,
- ] - ]
+ tuple[int, int, int] -):
):
return 2
-
-
+def foo() -> tuple[loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong, loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong, loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong]: +def foo() -> tuple[loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong, loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong, loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong]:
+ return 2 return 2
# Magic trailing comma example # Magic trailing comma example
-def foo() -> ( -def foo() -> (
- tuple[ - tuple[
@ -273,49 +272,77 @@ def foo() -> tuple[int, int, int,]:
# Control # Control
def double(a: int) -> int: def double(a: int) -> int:
return 2*a return 2*a
# Remove the brackets # Remove the brackets
def double(a: int) -> (int): def double(a: int) -> (int):
return 2*a return 2*a
# Some newline variations # Some newline variations
def double(a: int) -> ( def double(a: int) -> (
int): int):
return 2*a return 2*a
def double(a: int) -> (int def double(a: int) -> (int
): ):
return 2*a return 2*a
def double(a: int) -> ( def double(a: int) -> (
int int
): ):
return 2*a return 2*a
# Don't lose the comments # Don't lose the comments
def double(a: int) -> ( # Hello def double(a: int) -> ( # Hello
int int
): ):
return 2*a return 2*a
def double(a: int) -> ( def double(a: int) -> (
int # Hello int # Hello
): ):
return 2*a return 2*a
# Really long annotations # Really long annotations
def foo() -> ( def foo() -> (
intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds
): ):
return 2 return 2
def foo() -> intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds: def foo() -> intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds:
return 2 return 2
def foo() -> intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds | intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds: def foo() -> intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds | intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds:
return 2 return 2
def foo(a: int, b: int, c: int,) -> intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds: def foo(a: int, b: int, c: int,) -> intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds:
return 2 return 2
def foo(a: int, b: int, c: int,) -> intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds | intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds: def foo(a: int, b: int, c: int,) -> intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds | intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds:
return 2 return 2
# Split args but no need to split return # Split args but no need to split return
def foo(a: int, b: int, c: int,) -> int: def foo(a: int, b: int, c: int,) -> int:
return 2 return 2
# Deeply nested brackets # Deeply nested brackets
# with *interesting* spacing # with *interesting* spacing
def double(a: int) -> (((((int))))): def double(a: int) -> (((((int))))):
return 2*a return 2*a
def double(a: int) -> ( def double(a: int) -> (
( ( ( (
((int) ((int)
@ -324,19 +351,27 @@ def double(a: int) -> (
) )
): ):
return 2*a return 2*a
def foo() -> ( def foo() -> (
( ( ( (
intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds
) )
)): )):
return 2 return 2
# Return type with commas # Return type with commas
def foo() -> ( def foo() -> (
tuple[int, int, int] tuple[int, int, int]
): ):
return 2 return 2
def foo() -> tuple[loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong, loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong, loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong]: def foo() -> tuple[loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong, loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong, loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong]:
return 2 return 2
# Magic trailing comma example # Magic trailing comma example
def foo() -> tuple[int, int, int,]: def foo() -> tuple[int, int, int,]:
return 2 return 2

View file

@ -60,7 +60,7 @@ func(
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,25 +1,40 @@ @@ -1,25 +1,43 @@
# We should not remove the trailing comma in a single-element subscript. # We should not remove the trailing comma in a single-element subscript.
a: tuple[int,] a: tuple[int,]
b = tuple[int,] b = tuple[int,]
@ -86,12 +86,6 @@ func(
- -
# Trailing commas in multiple chained non-nested parens. # Trailing commas in multiple chained non-nested parens.
-zero(one).two(three).four(five) -zero(one).two(three).four(five)
-
-func1(arg1).func2(arg2).func3(arg3).func4(arg4).func5(arg5)
-
-(a, b, c, d) = func1(arg1) and func2(arg2)
-
-func(argument1, (one, two), argument4, argument5, argument6)
+zero( +zero(
+ one, + one,
+).two( +).two(
@ -99,7 +93,11 @@ func(
+).four( +).four(
+ five, + five,
+) +)
-func1(arg1).func2(arg2).func3(arg3).func4(arg4).func5(arg5)
+func1(arg1).func2(arg2,).func3(arg3).func4(arg4,).func5(arg5) +func1(arg1).func2(arg2,).func3(arg3).func4(arg4,).func5(arg5)
-(a, b, c, d) = func1(arg1) and func2(arg2)
+( +(
+ a, + a,
+ b, + b,
@ -108,6 +106,8 @@ func(
+) = func1( +) = func1(
+ arg1 + arg1
+) and func2(arg2) +) and func2(arg2)
-func(argument1, (one, two), argument4, argument5, argument6)
+func( +func(
+ argument1, + argument1,
+ ( + (
@ -144,7 +144,9 @@ zero(
).four( ).four(
five, five,
) )
func1(arg1).func2(arg2,).func3(arg3).func4(arg4,).func5(arg5) func1(arg1).func2(arg2,).func3(arg3).func4(arg4,).func5(arg5)
( (
a, a,
b, b,
@ -153,6 +155,7 @@ func1(arg1).func2(arg2,).func3(arg3).func4(arg4,).func5(arg5)
) = func1( ) = func1(
arg1 arg1
) and func2(arg2) ) and func2(arg2)
func( func(
argument1, argument1,
( (

View file

@ -76,35 +76,7 @@ x[
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -17,19 +17,14 @@ @@ -56,4 +56,8 @@
slice[not so_simple : 1 < val <= 10]
slice[(1 for i in range(42)) : x]
slice[:: [i for i in range(42)]]
-
-
async def f():
slice[await x : [i async for i in arange(42)] : 42]
-
-
# These are from PEP-8:
ham[1:9], ham[1:9:3], ham[:9:3], ham[1::3], ham[1:9:]
ham[lower:upper], ham[lower:upper:], ham[lower::step]
# ham[lower+offset : upper+offset]
ham[: upper_fn(x) : step_fn(x)], ham[:: step_fn(x)]
ham[lower + offset : upper + offset]
-
slice[::, ::]
slice[
# A
@@ -46,7 +41,6 @@
# C
3
]
-
slice[
# A
1
@@ -56,4 +50,8 @@
# C # C
4 4
] ]
@ -138,14 +110,19 @@ slice[1 or 2 : True and False]
slice[not so_simple : 1 < val <= 10] slice[not so_simple : 1 < val <= 10]
slice[(1 for i in range(42)) : x] slice[(1 for i in range(42)) : x]
slice[:: [i for i in range(42)]] slice[:: [i for i in range(42)]]
async def f(): async def f():
slice[await x : [i async for i in arange(42)] : 42] slice[await x : [i async for i in arange(42)] : 42]
# These are from PEP-8: # These are from PEP-8:
ham[1:9], ham[1:9:3], ham[:9:3], ham[1::3], ham[1:9:] ham[1:9], ham[1:9:3], ham[:9:3], ham[1::3], ham[1:9:]
ham[lower:upper], ham[lower:upper:], ham[lower::step] ham[lower:upper], ham[lower:upper:], ham[lower::step]
# ham[lower+offset : upper+offset] # ham[lower+offset : upper+offset]
ham[: upper_fn(x) : step_fn(x)], ham[:: step_fn(x)] ham[: upper_fn(x) : step_fn(x)], ham[:: step_fn(x)]
ham[lower + offset : upper + offset] ham[lower + offset : upper + offset]
slice[::, ::] slice[::, ::]
slice[ slice[
# A # A
@ -162,6 +139,7 @@ slice[
# C # C
3 3
] ]
slice[ slice[
# A # A
1 1

View file

@ -33,7 +33,7 @@ def docstring_multiline():
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,19 +1,14 @@ @@ -1,13 +1,13 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
name = "Łukasz" name = "Łukasz"
@ -44,20 +44,14 @@ def docstring_multiline():
+(b"", B"") +(b"", B"")
+(u"", U"") +(u"", U"")
(r"", R"") (r"", R"")
-
-(rf"", rf"", Rf"", Rf"", rf"", rf"", Rf"", Rf"") -(rf"", rf"", Rf"", Rf"", rf"", rf"", Rf"", Rf"")
-(rb"", rb"", Rb"", Rb"", rb"", rb"", Rb"", Rb"") -(rb"", rb"", Rb"", Rb"", rb"", rb"", Rb"", Rb"")
-
-
+(rf"", fr"", Rf"", fR"", rF"", Fr"", RF"", FR"") +(rf"", fr"", Rf"", fR"", rF"", Fr"", RF"", FR"")
+(rb"", br"", Rb"", bR"", rB"", Br"", RB"", BR"") +(rb"", br"", Rb"", bR"", rB"", Br"", RB"", BR"")
def docstring_singleline(): def docstring_singleline():
R"""2020 was one hell of a year. The good news is that we were able to"""
-
-
def docstring_multiline():
R"""
clear out all of the issues opened in that time :p
``` ```
## Ruff Output ## Ruff Output
@ -70,10 +64,15 @@ name = "Łukasz"
(b"", B"") (b"", B"")
(u"", U"") (u"", U"")
(r"", R"") (r"", R"")
(rf"", fr"", Rf"", fR"", rF"", Fr"", RF"", FR"") (rf"", fr"", Rf"", fR"", rF"", Fr"", RF"", FR"")
(rb"", br"", Rb"", bR"", rB"", Br"", RB"", BR"") (rb"", br"", Rb"", bR"", rB"", Br"", RB"", BR"")
def docstring_singleline(): def docstring_singleline():
R"""2020 was one hell of a year. The good news is that we were able to""" R"""2020 was one hell of a year. The good news is that we were able to"""
def docstring_multiline(): def docstring_multiline():
R""" R"""
clear out all of the issues opened in that time :p clear out all of the issues opened in that time :p

View file

@ -42,15 +42,15 @@ assert (
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,58 +1,25 @@ @@ -1,58 +1,33 @@
importA importA
-( -(
- () - ()
- << 0 - << 0
- ** 101234234242352525425252352352525234890264906820496920680926538059059209922523523525 - ** 101234234242352525425252352352525234890264906820496920680926538059059209922523523525
-) # -) #
-
+() << 0 ** 101234234242352525425252352352525234890264906820496920680926538059059209922523523525 # +() << 0 ** 101234234242352525425252352352525234890264906820496920680926538059059209922523523525 #
assert sort_by_dependency( assert sort_by_dependency(
{ {
- "1": {"2", "3"}, - "1": {"2", "3"},
@ -64,13 +64,13 @@ assert (
+ "2a": set(), "2b": set(), "3a": set(), "3b": set() + "2a": set(), "2b": set(), "3a": set(), "3b": set()
} }
) == ["2a", "2b", "2", "3a", "3b", "3", "1"] ) == ["2a", "2b", "2", "3a", "3b", "3", "1"]
-
importA importA
0 0
-0 ^ 0 # -0 ^ 0 #
-
-
+0^0 # +0^0 #
class A: class A:
def foo(self): def foo(self):
for _ in range(10): for _ in range(10):
@ -78,9 +78,9 @@ assert (
+ aaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbb.cccccccccc( # pylint: disable=no-member + aaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbb.cccccccccc( # pylint: disable=no-member
xxxxxxxxxxxx xxxxxxxxxxxx
- ) # pylint: disable=no-member - ) # pylint: disable=no-member
-
-
+ ) + )
def test(self, othr): def test(self, othr):
- return 1 == 2 and ( - return 1 == 2 and (
- name, - name,
@ -101,15 +101,15 @@ assert (
- othr.meta_data, - othr.meta_data,
- othr.schedule, - othr.schedule,
- ) - )
- + return (1 == 2 and
- + (name, description, self.default, self.selected, self.auto_generated, self.parameters, self.meta_data, self.schedule) ==
+ (name, description, othr.default, othr.selected, othr.auto_generated, othr.parameters, othr.meta_data, othr.schedule))
-assert a_function( -assert a_function(
- very_long_arguments_that_surpass_the_limit, - very_long_arguments_that_surpass_the_limit,
- which_is_eighty_eight_in_this_case_plus_a_bit_more, - which_is_eighty_eight_in_this_case_plus_a_bit_more,
-) == {"x": "this need to pass the line limit as well", "b": "but only by a little bit"} -) == {"x": "this need to pass the line limit as well", "b": "but only by a little bit"}
+ return (1 == 2 and
+ (name, description, self.default, self.selected, self.auto_generated, self.parameters, self.meta_data, self.schedule) ==
+ (name, description, othr.default, othr.selected, othr.auto_generated, othr.parameters, othr.meta_data, othr.schedule))
+assert ( +assert (
+ a_function(very_long_arguments_that_surpass_the_limit, which_is_eighty_eight_in_this_case_plus_a_bit_more) + a_function(very_long_arguments_that_surpass_the_limit, which_is_eighty_eight_in_this_case_plus_a_bit_more)
+ == {"x": "this need to pass the line limit as well", "b": "but only by a little bit"} + == {"x": "this need to pass the line limit as well", "b": "but only by a little bit"}
@ -121,25 +121,33 @@ assert (
```py ```py
importA importA
() << 0 ** 101234234242352525425252352352525234890264906820496920680926538059059209922523523525 # () << 0 ** 101234234242352525425252352352525234890264906820496920680926538059059209922523523525 #
assert sort_by_dependency( assert sort_by_dependency(
{ {
"1": {"2", "3"}, "2": {"2a", "2b"}, "3": {"3a", "3b"}, "1": {"2", "3"}, "2": {"2a", "2b"}, "3": {"3a", "3b"},
"2a": set(), "2b": set(), "3a": set(), "3b": set() "2a": set(), "2b": set(), "3a": set(), "3b": set()
} }
) == ["2a", "2b", "2", "3a", "3b", "3", "1"] ) == ["2a", "2b", "2", "3a", "3b", "3", "1"]
importA importA
0 0
0^0 # 0^0 #
class A: class A:
def foo(self): def foo(self):
for _ in range(10): for _ in range(10):
aaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbb.cccccccccc( # pylint: disable=no-member aaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbb.cccccccccc( # pylint: disable=no-member
xxxxxxxxxxxx xxxxxxxxxxxx
) )
def test(self, othr): def test(self, othr):
return (1 == 2 and return (1 == 2 and
(name, description, self.default, self.selected, self.auto_generated, self.parameters, self.meta_data, self.schedule) == (name, description, self.default, self.selected, self.auto_generated, self.parameters, self.meta_data, self.schedule) ==
(name, description, othr.default, othr.selected, othr.auto_generated, othr.parameters, othr.meta_data, othr.schedule)) (name, description, othr.default, othr.selected, othr.auto_generated, othr.parameters, othr.meta_data, othr.schedule))
assert ( assert (
a_function(very_long_arguments_that_surpass_the_limit, which_is_eighty_eight_in_this_case_plus_a_bit_more) a_function(very_long_arguments_that_surpass_the_limit, which_is_eighty_eight_in_this_case_plus_a_bit_more)
== {"x": "this need to pass the line limit as well", "b": "but only by a little bit"} == {"x": "this need to pass the line limit as well", "b": "but only by a little bit"}

View file

@ -38,7 +38,7 @@ class A:
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,29 +1,17 @@ @@ -1,18 +1,11 @@
-if e1234123412341234.winerror not in ( -if e1234123412341234.winerror not in (
- _winapi.ERROR_SEM_TIMEOUT, - _winapi.ERROR_SEM_TIMEOUT,
- _winapi.ERROR_PIPE_BUSY, - _winapi.ERROR_PIPE_BUSY,
@ -46,7 +46,7 @@ class A:
+if e1234123412341234.winerror not in (_winapi.ERROR_SEM_TIMEOUT, +if e1234123412341234.winerror not in (_winapi.ERROR_SEM_TIMEOUT,
+ _winapi.ERROR_PIPE_BUSY) or _check_timeout(t): + _winapi.ERROR_PIPE_BUSY) or _check_timeout(t):
pass pass
-
if x: if x:
if y: if y:
- new_id = ( - new_id = (
@ -56,23 +56,20 @@ class A:
- ) - )
- + 1 - + 1
- ) - )
-
-
+ new_id = max(Vegetable.objects.order_by('-id')[0].id, + new_id = max(Vegetable.objects.order_by('-id')[0].id,
+ Mineral.objects.order_by('-id')[0].id) + 1 + Mineral.objects.order_by('-id')[0].id) + 1
class X: class X:
def get_help_text(self): @@ -21,7 +14,7 @@
return ngettext(
"Your password must contain at least %(min_length)d character.", "Your password must contain at least %(min_length)d character.",
"Your password must contain at least %(min_length)d characters.", "Your password must contain at least %(min_length)d characters.",
self.min_length, self.min_length,
- ) % {"min_length": self.min_length} - ) % {"min_length": self.min_length}
-
-
+ ) % {'min_length': self.min_length} + ) % {'min_length': self.min_length}
class A: class A:
def b(self):
if self.connection.mysql_is_mariadb and (
``` ```
## Ruff Output ## Ruff Output
@ -81,10 +78,13 @@ class A:
if e1234123412341234.winerror not in (_winapi.ERROR_SEM_TIMEOUT, if e1234123412341234.winerror not in (_winapi.ERROR_SEM_TIMEOUT,
_winapi.ERROR_PIPE_BUSY) or _check_timeout(t): _winapi.ERROR_PIPE_BUSY) or _check_timeout(t):
pass pass
if x: if x:
if y: if y:
new_id = max(Vegetable.objects.order_by('-id')[0].id, new_id = max(Vegetable.objects.order_by('-id')[0].id,
Mineral.objects.order_by('-id')[0].id) + 1 Mineral.objects.order_by('-id')[0].id) + 1
class X: class X:
def get_help_text(self): def get_help_text(self):
return ngettext( return ngettext(
@ -92,6 +92,8 @@ class X:
"Your password must contain at least %(min_length)d characters.", "Your password must contain at least %(min_length)d characters.",
self.min_length, self.min_length,
) % {'min_length': self.min_length} ) % {'min_length': self.min_length}
class A: class A:
def b(self): def b(self):
if self.connection.mysql_is_mariadb and ( if self.connection.mysql_is_mariadb and (

View file

@ -46,7 +46,7 @@ assert xxxxxxxxx.xxxxxxxxx.xxxxxxxxx(
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,30 +1,8 @@ @@ -1,28 +1,10 @@
-zero( -zero(
- one, - one,
-).two( -).two(
@ -60,12 +60,12 @@ assert xxxxxxxxx.xxxxxxxxx.xxxxxxxxx(
-).func3(arg3).func4( -).func3(arg3).func4(
- arg4, - arg4,
-).func5(arg5) -).func5(arg5)
-
+zero(one,).two(three,).four(five,) +zero(one,).two(three,).four(five,)
+func1(arg1).func2(arg2,).func3(arg3).func4(arg4,).func5(arg5) +func1(arg1).func2(arg2,).func3(arg3).func4(arg4,).func5(arg5)
# Inner one-element tuple shouldn't explode # Inner one-element tuple shouldn't explode
func1(arg1).func2(arg1, (one_tuple,)).func3(arg3) func1(arg1).func2(arg1, (one_tuple,)).func3(arg3)
-
-( -(
- a, - a,
- b, - b,
@ -74,21 +74,11 @@ assert xxxxxxxxx.xxxxxxxxx.xxxxxxxxx(
-) = func1( -) = func1(
- arg1 - arg1
-) and func2(arg2) -) and func2(arg2)
-
-
+(a, b, c, d,) = func1(arg1) and func2(arg2) +(a, b, c, d,) = func1(arg1) and func2(arg2)
# Example from https://github.com/psf/black/issues/3229 # Example from https://github.com/psf/black/issues/3229
def refresh_token(self, device_family, refresh_token, api_key): @@ -41,7 +23,6 @@
return self.orchestration.refresh_token(
@@ -33,15 +11,12 @@
},
api_key=api_key,
)["extensions"]["sdk"]["token"]
-
-
# Edge case where a bug in a working-in-progress version of
# https://github.com/psf/black/pull/3370 causes an infinite recursion.
assert (
long_module.long_class.long_func().another_func() long_module.long_class.long_func().another_func()
== long_module.long_class.long_func()["some_key"].another_func(arg1) == long_module.long_class.long_func()["some_key"].another_func(arg1)
) )
@ -102,10 +92,14 @@ assert xxxxxxxxx.xxxxxxxxx.xxxxxxxxx(
```py ```py
zero(one,).two(three,).four(five,) zero(one,).two(three,).four(five,)
func1(arg1).func2(arg2,).func3(arg3).func4(arg4,).func5(arg5) func1(arg1).func2(arg2,).func3(arg3).func4(arg4,).func5(arg5)
# Inner one-element tuple shouldn't explode # Inner one-element tuple shouldn't explode
func1(arg1).func2(arg1, (one_tuple,)).func3(arg3) func1(arg1).func2(arg1, (one_tuple,)).func3(arg3)
(a, b, c, d,) = func1(arg1) and func2(arg2) (a, b, c, d,) = func1(arg1) and func2(arg2)
# Example from https://github.com/psf/black/issues/3229 # Example from https://github.com/psf/black/issues/3229
def refresh_token(self, device_family, refresh_token, api_key): def refresh_token(self, device_family, refresh_token, api_key):
return self.orchestration.refresh_token( return self.orchestration.refresh_token(
@ -114,6 +108,8 @@ def refresh_token(self, device_family, refresh_token, api_key):
}, },
api_key=api_key, api_key=api_key,
)["extensions"]["sdk"]["token"] )["extensions"]["sdk"]["token"]
# Edge case where a bug in a working-in-progress version of # Edge case where a bug in a working-in-progress version of
# https://github.com/psf/black/pull/3370 causes an infinite recursion. # https://github.com/psf/black/pull/3370 causes an infinite recursion.
assert ( assert (

View file

@ -1,61 +0,0 @@
---
source: crates/ruff_python_formatter/src/lib.rs
expression: snapshot
input_file: crates/ruff_python_formatter/resources/test/fixtures/black/simple_cases/tricky_unicode_symbols.py
---
## Input
```py
ä = 1
µ = 2
蟒 = 3
x󠄀 = 4
មុ = 1
Q̇_per_meter = 4
A᧚ = 3
A፩ = 8
```
## Black Differences
```diff
--- Black
+++ Ruff
@@ -4,6 +4,5 @@
x󠄀 = 4
មុ = 1
Q̇_per_meter = 4
-
A᧚ = 3
A፩ = 8
```
## Ruff Output
```py
ä = 1
µ = 2
蟒 = 3
x󠄀 = 4
មុ = 1
Q̇_per_meter = 4
A᧚ = 3
A፩ = 8
```
## Black Output
```py
ä = 1
µ = 2
蟒 = 3
x󠄀 = 4
មុ = 1
Q̇_per_meter = 4
A᧚ = 3
A፩ = 8
```

View file

@ -20,7 +20,7 @@ this_will_be_wrapped_in_parens, = struct.unpack(b"12345678901234567890")
```diff ```diff
--- Black --- Black
+++ Ruff +++ Ruff
@@ -1,12 +1,5 @@ @@ -1,12 +1,6 @@
# This is a standalone comment. # This is a standalone comment.
-( -(
- sdfjklsdfsjldkflkjsf, - sdfjklsdfsjldkflkjsf,
@ -32,8 +32,8 @@ this_will_be_wrapped_in_parens, = struct.unpack(b"12345678901234567890")
+sdfjklsdfsjldkflkjsf, sdfjsdfjlksdljkfsdlkf, sdfsdjfklsdfjlksdljkf, sdsfsdfjskdflsfsdf = 1, 2, 3 +sdfjklsdfsjldkflkjsf, sdfjsdfjlksdljkfsdlkf, sdfsdjfklsdfjlksdljkf, sdsfsdfjskdflsfsdf = 1, 2, 3
# This is as well. # This is as well.
-(this_will_be_wrapped_in_parens,) = struct.unpack(b"12345678901234567890") -(this_will_be_wrapped_in_parens,) = struct.unpack(b"12345678901234567890")
-
+this_will_be_wrapped_in_parens, = struct.unpack(b"12345678901234567890") +this_will_be_wrapped_in_parens, = struct.unpack(b"12345678901234567890")
(a,) = call() (a,) = call()
``` ```
@ -44,6 +44,7 @@ this_will_be_wrapped_in_parens, = struct.unpack(b"12345678901234567890")
sdfjklsdfsjldkflkjsf, sdfjsdfjlksdljkfsdlkf, sdfsdjfklsdfjlksdljkf, sdsfsdfjskdflsfsdf = 1, 2, 3 sdfjklsdfsjldkflkjsf, sdfjsdfjlksdljkfsdlkf, sdfsdjfklsdfjlksdljkf, sdsfsdfjskdflsfsdf = 1, 2, 3
# This is as well. # This is as well.
this_will_be_wrapped_in_parens, = struct.unpack(b"12345678901234567890") this_will_be_wrapped_in_parens, = struct.unpack(b"12345678901234567890")
(a,) = call() (a,) = call()
``` ```

View file

@ -51,6 +51,8 @@ else: # trailing else comment
pass pass
# trailing else body comment # trailing else body comment
while ( while (
aVeryLongConditionThatSpillsOverToTheNextLineBecauseItIsExtremelyLongAndGoesOnAndOnAndOnAndOnAndOnAndOnAndOnAndOnAndOn aVeryLongConditionThatSpillsOverToTheNextLineBecauseItIsExtremelyLongAndGoesOnAndOnAndOnAndOnAndOnAndOnAndOnAndOnAndOn
): # trailing comment ): # trailing comment
@ -58,8 +60,11 @@ while (
else: else:
... ...
while some_condition(unformatted, args) and anotherCondition or aThirdCondition: # comment while some_condition(unformatted, args) and anotherCondition or aThirdCondition: # comment
print("Do something") print("Do something")
while ( while (
some_condition(unformatted, args) # trailing some condition some_condition(unformatted, args) # trailing some condition
and anotherCondition or aThirdCondition # trailing third condition and anotherCondition or aThirdCondition # trailing third condition