VS Code:Python代码过长导致格式化时自动换行?


1、背景

  平常写在VSCode写python程序并不关心每行的字符个数限制或者允许长度。而且对于过长代码,VSCode也能通过格式化工具较好地调整代码格式。现有如下代码,发现格式化后的结果并不理想。

g_location_xy, g_location_wh = [0, 0], [0, 0]
if __name__ == "__main__":
    print(g_location_xy[0] + g_location_xy[1] + g_location_wh[0] + g_location_wh[1])

格式化结果:

2、解决方法

  Python编码风格指导(PEP8)要求每行代码不得超过80个字符。而VSCode+Pyhon常用代码检查工具是pylint和flake8,常用代码格式化工具是yapf、autopep8和black
  针对代码过长导致格式化时自动换行,应在setting.json中修改格式化工具的每行最大字符个数。

setting.json:

    // yapf
    "python.formatting.provider": "yapf",
    "python.formatting.yapfArgs": [
        "--style",
        "{column_limit: 200}"
    ],
    // autopep8
    "python.formatting.provider": "autopep8",
    "python.formatting.autopep8Args": [
        "--max-line-length=200"
    ],
    // black
    "python.formatting.provider": "black",
    "python.formatting.blackArgs": [
        "--line-length",
        "200"
    ],

  当某行代码大于79个字符,代码检查工具flake8会报错,同样应在setting.json中修改其每行最大字符个数。pylint不会报错,故不用修改。

flake8报错:

setting.json:

    // pylint
    "python.linting.pylintEnabled": true,
    // flake8
    "python.linting.flake8Enabled": true,
    "python.linting.flake8Args": [
        "--max-line-length=200"
    ],

正确格式化结果:

猜你喜欢

转载自blog.csdn.net/qq_34801642/article/details/106475019
今日推荐