Skip to content

allow_empty_first_line_before_new_block_or_comment can lead to inconsistent formatting #4121

@MichaReiser

Description

@MichaReiser

Describe the style change

I am working on Ruff's formatter and implementing Black's preview styles. We reviewed the allow_empty_first_line_before_new_block_or_comment preview style and decided not to implement it because it leads to inconsistent formatting after moving or deleting code or requires more manual intervention.

Examples when allow_empty_first_line_before_new_block_or_comment is enabled

I work on a refactoring and start with the following code:

def foo():
    """
    Docstring
    """

    # Here we go
    if x:
        if no_longer_needed:
            print("Some complex statements")

        # This is also now fine
        a = 123

And I delete the no_longer_needed branch:

def foo():
    """
    Docstring
    """

    # Here we go
    if x:

        # This is also now fine
        a = 123

Black removes the empty line above the comment when the allow_empty_first_line_before_new_block_or_comment style is disabled.

def foo():
    """
    Docstring
    """

    # Here we go
    if x:
        # This is also now fine
        a = 123

Black doesn't remove the empty line when enabling allow_empty_first_line_before_new_block_or_comment, which either results in an unintended empty line above the comment (inconsistency) or that I have to intervene and remove the empty line manually. This feels like something I would expect a formatter to do for me (at the cost that having empty lines before comments isn't possible)

Desired style

To keep the non-preview formatting for comments at the start of a block.

Additional context

Metadata

Metadata

Assignees

No one assigned

    Labels

    C: preview styleIssues with the preview and unstable style. Add the name of the responsible feature in the title.T: styleWhat do we want Blackened code to look like?

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions