Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Insert empty line between suite and alternative branch after def/class #12294

Merged
merged 5 commits into from
Jul 15, 2024

Conversation

konstin
Copy link
Member

@konstin konstin commented Jul 12, 2024

When there is a function or class definition at the end of a suite followed by the beginning of an alternative block, we have to insert a single empty line between them.

In the if-else-statement example below, we insert an empty line after the foo in the if-block, but none after the else-block foo, since in the latter case the enclosing suite already adds empty lines.

if sys.version_info >= (3, 10):
    def foo():
        return "new"
else:
    def foo():
        return "old"
class Bar:
    pass

To do so, we track whether the current suite is the last one in the current statement with a new option on the suite kind.

Fixes #12199

@konstin konstin added the formatter Related to the formatter label Jul 12, 2024
Copy link
Contributor

github-actions bot commented Jul 12, 2024

ruff-ecosystem results

Formatter (stable)

ℹ️ ecosystem check encountered format errors. (no format changes; 1 project error)

openai/openai-cookbook (error)

warning: Detected debug build without --no-cache.
error: Failed to parse examples/chatgpt/gpt_actions_library/.gpt_action_getting_started.ipynb:11:1:1: Expected an expression
error: Failed to parse examples/chatgpt/gpt_actions_library/gpt_action_bigquery.ipynb:13:1:1: Expected an expression

Formatter (preview)

ℹ️ ecosystem check detected format changes. (+15 -0 lines in 14 files in 5 projects; 1 project error; 48 projects unchanged)

bokeh/bokeh (+5 -0 lines across 5 files)

ruff format --preview

setup.py~L42

 
     def yellow(text: str) -> str:
         return f"{colorama.Fore.YELLOW}{text}{colorama.Style.RESET_ALL}"
+
 except ModuleNotFoundError:
 
     def _plain(text: str) -> str:

src/bokeh/command/subcommands/file_output.py~L193

 
                 def indexed(i: int) -> str:
                     return filename
+
             else:
 
                 def indexed(i: int) -> str:

src/bokeh/core/has_props.py~L49

     F = TypeVar("F", bound=Callable[..., Any])
 
     def lru_cache(arg: int | None) -> Callable[[F], F]: ...
+
 else:
     from functools import lru_cache
 

src/bokeh/document/locking.py~L93

         @wraps(func)
         async def _wrapper(*args: Any, **kw: Any) -> None:
             await func(*args, **kw)
+
     else:
 
         @wraps(func)

tests/unit/bokeh/core/test_has_props.py~L556

         class DupeProps(hp.HasProps):
             bar = AngleSpec()
             bar_units = String()
+
     except RuntimeError as e:
         assert str(e) == "Two property generators both created DupeProps.bar_units"
     else:

langchain-ai/langchain (+2 -0 lines across 2 files)

ruff format --preview

libs/community/tests/unit_tests/chat_message_histories/test_sql.py~L10

 
     class Base(DeclarativeBase):
         pass
+
 except ImportError:
     # for sqlalchemy < 2
     from sqlalchemy.ext.declarative import declarative_base

libs/core/langchain_core/messages/utils.py~L765

 
         def list_token_counter(messages: Sequence[BaseMessage]) -> int:
             return sum(token_counter(msg) for msg in messages)  # type: ignore[arg-type, misc]
+
     else:
         list_token_counter = token_counter  # type: ignore[assignment]
 

python/typeshed (+4 -0 lines across 3 files)

ruff format --preview

stdlib/dbm/gnu.pyi~L44

 
     if sys.version_info >= (3, 11):
         def open(filename: StrOrBytesPath, flags: str = "r", mode: int = 0o666, /) -> _gdbm: ...
+
     else:
         def open(filename: str, flags: str = "r", mode: int = 0o666, /) -> _gdbm: ...

stdlib/inspect.pyi~L334

             locals: Mapping[str, Any] | None = None,
             eval_str: bool = False,
         ) -> Self: ...
+
     else:
         @classmethod
         def from_callable(cls, obj: _IntrospectableCallable, *, follow_wrapped: bool = True) -> Self: ...

stdlib/ipaddress.pyi~L46

         def __ge__(self, other: Self) -> bool: ...
         def __gt__(self, other: Self) -> bool: ...
         def __le__(self, other: Self) -> bool: ...
+
     else:
         def __ge__(self, other: Self, NotImplemented: Any = ...) -> bool: ...
         def __gt__(self, other: Self, NotImplemented: Any = ...) -> bool: ...

stdlib/ipaddress.pyi~L84

         def __ge__(self, other: Self) -> bool: ...
         def __gt__(self, other: Self) -> bool: ...
         def __le__(self, other: Self) -> bool: ...
+
     else:
         def __ge__(self, other: Self, NotImplemented: Any = ...) -> bool: ...
         def __gt__(self, other: Self, NotImplemented: Any = ...) -> bool: ...

indico/indico (+3 -0 lines across 3 files)

ruff format --preview

indico/modules/events/contributions/util.py~L110

             if not c.speakers:
                 return True, None
             return False, speakers[0].get_full_name(last_name_upper=False, abbrev_first_name=False).lower()
+
     elif sort_by == BOASortField.board_number:
         key_func = attrgetter('board_number')
     elif sort_by == BOASortField.session_board_number:

indico/web/flask/templating.py~L63

             if isinstance(item, str):
                 item = item.lower()
             return natural_sort_key(item)
+
     else:
         sort_func = natural_sort_key
 

indico/web/flask/util.py~L78

             # Indico RH
             def wrapper(**kwargs):
                 return obj().process()
+
         else:
             # Some class we didn't expect.
             raise ValueError(f'Unexpected view func class: {obj!r}')

mesonbuild/meson-python (+1 -0 lines across 1 file)

ruff format --preview

mesonpy/_compat.py~L29

 
     def read_binary(package: str, resource: str) -> bytes:
         return importlib.resources.files(package).joinpath(resource).read_bytes()
+
 else:
     read_binary = importlib.resources.read_binary
 

openai/openai-cookbook (error)

ruff format --preview

warning: Detected debug build without --no-cache.
error: Failed to parse examples/chatgpt/gpt_actions_library/.gpt_action_getting_started.ipynb:11:1:1: Expected an expression
error: Failed to parse examples/chatgpt/gpt_actions_library/gpt_action_bigquery.ipynb:13:1:1: Expected an expression

@konstin konstin force-pushed the konsti/fix-def-end-of-block branch from bd40982 to ba1f552 Compare July 12, 2024 08:38
@konstin konstin marked this pull request as draft July 12, 2024 08:38
When there is a function or class definition at the end of a suite followed by the beginning of an alternative block, we have to insert a single empty line between them.

In the if-else-statement example below, we insert an empty line after the `foo` in the if-block, but none after the else-block `foo`, since in the latter case the enclosing suite already adds empty lines.

```python
if sys.version_info >= (3, 10):
    def foo():
        return "new"
else:
    def foo():
        return "old"
class Bar:
    pass
```

To do so, we track whether the current suite is the last one in the current statement with a new option on the suite kind.

Fixes #12199
@konstin konstin force-pushed the konsti/fix-def-end-of-block branch from ba1f552 to b3d6adb Compare July 12, 2024 09:01
@konstin
Copy link
Member Author

konstin commented Jul 12, 2024

Not sure if this counts as bugfix or breaking change, i'm fine with merging it before the next breaking release.

@MichaReiser
Copy link
Member

Not sure if this counts as bugfix or breaking change, i'm fine with merging it before the next breaking release.

I think we have to gate this behind preview according to our version policy. The version policy only allows formatting style changes that address instabilities or formatting that lead to invalid syntax.

The ecosystem checks look good :)

@konstin konstin force-pushed the konsti/fix-def-end-of-block branch from 438001a to 5f4f4d8 Compare July 12, 2024 09:50
@konstin konstin marked this pull request as ready for review July 12, 2024 10:01
@konstin konstin requested review from MichaReiser and removed request for MichaReiser July 12, 2024 10:02
@MichaReiser MichaReiser added the preview Related to preview mode features label Jul 15, 2024
Copy link
Member

@MichaReiser MichaReiser left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice and thanks for working on this!

This overall looks good to me. We should add a few tests around suppression comments to make sure we don't add new lines into suppressed ranges

@konstin konstin merged commit 9a817a2 into main Jul 15, 2024
20 checks passed
@konstin konstin deleted the konsti/fix-def-end-of-block branch July 15, 2024 10:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
formatter Related to the formatter preview Related to preview mode features
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Formatter: inconsistent amount of added empty lines around an inner function
2 participants