Add a trailing newline to all .py.expect files (#3156)

This just re-formats all the `.py.expect` files with Black, both to add a trailing newline and be doubly-certain that they're correctly formatted.

I also ensured that we add a hard line break after each statement, and that we avoid including an extra newline in the generated Markdown (since the code should contain the exact expected newlines).
This commit is contained in:
Charlie Marsh 2023-02-22 21:29:27 -05:00 committed by GitHub
parent c1ddcb8a60
commit 5fd827545b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
104 changed files with 182 additions and 1464 deletions

View file

@ -19,4 +19,4 @@ if (10).real:
... ...
y = 100[no] y = 100[no]
y = 100(no) y = 100(no)

View file

@ -1 +1 @@
print("hello, world") print("hello, world")

View file

@ -1,4 +1,4 @@
for ((x in {}) or {})["a"] in x: for ((x in {}) or {})["a"] in x:
pass pass
pem_spam = lambda l, spam={"x": 3}: not spam.get(l.strip()) pem_spam = lambda l, spam={"x": 3}: not spam.get(l.strip())
lambda x=lambda y={1: 3}: y["x" : lambda y: {1: 2}]: x lambda x=lambda y={1: 3}: y["x" : lambda y: {1: 2}]: x

View file

@ -27,4 +27,4 @@ def class_under_the_func_with_blank_parentheses():
class NormalClass: class NormalClass:
def func_for_testing(self, first, second): def func_for_testing(self, first, second):
sum = first + second sum = first + second
return sum return sum

View file

@ -162,4 +162,4 @@ class ClassWithDecoInitAndVarsAndDocstringWithInner2:
@deco @deco
def __init__(self): def __init__(self):
pass pass

View file

@ -96,4 +96,4 @@ if True:
WaiterConfig={ WaiterConfig={
"Delay": 5, "Delay": 5,
}, },
) )

View file

@ -3,4 +3,4 @@ def bob(): # pylint: disable=W9016
def bobtwo(): # some comment here def bobtwo(): # some comment here
pass pass

View file

@ -170,4 +170,4 @@ class Test:
instruction() # comment with bad spacing instruction() # comment with bad spacing
# END COMMENTS # END COMMENTS
# MORE END COMMENTS # MORE END COMMENTS

View file

@ -45,4 +45,4 @@ def func():
) )
# %% # %%

View file

@ -91,4 +91,4 @@ def foo3(list_a, list_b):
db.or_(User.field_a.astext.in_(list_a), User.field_b.astext.in_(list_b)) db.or_(User.field_a.astext.in_(list_a), User.field_b.astext.in_(list_b))
) )
.filter(User.xyz.is_(None)) .filter(User.xyz.is_(None))
) )

View file

@ -70,4 +70,4 @@ def g():
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View file

@ -115,4 +115,4 @@ call_to_some_function_asdf(
[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

@ -3,4 +3,4 @@
# to the latter. # to the latter.
# %% # %%
# %% # %%

View file

@ -158,4 +158,4 @@ def foo():
@decorator1 @decorator1
# A standalone comment # A standalone comment
def bar(): def bar():
pass pass

View file

@ -20,4 +20,4 @@ def function(a: int = 42):
""" """
# There's a NBSP + 3 spaces before # There's a NBSP + 3 spaces before
# And 4 spaces on the next line # And 4 spaces on the next line
pass pass

View file

@ -178,4 +178,4 @@ class C:
key8: value8, key8: value8,
key9: value9, key9: value9,
} }
) )

View file

@ -178,4 +178,4 @@ class C:
key8: value8, key8: value8,
key9: value9, key9: value9,
} }
) )

View file

@ -216,4 +216,4 @@ def stable_quote_normalization_with_immediate_inner_single_quote(self):
"""'<text here> """'<text here>
<text here, since without another non-empty line black is stable> <text here, since without another non-empty line black is stable>
""" """

View file

@ -1,4 +1,4 @@
# Make sure when the file ends with class's docstring, # Make sure when the file ends with class's docstring,
# It doesn't add extra blank lines. # It doesn't add extra blank lines.
class ClassWithDocstring: class ClassWithDocstring:
"""A docstring.""" """A docstring."""

View file

@ -45,4 +45,4 @@ def single_quote_docstring_over_line_limit():
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

@ -86,4 +86,4 @@ def g():
syms.arglist, syms.arglist,
syms.argument, syms.argument,
}: }:
return NO return NO

View file

@ -114,7 +114,7 @@ call(
arg, arg,
another, another,
kwarg="hey", kwarg="hey",
**kwargs **kwargs,
) # note: no trailing comma pre-3.6 ) # note: no trailing comma pre-3.6
call(*gidgets[:2]) call(*gidgets[:2])
call(a, *gidgets[:2]) call(a, *gidgets[:2])
@ -367,4 +367,4 @@ bbbb >> bbbb * bbbb
^ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ^ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
) )
last_call() last_call()
# standalone comment at ENDMARKER # standalone comment at ENDMARKER

View file

@ -221,4 +221,4 @@ yield 'hello'
# No formatting to the end of the file # No formatting to the end of the file
l=[1,2,3] l=[1,2,3]
d={'a':1, d={'a':1,
'b':2} 'b':2}

View file

@ -37,4 +37,4 @@ def test_calculate_fades():
(None, 4, 0, 0, 10, 0, 0, 6, 10), (None, 4, 0, 0, 10, 0, 0, 6, 10),
] ]
# fmt: on # fmt: on

View file

@ -12,4 +12,4 @@ x = [
] ]
# fmt: on # fmt: on
x = [1, 2, 3, 4] x = [1, 2, 3, 4]

View file

@ -17,4 +17,4 @@ def f():
] ]
) )
def f(): def f():
pass pass

View file

@ -84,4 +84,4 @@ if x:
# fmt: off # fmt: off
elif unformatted: elif unformatted:
# fmt: on # fmt: on
will_be_formatted() will_be_formatted()

View file

@ -1,3 +1,3 @@
a, b = 1, 2 a, b = 1, 2
c = 6 # fmt: skip c = 6 # fmt: skip
d = 5 d = 5

View file

@ -8,4 +8,4 @@ l3 = [
"I have", "I have",
"trailing comma", "trailing comma",
"so I should be braked", "so I should be braked",
] ]

View file

@ -7,4 +7,4 @@ e = 5
f = [ f = [
"This is a very long line that should be formatted into a clearer line ", "This is a very long line that should be formatted into a clearer line ",
"by rearranging.", "by rearranging.",
] ]

View file

@ -4,4 +4,4 @@ l = [
1, 1,
2, 2,
3, 3,
] ]

View file

@ -6,4 +6,4 @@ if (
): ):
print("I'm good!") print("I'm good!")
else: else:
print("I'm bad") print("I'm bad")

View file

@ -2,4 +2,4 @@ class A:
def f(self): def f(self):
for line in range(10): for line in range(10):
if True: if True:
pass # fmt: skip pass # fmt: skip

View file

@ -1,4 +1,4 @@
a = "this is some code" a = "this is some code"
b = 5 # fmt:skip b = 5 # fmt:skip
c = 9 # fmt: skip c = 9 # fmt: skip
d = "thisisasuperlongstringthisisasuperlongstringthisisasuperlongstringthisisasuperlongstring" # fmt:skip d = "thisisasuperlongstringthisisasuperlongstringthisisasuperlongstringthisisasuperlongstring" # fmt:skip

View file

@ -59,4 +59,4 @@ with give_me_context( unformatted, args ): # 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

@ -6,4 +6,4 @@ f'some f-string with {a} {few(""):.2f} {formatted.values!r}'
f"{f'''{'nested'} inner'''} outer" f"{f'''{'nested'} inner'''} outer"
f"\"{f'{nested} inner'}\" outer" f"\"{f'{nested} inner'}\" outer"
f"space between opening braces: { {a for a in (1, 2, 3)}}" f"space between opening braces: { {a for a in (1, 2, 3)}}"
f'Hello \'{tricky + "example"}\'' f'Hello \'{tricky + "example"}\''

View file

@ -145,4 +145,4 @@ def f(
def __await__(): def __await__():
return (yield) return (yield)

View file

@ -63,4 +63,4 @@ else:
with hmm_but_this_should_get_two_preceding_newlines(): with hmm_but_this_should_get_two_preceding_newlines():
pass pass

View file

@ -111,4 +111,4 @@ some_module.some_function(
argument4, argument4,
argument5, argument5,
argument6, argument6,
) )

View file

@ -61,4 +61,4 @@ __all__ = (
+ queues.__all__ + queues.__all__
+ streams.__all__ + streams.__all__
+ tasks.__all__ + tasks.__all__
) )

View file

@ -19,4 +19,4 @@ small_list = [
] ]
list_of_types = [ list_of_types = [
tuple[int,], tuple[int,],
] ]

View file

@ -60,4 +60,4 @@ if hasattr(view, "sum_of_weights"):
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

@ -18,4 +18,4 @@
# exactly line length limit + 1, it won't be split like that. # exactly line length limit + 1, it won't be split like that.
xxxxxxxxx_yyy_zzzzzzzz[ xxxxxxxxx_yyy_zzzzzzzz[
xx.xxxxxx(x_yyy_zzzzzz.xxxxx[0]), x_yyy_zzzzzz.xxxxxx(xxxx=1) xx.xxxxxx(x_yyy_zzzzzz.xxxxx[0]), x_yyy_zzzzzz.xxxxxx(xxxx=1)
] = 1 ] = 1

View file

@ -90,4 +90,4 @@ async def main():
async def main(): async def main():
await (yield) await (yield)

View file

@ -39,4 +39,4 @@ except (
some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error, some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error,
some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error, some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error,
) as err: ) as err:
raise err raise err

View file

@ -24,4 +24,4 @@ for (
# Test deeply nested brackets # Test deeply nested brackets
for k, v in d.items(): for k, v in d.items():
print(k, v) print(k, v)

View file

@ -75,4 +75,4 @@ with open("/path/to/file.txt", mode="w") as 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())

View file

@ -82,4 +82,4 @@ def example7():
def example8(): def example8():
return None return None

View file

@ -117,4 +117,4 @@ def foo() -> (
int, int,
] ]
): ):
return 2 return 2

View file

@ -22,4 +22,4 @@ func1(arg1).func2(arg2).func3(arg3).func4(arg4).func5(arg5)
(a, b, c, d) = func1(arg1) and func2(arg2) (a, b, c, d) = func1(arg1) and func2(arg2)
func(argument1, (one, two), argument4, argument5, argument6) func(argument1, (one, two), argument4, argument5, argument6)

View file

@ -28,4 +28,4 @@ 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]

View file

@ -17,4 +17,4 @@ def docstring_singleline():
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

@ -55,4 +55,4 @@ def test(self, othr):
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"}

View file

@ -31,4 +31,4 @@ class A:
4, 4,
3, 3,
) < self.connection.mysql_version < (10, 5, 2): ) < self.connection.mysql_version < (10, 5, 2):
pass pass

View file

@ -3,4 +3,4 @@ if e123456.get_tk_patchlevel() >= (8, 6, 0, "final") or (
5, 5,
8, 8,
) <= get_tk_patchlevel() < (8, 6): ) <= get_tk_patchlevel() < (8, 6):
pass pass

View file

@ -5,4 +5,4 @@ if True:
"qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweas " "qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweas "
+ "qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqwegqweasdzxcqweasdzxc.", + "qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqwegqweasdzxcqweasdzxc.",
"qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqwe", "qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqwe",
) % {"reported_username": reported_username, "report_reason": report_reason} ) % {"reported_username": reported_username, "report_reason": report_reason}

View file

@ -47,4 +47,4 @@ assert xxxxxxxxx.xxxxxxxxx.xxxxxxxxx(
xxxxxxxxx xxxxxxxxx
).xxxxxxxxxxxxxxxxxx(), ( ).xxxxxxxxxxxxxxxxxx(), (
"xxx {xxxxxxxxx} xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxx {xxxxxxxxx} xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
) )

View file

@ -6,4 +6,4 @@ x󠄀 = 4
Q̇_per_meter = 4 Q̇_per_meter = 4
A᧚ = 3 A᧚ = 3
A፩ = 8 A፩ = 8

View file

@ -4,9 +4,13 @@
sdfjsdfjlksdljkfsdlkf, sdfjsdfjlksdljkfsdlkf,
sdfsdjfklsdfjlksdljkf, sdfsdjfklsdfjlksdljkf,
sdsfsdfjskdflsfsdf, sdsfsdfjskdflsfsdf,
) = 1, 2, 3 ) = (
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

@ -882,6 +882,8 @@ impl Format<ASTFormatContext<'_>> for FormatStmt<'_> {
} }
}?; }?;
write!(f, [hard_line_break()])?;
// Any trailing comments come on the lines after. // Any trailing comments come on the lines after.
for trivia in &self.item.trivia { for trivia in &self.item.trivia {
if matches!(trivia.relationship, Relationship::Trailing) { if matches!(trivia.relationship, Relationship::Trailing) {

View file

@ -208,7 +208,7 @@ mod tests {
impl std::fmt::Display for CodeFrame<'_> { impl std::fmt::Display for CodeFrame<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
writeln!(f, "```{}", self.language)?; writeln!(f, "```{}", self.language)?;
writeln!(f, "{}", self.code)?; write!(f, "{}", self.code)?;
writeln!(f, "```")?; writeln!(f, "```")?;
writeln!(f) writeln!(f)
} }

View file

@ -28,7 +28,6 @@ if 10 .real:
y = 100[no] y = 100[no]
y = 100(no) y = 100(no)
``` ```
## Black Differences ## Black Differences
@ -75,10 +74,7 @@ y = 100(no)
y = 100[no] y = 100[no]
-y = 100(no) -y = 100(no)
\ No newline at end of file
+y = 100((no)) +y = 100((no))
\ No newline at end of file
``` ```
## Ruff Output ## Ruff Output

View file

@ -12,7 +12,6 @@ pem_spam = lambda l, spam = {
"x": 3 "x": 3
}: not spam.get(l.strip()) }: not spam.get(l.strip())
lambda x=lambda y={1: 3}: y['x':lambda y: {1: 2}]: x lambda x=lambda y={1: 3}: y['x':lambda y: {1: 2}]: x
``` ```
## Black Differences ## Black Differences
@ -26,10 +25,7 @@ lambda x=lambda y={1: 3}: y['x':lambda y: {1: 2}]: x
pass pass
pem_spam = lambda l, spam={"x": 3}: not spam.get(l.strip()) pem_spam = lambda l, spam={"x": 3}: not spam.get(l.strip())
-lambda x=lambda y={1: 3}: y["x" : lambda y: {1: 2}]: x -lambda x=lambda y={1: 3}: y["x" : lambda y: {1: 2}]: x
\ No newline at end of file
+lambda x=lambda y={1: 3}: y['x' : lambda y: {1: 2}]: x +lambda x=lambda y={1: 3}: y['x' : lambda y: {1: 2}]: x
\ No newline at end of file
``` ```
## Ruff Output ## Ruff Output

View file

@ -1,121 +0,0 @@
---
source: crates/ruff_python_formatter/src/lib.rs
expression: snapshot
input_file: crates/ruff_python_formatter/resources/test/fixtures/black/simple_cases/class_blank_parentheses.py
---
## Input
```py
class SimpleClassWithBlankParentheses():
pass
class ClassWithSpaceParentheses ( ):
first_test_data = 90
second_test_data = 100
def test_func(self):
return None
class ClassWithEmptyFunc(object):
def func_with_blank_parentheses():
return 5
def public_func_with_blank_parentheses():
return None
def class_under_the_func_with_blank_parentheses():
class InsideFunc():
pass
class NormalClass (
):
def func_for_testing(self, first, second):
sum = first + second
return sum
```
## Black Differences
```diff
--- Black
+++ Ruff
@@ -27,4 +27,4 @@
class NormalClass:
def func_for_testing(self, first, second):
sum = first + second
- return sum
\ No newline at end of file
+ return sum
```
## Ruff Output
```py
class SimpleClassWithBlankParentheses:
pass
class ClassWithSpaceParentheses:
first_test_data = 90
second_test_data = 100
def test_func(self):
return None
class ClassWithEmptyFunc(object):
def func_with_blank_parentheses():
return 5
def public_func_with_blank_parentheses():
return None
def class_under_the_func_with_blank_parentheses():
class InsideFunc:
pass
class NormalClass:
def func_for_testing(self, first, second):
sum = first + second
return sum
```
## Black Output
```py
class SimpleClassWithBlankParentheses:
pass
class ClassWithSpaceParentheses:
first_test_data = 90
second_test_data = 100
def test_func(self):
return None
class ClassWithEmptyFunc(object):
def func_with_blank_parentheses():
return 5
def public_func_with_blank_parentheses():
return None
def class_under_the_func_with_blank_parentheses():
class InsideFunc:
pass
class NormalClass:
def func_for_testing(self, first, second):
sum = first + second
return sum
```

View file

@ -1,468 +0,0 @@
---
source: crates/ruff_python_formatter/src/lib.rs
expression: snapshot
input_file: crates/ruff_python_formatter/resources/test/fixtures/black/simple_cases/class_methods_new_line.py
---
## Input
```py
class ClassSimplest:
pass
class ClassWithSingleField:
a = 1
class ClassWithJustTheDocstring:
"""Just a docstring."""
class ClassWithInit:
def __init__(self):
pass
class ClassWithTheDocstringAndInit:
"""Just a docstring."""
def __init__(self):
pass
class ClassWithInitAndVars:
cls_var = 100
def __init__(self):
pass
class ClassWithInitAndVarsAndDocstring:
"""Test class"""
cls_var = 100
def __init__(self):
pass
class ClassWithDecoInit:
@deco
def __init__(self):
pass
class ClassWithDecoInitAndVars:
cls_var = 100
@deco
def __init__(self):
pass
class ClassWithDecoInitAndVarsAndDocstring:
"""Test class"""
cls_var = 100
@deco
def __init__(self):
pass
class ClassSimplestWithInner:
class Inner:
pass
class ClassSimplestWithInnerWithDocstring:
class Inner:
"""Just a docstring."""
def __init__(self):
pass
class ClassWithSingleFieldWithInner:
a = 1
class Inner:
pass
class ClassWithJustTheDocstringWithInner:
"""Just a docstring."""
class Inner:
pass
class ClassWithInitWithInner:
class Inner:
pass
def __init__(self):
pass
class ClassWithInitAndVarsWithInner:
cls_var = 100
class Inner:
pass
def __init__(self):
pass
class ClassWithInitAndVarsAndDocstringWithInner:
"""Test class"""
cls_var = 100
class Inner:
pass
def __init__(self):
pass
class ClassWithDecoInitWithInner:
class Inner:
pass
@deco
def __init__(self):
pass
class ClassWithDecoInitAndVarsWithInner:
cls_var = 100
class Inner:
pass
@deco
def __init__(self):
pass
class ClassWithDecoInitAndVarsAndDocstringWithInner:
"""Test class"""
cls_var = 100
class Inner:
pass
@deco
def __init__(self):
pass
class ClassWithDecoInitAndVarsAndDocstringWithInner2:
"""Test class"""
class Inner:
pass
cls_var = 100
@deco
def __init__(self):
pass
```
## Black Differences
```diff
--- Black
+++ Ruff
@@ -162,4 +162,4 @@
@deco
def __init__(self):
- pass
\ No newline at end of file
+ pass
```
## Ruff Output
```py
class ClassSimplest:
pass
class ClassWithSingleField:
a = 1
class ClassWithJustTheDocstring:
"""Just a docstring."""
class ClassWithInit:
def __init__(self):
pass
class ClassWithTheDocstringAndInit:
"""Just a docstring."""
def __init__(self):
pass
class ClassWithInitAndVars:
cls_var = 100
def __init__(self):
pass
class ClassWithInitAndVarsAndDocstring:
"""Test class"""
cls_var = 100
def __init__(self):
pass
class ClassWithDecoInit:
@deco
def __init__(self):
pass
class ClassWithDecoInitAndVars:
cls_var = 100
@deco
def __init__(self):
pass
class ClassWithDecoInitAndVarsAndDocstring:
"""Test class"""
cls_var = 100
@deco
def __init__(self):
pass
class ClassSimplestWithInner:
class Inner:
pass
class ClassSimplestWithInnerWithDocstring:
class Inner:
"""Just a docstring."""
def __init__(self):
pass
class ClassWithSingleFieldWithInner:
a = 1
class Inner:
pass
class ClassWithJustTheDocstringWithInner:
"""Just a docstring."""
class Inner:
pass
class ClassWithInitWithInner:
class Inner:
pass
def __init__(self):
pass
class ClassWithInitAndVarsWithInner:
cls_var = 100
class Inner:
pass
def __init__(self):
pass
class ClassWithInitAndVarsAndDocstringWithInner:
"""Test class"""
cls_var = 100
class Inner:
pass
def __init__(self):
pass
class ClassWithDecoInitWithInner:
class Inner:
pass
@deco
def __init__(self):
pass
class ClassWithDecoInitAndVarsWithInner:
cls_var = 100
class Inner:
pass
@deco
def __init__(self):
pass
class ClassWithDecoInitAndVarsAndDocstringWithInner:
"""Test class"""
cls_var = 100
class Inner:
pass
@deco
def __init__(self):
pass
class ClassWithDecoInitAndVarsAndDocstringWithInner2:
"""Test class"""
class Inner:
pass
cls_var = 100
@deco
def __init__(self):
pass
```
## Black Output
```py
class ClassSimplest:
pass
class ClassWithSingleField:
a = 1
class ClassWithJustTheDocstring:
"""Just a docstring."""
class ClassWithInit:
def __init__(self):
pass
class ClassWithTheDocstringAndInit:
"""Just a docstring."""
def __init__(self):
pass
class ClassWithInitAndVars:
cls_var = 100
def __init__(self):
pass
class ClassWithInitAndVarsAndDocstring:
"""Test class"""
cls_var = 100
def __init__(self):
pass
class ClassWithDecoInit:
@deco
def __init__(self):
pass
class ClassWithDecoInitAndVars:
cls_var = 100
@deco
def __init__(self):
pass
class ClassWithDecoInitAndVarsAndDocstring:
"""Test class"""
cls_var = 100
@deco
def __init__(self):
pass
class ClassSimplestWithInner:
class Inner:
pass
class ClassSimplestWithInnerWithDocstring:
class Inner:
"""Just a docstring."""
def __init__(self):
pass
class ClassWithSingleFieldWithInner:
a = 1
class Inner:
pass
class ClassWithJustTheDocstringWithInner:
"""Just a docstring."""
class Inner:
pass
class ClassWithInitWithInner:
class Inner:
pass
def __init__(self):
pass
class ClassWithInitAndVarsWithInner:
cls_var = 100
class Inner:
pass
def __init__(self):
pass
class ClassWithInitAndVarsAndDocstringWithInner:
"""Test class"""
cls_var = 100
class Inner:
pass
def __init__(self):
pass
class ClassWithDecoInitWithInner:
class Inner:
pass
@deco
def __init__(self):
pass
class ClassWithDecoInitAndVarsWithInner:
cls_var = 100
class Inner:
pass
@deco
def __init__(self):
pass
class ClassWithDecoInitAndVarsAndDocstringWithInner:
"""Test class"""
cls_var = 100
class Inner:
pass
@deco
def __init__(self):
pass
class ClassWithDecoInitAndVarsAndDocstringWithInner2:
"""Test class"""
class Inner:
pass
cls_var = 100
@deco
def __init__(self):
pass
```

View file

@ -77,7 +77,6 @@ if True:
ec2client.get_waiter("instance_stopped").wait( ec2client.get_waiter("instance_stopped").wait(
InstanceIds=[instance.id], WaiterConfig={"Delay": 5,}, InstanceIds=[instance.id], WaiterConfig={"Delay": 5,},
) )
``` ```
## Black Differences ## Black Differences
@ -107,14 +106,6 @@ if True:
}, },
) )
ec2client.get_waiter("instance_stopped").wait( ec2client.get_waiter("instance_stopped").wait(
@@ -96,4 +96,4 @@
WaiterConfig={
"Delay": 5,
},
- )
\ No newline at end of file
+ )
``` ```
## Ruff Output ## Ruff Output
@ -219,7 +210,6 @@ if True:
"Delay": 5, "Delay": 5,
}, },
) )
``` ```
## Black Output ## Black Output

View file

@ -15,7 +15,6 @@ def bobtwo(): \
\ \
# some comment here # some comment here
pass pass
``` ```
## Black Differences ## Black Differences
@ -31,12 +30,9 @@ def bobtwo(): \
-def bobtwo(): # some comment here -def bobtwo(): # some comment here
- pass
\ No newline at end of file
+def bobtwo(): +def bobtwo():
+ # some comment here + # some comment here
+ pass pass
``` ```
## Ruff Output ## Ruff Output
@ -50,7 +46,6 @@ def bob():
def bobtwo(): def bobtwo():
# some comment here # some comment here
pass pass
``` ```
## Black Output ## Black Output

View file

@ -171,7 +171,6 @@ instruction()#comment with bad spacing
# END COMMENTS # END COMMENTS
# MORE END COMMENTS # MORE END COMMENTS
``` ```
## Black Differences ## Black Differences
@ -361,10 +360,7 @@ instruction()#comment with bad spacing
+instruction() #comment with bad spacing +instruction() #comment with bad spacing
# END COMMENTS # END COMMENTS
-# MORE END COMMENTS # MORE END COMMENTS
\ No newline at end of file
+# MORE END COMMENTS
``` ```
## Ruff Output ## Ruff Output
@ -550,7 +546,6 @@ instruction() #comment with bad spacing
# END COMMENTS # END COMMENTS
# MORE END COMMENTS # MORE END COMMENTS
``` ```
## Black Output ## Black Output

View file

@ -100,7 +100,6 @@ def foo3(list_a, list_b):
) )
.filter(User.xyz.is_(None)) .filter(User.xyz.is_(None))
) )
``` ```
## Black Differences ## Black Differences
@ -240,12 +239,10 @@ def foo3(list_a, list_b):
- ) - )
- .filter(User.xyz.is_(None)) - .filter(User.xyz.is_(None))
- ) - )
\ No newline at end of file
+ return # Standlone comment but weirdly placed. + return # Standlone comment but weirdly placed.
+ User.query.filter(User.foo == "bar").filter( + User.query.filter(User.foo == "bar").filter(
+ db.or_(User.field_a.astext.in_(list_a), User.field_b.astext.in_(list_b)) + db.or_(User.field_a.astext.in_(list_a), User.field_b.astext.in_(list_b))
+ ).filter(User.xyz.is_(None)) + ).filter(User.xyz.is_(None))
``` ```
## Ruff Output ## Ruff Output
@ -345,7 +342,6 @@ def foo3(list_a, list_b):
User.query.filter(User.foo == "bar").filter( User.query.filter(User.foo == "bar").filter(
db.or_(User.field_a.astext.in_(list_a), User.field_b.astext.in_(list_b)) db.or_(User.field_a.astext.in_(list_a), User.field_b.astext.in_(list_b))
).filter(User.xyz.is_(None)) ).filter(User.xyz.is_(None))
``` ```
## Black Output ## Black Output

View file

@ -124,7 +124,6 @@ call_to_some_function_asdf(
) )
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]
``` ```
## Black Differences ## Black Differences
@ -289,8 +288,6 @@ aaaaaaaaaaaaa, bbbbbbbbb = map(list, map(itertools.chain.from_iterable, zip(*ite
) )
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]
\ No newline at end of file
``` ```
## Ruff Output ## Ruff Output

View file

@ -145,7 +145,6 @@ def foo():
# A standalone comment # A standalone comment
def bar(): def bar():
pass pass
``` ```
## Black Differences ## Black Differences
@ -280,11 +279,8 @@ def bar():
@decorator1 @decorator1
-# A standalone comment -# A standalone comment
def bar(): def bar():
- pass
\ No newline at end of file
+ # A standalone comment + # A standalone comment
+ pass pass
``` ```
## Ruff Output ## Ruff Output
@ -457,7 +453,6 @@ def foo():
def bar(): def bar():
# A standalone comment # A standalone comment
pass pass
``` ```
## Black Output ## Black Output

View file

@ -187,7 +187,6 @@ class C:
key9: value9 key9: value9
} }
) )
``` ```
## Black Differences ## Black Differences
@ -473,14 +472,6 @@ class C:
assert ( assert (
expectedexpectedexpectedexpectedexpectedexpectedexpectedexpectedexpect expectedexpectedexpectedexpectedexpectedexpectedexpectedexpectedexpect
@@ -178,4 +201,4 @@
key8: value8,
key9: value9,
}
- )
\ No newline at end of file
+ )
``` ```
## Ruff Output ## Ruff Output
@ -690,7 +681,6 @@ class C:
key9: value9, key9: value9,
} }
) )
``` ```
## Black Output ## Black Output

View file

@ -187,7 +187,6 @@ class C:
key9: value9, key9: value9,
} }
) )
``` ```
## Black Differences ## Black Differences
@ -473,14 +472,6 @@ class C:
assert ( assert (
expectedexpectedexpectedexpectedexpectedexpectedexpectedexpectedexpect expectedexpectedexpectedexpectedexpectedexpectedexpectedexpectedexpect
@@ -178,4 +201,4 @@
key8: value8,
key9: value9,
}
- )
\ No newline at end of file
+ )
``` ```
## Ruff Output ## Ruff Output
@ -690,7 +681,6 @@ class C:
key9: value9, key9: value9,
} }
) )
``` ```
## Black Output ## Black Output

View file

@ -1,50 +0,0 @@
---
source: crates/ruff_python_formatter/src/lib.rs
expression: snapshot
input_file: crates/ruff_python_formatter/resources/test/fixtures/black/simple_cases/docstring_no_extra_empty_line_before_eof.py
---
## Input
```py
# Make sure when the file ends with class's docstring,
# It doesn't add extra blank lines.
class ClassWithDocstring:
"""A docstring."""
```
## Black Differences
```diff
--- Black
+++ Ruff
@@ -1,4 +1,4 @@
# Make sure when the file ends with class's docstring,
# It doesn't add extra blank lines.
class ClassWithDocstring:
- """A docstring."""
\ No newline at end of file
+ """A docstring."""
```
## Ruff Output
```py
# Make sure when the file ends with class's docstring,
# It doesn't add extra blank lines.
class ClassWithDocstring:
"""A docstring."""
```
## Black Output
```py
# Make sure when the file ends with class's docstring,
# It doesn't add extra blank lines.
class ClassWithDocstring:
"""A docstring."""
```

View file

@ -98,7 +98,6 @@ def g():
syms.argument, syms.argument,
}: }:
return NO return NO
``` ```
## Black Differences ## Black Differences
@ -119,7 +118,7 @@ def g():
t = leaf.type t = leaf.type
p = leaf.parent # trailing comment p = leaf.parent # trailing comment
@@ -25,23 +25,30 @@ @@ -25,35 +25,41 @@
return NO return NO
if prevp.type == token.EQUAL: if prevp.type == token.EQUAL:
@ -165,11 +164,11 @@ def g():
return NO return NO
@@ -49,11 +56,10 @@ ###############################################################################
# SECTION BECAUSE SECTIONS # SECTION BECAUSE SECTIONS
############################################################################### ###############################################################################
- -
def g(): def g():
- NO = "" - NO = ""
- SPACE = " " - SPACE = " "
@ -200,8 +199,6 @@ def g():
- syms.arglist, - syms.arglist,
- syms.argument, - syms.argument,
- }: - }:
- return NO
\ No newline at end of file
+ if ( + if (
+ prevp.parent + prevp.parent
+ and prevp.parent.type + and prevp.parent.type
@ -213,8 +210,7 @@ def g():
+ syms.argument, + syms.argument,
+ } + }
+ ): + ):
+ return NO return NO
``` ```
## Ruff Output ## Ruff Output
@ -319,7 +315,6 @@ def g():
} }
): ):
return NO return NO
``` ```
## Black Output ## Black Output

View file

@ -260,7 +260,6 @@ bbbb >> bbbb * bbbb
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ^bbbb.a & aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa^aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ^bbbb.a & aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa^aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
last_call() last_call()
# standalone comment at ENDMARKER # standalone comment at ENDMARKER
``` ```
## Black Differences ## Black Differences
@ -308,7 +307,7 @@ last_call()
() ()
(1,) (1,)
(1, 2) (1, 2)
@@ -88,33 +90,34 @@ @@ -88,32 +90,33 @@
] ]
{i for i in (1, 2, 3)} {i for i in (1, 2, 3)}
{(i**2) for i in (1, 2, 3)} {(i**2) for i in (1, 2, 3)}
@ -346,12 +345,10 @@ last_call()
arg, arg,
another, another,
- kwarg="hey", - kwarg="hey",
- **kwargs
+ kwarg='hey', + kwarg='hey',
+ **kwargs, **kwargs,
) # note: no trailing comma pre-3.6 ) # note: no trailing comma pre-3.6
call(*gidgets[:2]) call(*gidgets[:2])
call(a, *gidgets[:2])
@@ -122,8 +125,8 @@ @@ -122,8 +125,8 @@
call(b, **self.screen_kwargs) call(b, **self.screen_kwargs)
lukasz.langa.pl lukasz.langa.pl
@ -370,19 +367,19 @@ last_call()
-xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = classmethod( # type: ignore -xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = classmethod( # type: ignore
- sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__) - sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__)
+xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = ( +xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = (
+ classmethod(sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__)) # type: ignore
+)
+xxxx_xxx_xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = (
+ classmethod(sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__)) # type: ignore + classmethod(sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__)) # type: ignore
) )
-xxxx_xxx_xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = classmethod( # type: ignore -xxxx_xxx_xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = classmethod( # type: ignore
- sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__) - sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__)
+xxxx_xxx_xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = ( +xxxx_xxx_xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = (
+ classmethod(sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__)) + classmethod(sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__)) # type: ignore
) )
-xxxx_xxx_xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = classmethod( -xxxx_xxx_xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = classmethod(
- sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__) - sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__)
-) # type: ignore -) # type: ignore
+xxxx_xxx_xxxx_xxxxx_xxxx_xxx: Callable[..., List[SomeClass]] = (
+ classmethod(sync(async_xxxx_xxx_xxxx_xxxxx_xxxx_xxx.__func__))
+)
slice[0] slice[0]
slice[0:1] slice[0:1]
slice[0:1:2] slice[0:1:2]
@ -436,10 +433,18 @@ last_call()
g = 1, *"ten" g = 1, *"ten"
-what_is_up_with_those_new_coord_names = (coord_names + set(vars_to_create)) + set( -what_is_up_with_those_new_coord_names = (coord_names + set(vars_to_create)) + set(
- vars_to_remove - vars_to_remove
-) +what_is_up_with_those_new_coord_names = (
+ (coord_names
+ + set(vars_to_create))
+ + set(vars_to_remove)
)
-what_is_up_with_those_new_coord_names = (coord_names | set(vars_to_create)) - set( -what_is_up_with_those_new_coord_names = (coord_names | set(vars_to_create)) - set(
- vars_to_remove - vars_to_remove
-) +what_is_up_with_those_new_coord_names = (
+ (coord_names
+ | set(vars_to_create))
+ - set(vars_to_remove)
)
-result = ( -result = (
- session.query(models.Customer.id) - session.query(models.Customer.id)
- .filter( - .filter(
@ -447,11 +452,7 @@ last_call()
- ) - )
- .order_by(models.Customer.id.asc()) - .order_by(models.Customer.id.asc())
- .all() - .all()
+what_is_up_with_those_new_coord_names = ( -)
+ (coord_names
+ + set(vars_to_create))
+ + set(vars_to_remove)
)
-result = ( -result = (
- session.query(models.Customer.id) - session.query(models.Customer.id)
- .filter( - .filter(
@ -461,11 +462,7 @@ last_call()
- models.Customer.id.asc(), - models.Customer.id.asc(),
- ) - )
- .all() - .all()
+what_is_up_with_those_new_coord_names = ( -)
+ (coord_names
+ | set(vars_to_create))
+ - set(vars_to_remove)
)
+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,
@ -533,15 +530,6 @@ last_call()
^ aaaaaaaaaaaaaaaa.i ^ aaaaaaaaaaaaaaaa.i
<< aaaaaaaaaaaaaaaa.k << aaaaaaaaaaaaaaaa.k
>> aaaaaaaaaaaaaaaa.l**aaaaaaaaaaaaaaaa.m // aaaaaaaaaaaaaaaa.n >> aaaaaaaaaaaaaaaa.l**aaaaaaaaaaaaaaaa.m // aaaaaaaaaaaaaaaa.n
@@ -366,5 +371,4 @@
^ bbbb.a & aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
^ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
)
-last_call()
-# standalone comment at ENDMARKER
\ No newline at end of file
+last_call()# standalone comment at ENDMARKER
``` ```
## Ruff Output ## Ruff Output
@ -920,8 +908,8 @@ bbbb >> bbbb * bbbb
^ bbbb.a & aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ^ bbbb.a & aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
^ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ^ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
) )
last_call()# standalone comment at ENDMARKER last_call()
# standalone comment at ENDMARKER
``` ```
## Black Output ## Black Output
@ -1043,7 +1031,7 @@ call(
arg, arg,
another, another,
kwarg="hey", kwarg="hey",
**kwargs **kwargs,
) # note: no trailing comma pre-3.6 ) # note: no trailing comma pre-3.6
call(*gidgets[:2]) call(*gidgets[:2])
call(a, *gidgets[:2]) call(a, *gidgets[:2])

View file

@ -46,7 +46,6 @@ def test_calculate_fades():
] ]
# fmt: on # fmt: on
``` ```
## Black Differences ## Black Differences
@ -63,9 +62,9 @@ def test_calculate_fades():
# Test data: # Test data:
# Position, Volume, State, TmSt/TmEx/None, [call, [arg1...]] # Position, Volume, State, TmSt/TmEx/None, [call, [arg1...]]
-
-@pytest.mark.parametrize('test', [
-@pytest.mark.parametrize('test', [
-
- # Test don't manage the volume - # Test don't manage the volume
+@pytest.mark.parametrize( +@pytest.mark.parametrize(
+ 'test', + 'test',
@ -106,10 +105,7 @@ def test_calculate_fades():
+ (None, 4, 0, 0, 10, 0, 0, 6, 10), + (None, 4, 0, 0, 10, 0, 0, 6, 10),
] ]
-# fmt: on # fmt: on
\ No newline at end of file
+# fmt: on
``` ```
## Ruff Output ## Ruff Output
@ -159,7 +155,6 @@ def test_calculate_fades():
] ]
# fmt: on # fmt: on
``` ```
## Black Output ## Black Output

View file

@ -23,7 +23,6 @@ x = [
x = [ x = [
1, 2, 3, 4 1, 2, 3, 4
] ]
``` ```
## Black Differences ## Black Differences
@ -54,7 +53,6 @@ x = [
] ]
# fmt: on # fmt: on
``` ```
## Ruff Output ## Ruff Output

View file

@ -19,7 +19,6 @@ def f(): pass
3, 4, 3, 4,
]) ])
def f(): pass def f(): pass
``` ```
## Black Differences ## Black Differences
@ -47,14 +46,6 @@ def f(): pass
pass pass
@@ -17,4 +21,4 @@
]
)
def f():
- pass
\ No newline at end of file
+ pass
``` ```
## Ruff Output ## Ruff Output
@ -84,7 +75,6 @@ def f():
) )
def f(): def f():
pass pass
``` ```
## Black Output ## Black Output

View file

@ -90,7 +90,6 @@ if x:
elif unformatted: elif unformatted:
# fmt: on # fmt: on
will_be_formatted () will_be_formatted ()
``` ```
## Black Differences ## Black Differences
@ -188,10 +187,7 @@ elif unformatted:
-elif unformatted: -elif unformatted:
+elif unformatted: +elif unformatted:
# fmt: on # fmt: on
- will_be_formatted() will_be_formatted()
\ No newline at end of file
+ will_be_formatted()
``` ```
## Ruff Output ## Ruff Output
@ -280,7 +276,6 @@ if x:
elif unformatted: elif unformatted:
# fmt: on # fmt: on
will_be_formatted() will_be_formatted()
``` ```
## Black Output ## Black Output

View file

@ -9,7 +9,6 @@ input_file: crates/ruff_python_formatter/resources/test/fixtures/black/simple_ca
l1 = ["This list should be broken up", "into multiple lines", "because it is way too long"] l1 = ["This list should be broken up", "into multiple lines", "because it is way too long"]
l2 = ["But this list shouldn't", "even though it also has", "way too many characters in it"] # fmt: skip l2 = ["But this list shouldn't", "even though it also has", "way too many characters in it"] # fmt: skip
l3 = ["I have", "trailing comma", "so I should be braked",] l3 = ["I have", "trailing comma", "so I should be braked",]
``` ```
## Black Differences ## Black Differences
@ -30,7 +29,6 @@ l3 = ["I have", "trailing comma", "so I should be braked",]
l3 = [ l3 = [
"I have", "I have",
"trailing comma", "trailing comma",
``` ```
## Ruff Output ## Ruff Output

View file

@ -13,7 +13,6 @@ d = 6 # fmt: skip
e = 5 e = 5
# fmt: on # fmt: on
f = ["This is a very long line that should be formatted into a clearer line ", "by rearranging."] f = ["This is a very long line that should be formatted into a clearer line ", "by rearranging."]
``` ```
## Black Differences ## Black Differences
@ -31,7 +30,6 @@ f = ["This is a very long line that should be formatted into a clearer line ", "
e = 5 e = 5
# fmt: on # fmt: on
f = [ f = [
``` ```
## Ruff Output ## Ruff Output

View file

@ -15,7 +15,6 @@ if (
print("I'm good!") print("I'm good!")
else: else:
print("I'm bad") print("I'm bad")
``` ```
## Black Differences ## Black Differences
@ -33,10 +32,7 @@ else:
+if a == 3 and b != 9 and c is not None: # fmt: skip +if a == 3 and b != 9 and c is not None: # fmt: skip
print("I'm good!") print("I'm good!")
else: else:
- print("I'm bad") print("I'm bad")
\ No newline at end of file
+ print("I'm bad")
``` ```
## Ruff Output ## Ruff Output
@ -47,7 +43,6 @@ if a == 3 and b != 9 and c is not None: # fmt: skip
print("I'm good!") print("I'm good!")
else: else:
print("I'm bad") print("I'm bad")
``` ```
## Black Output ## Black Output

View file

@ -11,7 +11,6 @@ class A:
for line in range(10): for line in range(10):
if True: if True:
pass # fmt: skip pass # fmt: skip
``` ```
## Black Differences ## Black Differences
@ -24,9 +23,7 @@ class A:
for line in range(10): for line in range(10):
if True: if True:
- pass # fmt: skip - pass # fmt: skip
\ No newline at end of file
+ pass + pass
``` ```
## Ruff Output ## Ruff Output
@ -37,7 +34,6 @@ class A:
for line in range(10): for line in range(10):
if True: if True:
pass pass
``` ```
## Black Output ## Black Output

View file

@ -10,7 +10,6 @@ a = "this is some code"
b = 5 #fmt:skip b = 5 #fmt:skip
c = 9 #fmt: skip c = 9 #fmt: skip
d = "thisisasuperlongstringthisisasuperlongstringthisisasuperlongstringthisisasuperlongstring" #fmt:skip d = "thisisasuperlongstringthisisasuperlongstringthisisasuperlongstringthisisasuperlongstring" #fmt:skip
``` ```
## Black Differences ## Black Differences
@ -23,12 +22,9 @@ d = "thisisasuperlongstringthisisasuperlongstringthisisasuperlongstringthisisasu
-b = 5 # fmt:skip -b = 5 # fmt:skip
-c = 9 # fmt: skip -c = 9 # fmt: skip
-d = "thisisasuperlongstringthisisasuperlongstringthisisasuperlongstringthisisasuperlongstring" # fmt:skip -d = "thisisasuperlongstringthisisasuperlongstringthisisasuperlongstringthisisasuperlongstring" # fmt:skip
\ No newline at end of file
+b = 5 #fmt:skip +b = 5 #fmt:skip
+c = 9 #fmt: skip +c = 9 #fmt: skip
+d = "thisisasuperlongstringthisisasuperlongstringthisisasuperlongstringthisisasuperlongstring" #fmt:skip +d = "thisisasuperlongstringthisisasuperlongstringthisisasuperlongstringthisisasuperlongstring" #fmt:skip
\ No newline at end of file
``` ```
## Ruff Output ## Ruff Output

View file

@ -9,7 +9,6 @@ input_file: crates/ruff_python_formatter/resources/test/fixtures/black/simple_ca
a, b = 1, 2 a, b = 1, 2
c = 6 # fmt: skip c = 6 # fmt: skip
d = 5 d = 5
``` ```
## Black Differences ## Black Differences
@ -22,8 +21,6 @@ d = 5
-c = 6 # fmt: skip -c = 6 # fmt: skip
+c = 6 # fmt: skip +c = 6 # fmt: skip
d = 5 d = 5
\ No newline at end of file
``` ```
## Ruff Output ## Ruff Output

View file

@ -15,7 +15,6 @@ f"{f'''{'nested'} inner'''} outer"
f"\"{f'{nested} inner'}\" outer" f"\"{f'{nested} inner'}\" outer"
f"space between opening braces: { {a for a in (1, 2, 3)}}" f"space between opening braces: { {a for a in (1, 2, 3)}}"
f'Hello \'{tricky + "example"}\'' f'Hello \'{tricky + "example"}\''
``` ```
## Black Differences ## Black Differences
@ -31,7 +30,6 @@ f'Hello \'{tricky + "example"}\''
f"some f-string with {a} {few():.2f} {formatted.values!r}" f"some f-string with {a} {few():.2f} {formatted.values!r}"
f'some f-string with {a} {few(""):.2f} {formatted.values!r}' f'some f-string with {a} {few(""):.2f} {formatted.values!r}'
f"{f'''{'nested'} inner'''} outer" f"{f'''{'nested'} inner'''} outer"
``` ```
## Ruff Output ## Ruff Output

View file

@ -1,223 +0,0 @@
---
source: crates/ruff_python_formatter/src/lib.rs
expression: snapshot
input_file: crates/ruff_python_formatter/resources/test/fixtures/black/simple_cases/function2.py
---
## Input
```py
def f(
a,
**kwargs,
) -> A:
with cache_dir():
if something:
result = (
CliRunner().invoke(black.main, [str(src1), str(src2), "--diff", "--check"])
)
limited.append(-limited.pop()) # negate top
return A(
very_long_argument_name1=very_long_value_for_the_argument,
very_long_argument_name2=-very.long.value.for_the_argument,
**kwargs,
)
def g():
"Docstring."
def inner():
pass
print("Inner defs should breathe a little.")
def h():
def inner():
pass
print("Inner defs should breathe a little.")
if os.name == "posix":
import termios
def i_should_be_followed_by_only_one_newline():
pass
elif os.name == "nt":
try:
import msvcrt
def i_should_be_followed_by_only_one_newline():
pass
except ImportError:
def i_should_be_followed_by_only_one_newline():
pass
elif False:
class IHopeYouAreHavingALovelyDay:
def __call__(self):
print("i_should_be_followed_by_only_one_newline")
else:
def foo():
pass
with hmm_but_this_should_get_two_preceding_newlines():
pass
```
## Black Differences
```diff
--- Black
+++ Ruff
@@ -63,4 +63,4 @@
with hmm_but_this_should_get_two_preceding_newlines():
- pass
\ No newline at end of file
+ pass
```
## Ruff Output
```py
def f(
a,
**kwargs,
) -> A:
with cache_dir():
if something:
result = CliRunner().invoke(
black.main,
[str(src1), str(src2), "--diff", "--check"],
)
limited.append(-limited.pop()) # negate top
return A(
very_long_argument_name1=very_long_value_for_the_argument,
very_long_argument_name2=-very.long.value.for_the_argument,
**kwargs,
)
def g():
"Docstring."
def inner():
pass
print("Inner defs should breathe a little.")
def h():
def inner():
pass
print("Inner defs should breathe a little.")
if os.name == "posix":
import termios
def i_should_be_followed_by_only_one_newline():
pass
elif os.name == "nt":
try:
import msvcrt
def i_should_be_followed_by_only_one_newline():
pass
except ImportError:
def i_should_be_followed_by_only_one_newline():
pass
elif False:
class IHopeYouAreHavingALovelyDay:
def __call__(self):
print("i_should_be_followed_by_only_one_newline")
else:
def foo():
pass
with hmm_but_this_should_get_two_preceding_newlines():
pass
```
## Black Output
```py
def f(
a,
**kwargs,
) -> A:
with cache_dir():
if something:
result = CliRunner().invoke(
black.main,
[str(src1), str(src2), "--diff", "--check"],
)
limited.append(-limited.pop()) # negate top
return A(
very_long_argument_name1=very_long_value_for_the_argument,
very_long_argument_name2=-very.long.value.for_the_argument,
**kwargs,
)
def g():
"Docstring."
def inner():
pass
print("Inner defs should breathe a little.")
def h():
def inner():
pass
print("Inner defs should breathe a little.")
if os.name == "posix":
import termios
def i_should_be_followed_by_only_one_newline():
pass
elif os.name == "nt":
try:
import msvcrt
def i_should_be_followed_by_only_one_newline():
pass
except ImportError:
def i_should_be_followed_by_only_one_newline():
pass
elif False:
class IHopeYouAreHavingALovelyDay:
def __call__(self):
print("i_should_be_followed_by_only_one_newline")
else:
def foo():
pass
with hmm_but_this_should_get_two_preceding_newlines():
pass
```

View file

@ -101,7 +101,6 @@ def f(
) )
) )
def __await__(): return (yield) def __await__(): return (yield)
``` ```
## Black Differences ## Black Differences
@ -184,9 +183,7 @@ def __await__(): return (yield)
def __await__(): def __await__():
- return (yield) - return (yield)
\ No newline at end of file
+ return yield + return yield
``` ```
## Ruff Output ## Ruff Output
@ -334,7 +331,6 @@ def f(
def __await__(): def __await__():
return yield return yield
``` ```
## Black Output ## Black Output

View file

@ -67,7 +67,6 @@ some_module.some_function(
some_module.some_function( some_module.some_function(
argument1, (one, two,), argument4, argument5, argument6 argument1, (one, two,), argument4, argument5, argument6
) )
``` ```
## Black Differences ## Black Differences
@ -176,7 +175,6 @@ some_module.some_function(
) )
# Inner trailing comma causes outer to explode # Inner trailing comma causes outer to explode
``` ```
## Ruff Output ## Ruff Output

View file

@ -87,7 +87,6 @@ async def main():
async def main(): async def main():
await (yield) await (yield)
``` ```
## Black Differences ## Black Differences
@ -183,7 +182,7 @@ async def main():
# Keep brackets around non power operations and nested awaits # Keep brackets around non power operations and nested awaits
@@ -82,12 +86,12 @@ @@ -82,11 +86,11 @@
async def main(): async def main():
@ -197,10 +196,6 @@ async def main():
async def main(): async def main():
- await (yield)
\ No newline at end of file
+ await (yield)
``` ```
## Ruff Output ## Ruff Output
@ -303,7 +298,6 @@ async def main():
async def main(): async def main():
await (yield) await (yield)
``` ```
## Black Output ## Black Output

View file

@ -41,7 +41,6 @@ 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:
raise err raise err
``` ```
## Black Differences ## Black Differences
@ -69,14 +68,6 @@ except (some.really.really.really.looooooooooooooooooooooooooooooooong.module.ov
raise err raise err
try: try:
@@ -39,4 +37,4 @@
some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error,
some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error,
) as err:
- raise err
\ No newline at end of file
+ raise err
``` ```
## Ruff Output ## Ruff Output
@ -122,7 +113,6 @@ except (
some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error, some.really.really.really.looooooooooooooooooooooooooooooooong.module.over89.chars.Error,
) as err: ) as err:
raise err raise err
``` ```
## Black Output ## Black Output

View file

@ -25,7 +25,6 @@ for (k, v) in dfkasdjfldsjflkdsjflkdsjfdslkfjldsjfgkjdshgkljjdsfldgkhsdofudsfuds
# Test deeply nested brackets # Test deeply nested brackets
for (((((k, v))))) in d.items(): for (((((k, v))))) in d.items():
print(k, v) print(k, v)
``` ```
## Black Differences ## Black Differences
@ -42,7 +41,7 @@ for (((((k, v))))) in d.items():
if hasattr(module, "_verify_python3_env"): if hasattr(module, "_verify_python3_env"):
module._verify_python3_env = lambda: None module._verify_python3_env = lambda: None
@@ -17,11 +17,9 @@ @@ -17,9 +17,7 @@
for ( for (
k, k,
v, v,
@ -53,11 +52,6 @@ for (((((k, v))))) in d.items():
print(k, v) print(k, v)
# Test deeply nested brackets # Test deeply nested brackets
for k, v in d.items():
- print(k, v)
\ No newline at end of file
+ print(k, v)
``` ```
## Ruff Output ## Ruff Output
@ -88,7 +82,6 @@ for (
# Test deeply nested brackets # Test deeply nested brackets
for k, v in d.items(): for k, v in d.items():
print(k, v) print(k, v)
``` ```
## Black Output ## Black Output

View file

@ -1,302 +0,0 @@
---
source: crates/ruff_python_formatter/src/lib.rs
expression: snapshot
input_file: crates/ruff_python_formatter/resources/test/fixtures/black/simple_cases/remove_newline_after_code_block_open.py
---
## Input
```py
import random
def foo1():
print("The newline above me should be deleted!")
def foo2():
print("All the newlines above me should be deleted!")
def foo3():
print("No newline above me!")
print("There is a newline above me, and that's OK!")
def foo4():
# There is a comment here
print("The newline above me should not be deleted!")
class Foo:
def bar(self):
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):
print(f"{i}) The lines above me should 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:
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!")
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 newline above me should be deleted!")
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:
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/output_file.txt", mode="w") as write_file:
write_file.writelines(read_file.readlines())
```
## Black Differences
```diff
--- Black
+++ Ruff
@@ -75,4 +75,4 @@
with open("/path/to/file.txt", mode="r") as read_file:
with open("/path/to/output_file.txt", mode="w") as write_file:
- write_file.writelines(read_file.readlines())
\ No newline at end of file
+ write_file.writelines(read_file.readlines())
```
## Ruff Output
```py
import random
def foo1():
print("The newline above me should be deleted!")
def foo2():
print("All the newlines above me should be deleted!")
def foo3():
print("No newline above me!")
print("There is a newline above me, and that's OK!")
def foo4():
# There is a comment here
print("The newline above me should not be deleted!")
class Foo:
def bar(self):
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):
print(f"{i}) The lines above me should 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:
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!")
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 newline above me should be deleted!")
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:
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/output_file.txt", mode="w") as write_file:
write_file.writelines(read_file.readlines())
```
## Black Output
```py
import random
def foo1():
print("The newline above me should be deleted!")
def foo2():
print("All the newlines above me should be deleted!")
def foo3():
print("No newline above me!")
print("There is a newline above me, and that's OK!")
def foo4():
# There is a comment here
print("The newline above me should not be deleted!")
class Foo:
def bar(self):
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):
print(f"{i}) The lines above me should 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:
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!")
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 newline above me should be deleted!")
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:
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/output_file.txt", mode="w") as write_file:
write_file.writelines(read_file.readlines())
```

View file

@ -61,7 +61,6 @@ def example7():
def example8(): def example8():
return (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((None))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) return (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((None)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
``` ```
## Black Differences ## Black Differences
@ -108,14 +107,6 @@ def example8():
def example4(): def example4():
@@ -82,4 +74,4 @@
def example8():
- return None
\ No newline at end of file
+ return None
``` ```
## Ruff Output ## Ruff Output
@ -198,7 +189,6 @@ def example7():
def example8(): def example8():
return None return None
``` ```
## Black Output ## Black Output

View file

@ -94,7 +94,6 @@ def foo() -> tuple[loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
# Magic trailing comma example # Magic trailing comma example
def foo() -> tuple[int, int, int,]: def foo() -> tuple[int, int, int,]:
return 2 return 2
``` ```
## Black Differences ## Black Differences
@ -237,15 +236,12 @@ def foo() -> tuple[int, int, int,]:
- int, - int,
- ] - ]
-): -):
- return 2
\ No newline at end of file
+def foo() -> tuple[ +def foo() -> tuple[
+ int, + int,
+ int, + int,
+ int, + int,
+]: +]:
+ return 2 return 2
``` ```
## Ruff Output ## Ruff Output
@ -366,7 +362,6 @@ def foo() -> tuple[
int, int,
]: ]:
return 2 return 2
``` ```
## Black Output ## Black Output

View file

@ -53,7 +53,6 @@ func(
argument5, argument5,
argument6, argument6,
) )
``` ```
## Black Differences ## Black Differences
@ -123,7 +122,6 @@ func(
+) = func1(arg1) and func2(arg2) +) = func1(arg1) and func2(arg2)
-func(argument1, (one, two), argument4, argument5, argument6) -func(argument1, (one, two), argument4, argument5, argument6)
\ No newline at end of file
+func( +func(
+ argument1, + argument1,
+ ( + (
@ -134,8 +132,6 @@ func(
+ argument5, + argument5,
+ argument6, + argument6,
+) +)
\ No newline at end of file
``` ```
## Ruff Output ## Ruff Output

View file

@ -26,7 +26,6 @@ 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
""" """
``` ```
## Black Differences ## Black Differences
@ -53,14 +52,6 @@ def docstring_multiline():
def docstring_singleline(): def docstring_singleline():
@@ -17,4 +17,4 @@
def docstring_multiline():
R"""
clear out all of the issues opened in that time :p
- """
\ No newline at end of file
+ """
``` ```
## Ruff Output ## Ruff Output
@ -86,7 +77,6 @@ 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
""" """
``` ```
## Black Output ## Black Output

View file

@ -35,7 +35,6 @@ 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"}
) )
``` ```
## Black Differences ## Black Differences
@ -115,7 +114,6 @@ assert (
- 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"}
\ No newline at end of file
+assert ( +assert (
+ a_function( + a_function(
+ very_long_arguments_that_surpass_the_limit, + very_long_arguments_that_surpass_the_limit,
@ -126,8 +124,6 @@ assert (
+ "b": "but only by a little bit", + "b": "but only by a little bit",
+ } + }
+) +)
\ No newline at end of file
``` ```
## Ruff Output ## Ruff Output

View file

@ -31,7 +31,6 @@ class A:
3, 3,
) < self.connection.mysql_version < (10, 5, 2): ) < self.connection.mysql_version < (10, 5, 2):
pass pass
``` ```
## Black Differences ## Black Differences
@ -76,8 +75,6 @@ class A:
- 4, - 4,
- 3, - 3,
- ) < self.connection.mysql_version < (10, 5, 2): - ) < self.connection.mysql_version < (10, 5, 2):
- pass
\ No newline at end of file
+ if ( + if (
+ self.connection.mysql_is_mariadb + self.connection.mysql_is_mariadb
+ and ( + and (
@ -88,8 +85,7 @@ class A:
+ < self.connection.mysql_version + < self.connection.mysql_version
+ < (10, 5, 2) + < (10, 5, 2)
+ ): + ):
+ pass pass
``` ```
## Ruff Output ## Ruff Output
@ -134,7 +130,6 @@ class A:
< (10, 5, 2) < (10, 5, 2)
): ):
pass pass
``` ```
## Black Output ## Black Output

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