Search code examples
pythonvisual-studio-codeautoformatting

Is there a way to prevent autoformatter in VSC to change certain line/piece of code?


I write some python scripts, and for the most of the time, I am totally OK with how autoformatter works. But sometimes I want to preserve a vertical consistency or split code into lines logically.

# autoformatter removes all leading spaces here
array = numpy.array([[
        [       0,     1589, 25825225,     1589,        0],
        [    1589, 26265625, 26265625, 26265625,     1589],
        [25825225, 26265625, 26265625, 26265625, 25825225],
        [    1589, 26265625, 26265625, 26265625,     1589],
        [       0,     1589, 25825225,     1589,        0],
]])
# autoformatter splits line at '-' sign in the first brackets
links[point.degree - 1].append([
    neighbor.index for neighbor in point.neighbors
])

Is there a way to tell autoformatter (I use default Python package for VSC) to ignore these lines (similar to # pylint: disable=C0123 magic comment)?


Solution

  • The Python extension supports two formatters: autopep8 (default) and yapf. You can switch to yapf with the following configuration:

    "python.formatting.provider": "yapf"
    

    Yapf supports excluding regions from formatting via comments:

    # yapf: disable
    links[point.degree - 1].append([
       neighbor.index for neighbor in point.neighbors
    ])
    # yapf: enable
    

    I haven't found a similar feature for autopep8 (although you can disable specific fixes globally with --ignore).