Add empty lines before nested functions and classes (#6206)

## Summary

This PR ensures that if a function or class is the first statement in a
nested suite that _isn't_ a function or class body, we insert a leading
newline.

For example, given:

```python
def f():
    if True:

        def register_type():
            pass
```

We _want_ to preserve the newline, whereas today, we remove it.

Note that this only applies when the function or class doesn't have any
leading comments.

Closes https://github.com/astral-sh/ruff/issues/6066.
This commit is contained in:
Charlie Marsh 2023-08-01 11:30:59 -04:00 committed by GitHub
parent b68f76f0d9
commit 928ab63a64
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 64 additions and 43 deletions

View file

@ -73,22 +73,13 @@ with hmm_but_this_should_get_two_preceding_newlines():
elif os.name == "nt":
try:
import msvcrt
@@ -45,21 +44,16 @@
pass
except ImportError:
-
def i_should_be_followed_by_only_one_newline():
pass
elif False:
-
@@ -54,12 +53,10 @@
class IHopeYouAreHavingALovelyDay:
def __call__(self):
print("i_should_be_followed_by_only_one_newline")
-
else:
-
def foo():
pass
-
@ -146,14 +137,17 @@ elif os.name == "nt":
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

View file

@ -344,6 +344,7 @@ def with_leading_comment():
# looking from the position of the if
# Regression test for https://github.com/python/cpython/blob/ad56340b665c5d8ac1f318964f71697bba41acb7/Lib/logging/__init__.py#L253-L260
if True:
def f1():
pass # a
else:
@ -351,6 +352,7 @@ else:
# Here it's actually a trailing comment
if True:
def f2():
pass
# a

View file

@ -203,14 +203,17 @@ def f():
if True:
def f():
pass
# 1
elif True:
def f():
pass
# 2
else:
def f():
pass
# 3

View file

@ -263,18 +263,22 @@ except RuntimeError:
raise
try:
def f():
pass
# a
except:
def f():
pass
# b
else:
def f():
pass
# c
finally:
def f():
pass
# d