python-black icon indicating copy to clipboard operation
python-black copied to clipboard

Wrong formatting for indented scopes

Open fievelk opened this issue 3 years ago • 1 comments

Suppose you have this in a file:

class SomeClass:
    def some_function(self):
        with open("somefile", "w") as inf:
                print(inf)  # <-- wrong indentation (4 unnecessary additional spaces)

When you only select the two lines (starting from the "w" in with until print(inf) and format them, the result ignores the current level of nesting and returns invalid code:

class SomeClass:
    def some_function(self):
        with open("somefile", "w") as inf:
    print(inf)

If you select the full line that contains with open (starting from the very first empty character of the line) you get this:

class SomeClass:
    def some_function(self):
with open("somefile", "w") as inf:
    print(inf)

So, at the moment, the selection formatter doesn't consider the current context of the selected code (its indentation). I'm not sure how this could be fixed, but it might be something interesting to check.

fievelk avatar Jul 02 '22 11:07 fievelk

I think this feature or issue should belong to black.

thep0y avatar Jul 03 '22 00:07 thep0y