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"
    ],

正确格式化结果:

  • 12
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值