如何用指定autopep8命令实现多行字符串缩进而非对齐函数名
解决autopep8多行字符串缩进而非对齐函数名的问题
针对你的需求,我们可以通过调整autopep8的规则忽略列表,让它把函数参数中的多行字符串处理成缩进格式,而不是对齐到函数名称的末尾。
调整后的autopep8命令
你需要在原有命令的基础上添加--ignore=E125(E125是控制续行对齐到括号起始位置的PEP8规则),最终命令如下:
autopep8 --pep8-passes 2000 --verbose --aggressive --aggressive --ignore=E501,E722,E125
为什么这样做?
默认情况下,autopep8会遵循E125规则,把函数参数里的多行内容对齐到函数调用的起始括号位置(也就是你示例中parser.add_argument的末尾)。当我们忽略这条规则后,autopep8会转而采用缩进格式来排版续行,让多行字符串的后续行与函数内部的缩进层级保持一致,更符合你想要的样式。
效果对比
处理前的代码片段
parser.add_argument('-a', '--auto', help='Activate automatic semi-intelligent inference for --some-long-flags and --other-long-flags. ' '--some-long-flags will be activated when the primary manifold script is presented with a single-node cluster. ' '--other-long-flags will be enabled when no resources are specified in the helm overrides file.', action=...
处理后的预期格式
parser.add_argument( '-a', '--auto', help='Activate automatic semi-intelligent inference for --some-long-flags and --other-long-flags. ' '--some-long-flags will be activated when the primary manifold script is presented with a single-node cluster. ' '--other-long-flags will be enabled when no resources are specified in the helm overrides file.', action=... )
额外注意事项
如果调整命令后没有达到预期效果,可以检查这几点:
- 确保你的autopep8是最新版本,旧版本对部分规则的处理逻辑可能不够完善;
- 确认代码中的多行字符串是通过空格拼接的(如示例中的写法),三重引号的多行字符串处理逻辑会有差异;
- 可以适当提高
--pep8-passes的数值,保证autopep8有足够的迭代次数完成格式调整。
内容的提问来源于stack exchange,提问作者Jay Taylor




