Skip to main content
 首页 » 编程设计

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

2024年09月07日22me-sa

我写了一些 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 
]) 

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

请您参考如下方法:

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

"python.formatting.provider": "yapf" 

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

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

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