防止 VS Code Python 脚本中的 autopep8 自动转义字符串中的反斜杠

Prevent automatic escaping of backslash in strings by autopep8 in VS Code Python scripts

我使用 Python 插件和 autopep8 设置了 VS Code。我的相关设置是:

{
    "editor.defaultFormatter": "ms-python.python",   
    "editor.formatOnSave: true,
    "python.formatting.autopep8Args":[
        "--agressive"
    ]
}

我喜欢它在自动格式化方面的大部分功能(切割行长度,替换这里或那里的奇怪东西)但是有一个功能真的让我很烦。

我正在使用 pySpark 并将 regexp_replace 函数设置为

df = df.withColumn('NewCol', regexp_replace(col('OldCol'), '\W', ' ')

当我保存文件时,自动格式化程序每次都会将 '\W' 替换为 '\W'。我明白它为什么这样做(通常,字符串中的单个反斜杠是错误的未转义字符),但在这种情况下,我需要它停止。我可以通过任何忽略这种情况的论点吗?我不介意它再也不会转义反斜杠。但我宁愿不关闭 --agressive 对它实现的所有其他事情的更正。

关闭此设置是一个坏主意

无效的转义序列are depreciated as of Python 3.6,最终会导致SyntaxError。即使您目前无意升级您正在使用的 Python 版本,使用无效的转义序列也会限制代码的可移植性。

改为使用原始字符串:

df = df.withColumn('NewCol', regexp_replace(col('OldCol'), r'\W', ' ')

但是,如果您真的想要禁用此设置,您可以将 --ignore 标志与 W605 一起使用,如 here 所述.

{
    "editor.defaultFormatter": "ms-python.python",   
    "editor.formatOnSave": true,
    "python.formatting.autopep8Args":[
        "--aggressive",
        "--ignore W605"
    ]
}

如前面link所述,问题代码W605对应于“修复无效的转义序列'x'”。