LoginSignup
0
0

VSCode の拡張機能 Flake8 と autopep8 に pyproject.toml を読み込ませる

Last updated at Posted at 2024-06-01

VSCode の拡張機能 Flake8, autopep8 ではsettings.jsonで各種設定が可能です

settings.json
{
    "[python]": {
        "editor.defaultFormatter": "ms-python.autopep8"
    },
    "autopep8.args": [
        "--aggressive",
        "--indent-size",
        "4",
        "--max-line-length",
        "119",
        "--ignore=E111, E114, E402, E501"
    ]
    "flake8.args": [
        "--ignore=W293, W504, E111, E114, E402, E501"
    ]
}

しかし,Poetry のプロジェクトのような場合にはpyproject.tomlに設定を記載することが多いかと思います
その場合,VSCodeがpyproject.tomlを読み込むための設定が必要です

今回は次のファイルを読み込んでみます

pyproject.toml
    (略)
    [tool.flake8]
    max-line-length = 119
    max-complexity = 18
    ignore = "W293, W504, E111, E114, E402, E501,"
    exclude = [".venv"]
    
    [tool.autopep8]
    max-line-length = 119
    indent-size = 4
    ignore = "E111, E114, E402, E501,"
    aggressive = 3
    exclude = ".venv"

autopep8

autopep8 では--global-configで外部の設定を読み込めます

    autopep8 --global-config <path/to/setting>

.vscode/settings.jsonでグローバルの設定を上書きしましょう.pyproject.tomlはワークスペースのルートディレクトリに配置しているものとします

settings.json
{
    "[python]": {
        "editor.defaultFormatter": "ms-python.autopep8",
    },
    "autopep8.args": [
        "--global-config",
        "pyproject.toml"
    ]
}

VSCodeの OUTPUT タブから autopep8 を選んで正しく読み込めているか確認できます

    2024-06-01 08:49:32.670 [info] /app/.venv/bin/python -m autopep8 --global-config pyproject.toml -
    2024-06-01 08:49:32.670 [info] CWD Server: /app

Flake8

Flake8 の場合,そもそもpyproject.tomlに対応していないのでpflake8 (pyproject-flake8) を入れる必要があります

pyproject.toml
    [tool.poetry.group.dev.dependencies]
    autopep8 = "2.0.0"
    pyproject-flake8 = "5.0.4"

pflake8では--configで外部の設定を読み込めます

    pflake8 --config=<path/to/setting>

.vscode/settings.jsonでグローバルの設定を上書きしましょう

settings.json
{
    (略)
    "flake8.path": [
        "pflake8"
    ],
    "flake8.args": [
        "--config=pyproject.toml"
    ]
}

VSCodeの OUTPUT タブから Flake8 を選んで正しく読み込めているか確認できます

    2024-06-01 08:46:59.235 [info] [Trace - 8:46:59 AM] Received notification 'window/logMessage'.
    2024-06-01 08:46:59.235 [info] pflake8 --format='%(row)d,%(col)d,%(code).1s,%(code)s:%(text)s' --config=pyproject.toml /app/sample.py
    2024-06-01 08:46:59.235 [info] [Trace - 8:46:59 AM] Received notification 'window/logMessage'.
    2024-06-01 08:46:59.235 [info] CWD Server: /app
    2024-06-01 08:46:59.700 [info] [Trace - 8:46:59 AM] Received notification 'textDocument/publishDiagnostics'.

以上です

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0