有没有办法阻止 VSC 中的自动格式化程序更改某些行/代码段?

Vas*_*tch 5 python autoformatting visual-studio-code

我写了一些 python 脚本,大多数时候,我完全同意自动格式化程序的工作原理。但有时我想保持垂直一致性或将代码逻辑地分成几行。

# 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
])
Run Code Online (Sandbox Code Playgroud)

有没有办法告诉自动格式化程序(我使用VSC的默认Python包)忽略这些行(类似于# pylint: disable=C0123魔术注释)?

Gam*_*a11 5

Python 扩展支持两种格式化程序:autopep8(默认)和 yapf。您可以使用以下配置切换到 yapf:

"python.formatting.provider": "yapf"
Run Code Online (Sandbox Code Playgroud)

Yapf 支持通过注释排除格式化区域:

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

我还没有找到 autopep8 的类似功能(尽管您可以使用 全局禁用特定修复--ignore)。