yapf icon indicating copy to clipboard operation
yapf copied to clipboard

# yapf: disable does not preserve indent_width

Open phoenix-meadowlark opened this issue 4 years ago • 2 comments

# yapf: disable does not preserve the indent width of the code to not be formatted, and applies indent_width instead. For example, in a python file using an indent of two spaces, yapf outputs a file with an indent width of four spaces in the disabled region:

# yapf_disable_indent_width_bug.py
# yapf: disable
def dont_indent_me():
  return
# yapf: enable
python -m yapf -i yapf_disable_indent_width_bug.py
# yapf_disable_indent_width_bug.py
# yapf: disable
def dont_indent_me():
    return
# yapf: enable

Aside from throwing an error, this is probably the least awful thing to do when there is other code that yapf needs to format. That said it probably warrants noting that # yapf: disable will be disregarded wrt indent widths in its readme section.

phoenix-meadowlark avatar Apr 08 '21 17:04 phoenix-meadowlark

This is more-or-less intentional. The issue is that if we don't use the correct indentation within a "disabled" section, it could result in invalid code. For instance:

        class SplitPenaltyTest(unittest.TestCase):
          def testUnbreakable(self):
            self._CheckPenalties(tree, [
            ])  # yapf: disable

would reformat to:

        class SplitPenaltyTest(unittest.TestCase):
            def testUnbreakable(self):
            self._CheckPenalties(tree, [
            ])  # yapf: disable

This seems very bad, and could cause a lot of issues when the text around the disabled line needs to be reindented.

bwendling avatar May 30 '21 05:05 bwendling

The way to prevent your situation is to use the same indentation strategy. So if you have two space indentations, keep it two spaces instead of four.

bwendling avatar May 30 '21 05:05 bwendling