Open8

VS Code devcontainerでPythonのLinterやFormatterやら諸々の設定

kun432kun432

いろんな情報があってちょっとよくわからないので、1つづつまとめる。

kun432kun432

前提

devcontainerのイメージはMS公式のpythonイメージを使う。今回使うのはpython:1-3.10-bookworm

  • 適当なディレクトリをVS Codeで開いて、「開発コンテナー構成ファイルの追加」を選択。
  • 「Python 3」テンプレートを選択、バージョンは「3.10-bookworm」を選択。
  • 追加機能はなし。

こんな感じの設定ファイルになる。

.devcontainer/.devcontainer.json
// For format details, see https://aka.ms/devcontainer.json. For config options, see the
// README at: https://github.com/devcontainers/templates/tree/main/src/python
{
	"name": "Python 3",
	// Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile
	"image": "mcr.microsoft.com/devcontainers/python:1-3.10-bookworm"

	// Features to add to the dev container. More info: https://containers.dev/features.
	// "features": {},

	// Use 'forwardPorts' to make a list of ports inside the container available locally.
	// "forwardPorts": [],

	// Use 'postCreateCommand' to run commands after the container is created.
	// "postCreateCommand": "pip3 install --user -r requirements.txt",

	// Configure tool-specific properties.
	// "customizations": {},

	// Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
	// "remoteUser": "root"
}

コンテナで開き直して、ここからスタート。

kun432kun432

Linter

コードの静的解析。いろいろあるけど「flake8」を使うことにする。MS公式のPythonイメージを使うとflake8はインストールされている。

vscode ➜  /workspace/test $ which flake8
/usr/local/py-utils/bin/flake8

なので、あとは設定を追加していくだけのはず。Lintingはデフォルトで有効になっているけど、明示的に少し書いていく。

.vscode/settings.json
{
    "python.linting.enabled": true,
    "python.linting.lintOnSave": true,
    "python.linting.pylintEnabled": false,
    "python.linting.flake8Enabled": true
}

で適当に.pyファイルを用意して保存してみる。openとfのあとに無駄なスペースを含めてみた。

with open ("file.dat") as f :
    contents = f.read()

以下のように表示される。

どうやら以下の拡張のインストールを促してる様子。

https://marketplace.visualstudio.com/items?itemName=ms-python.flake8

ちなみにこの拡張を入れなくても以下のように表示されるのでチェック自体は動作している模様。

なので多分この拡張は無視してもいいはず。というか、もしチームでやるなら拡張なんかも設定で管理しておきたいので、このおすすめ機能自体を無効化しておく。

.vscode/settings.json
{
    "python.linting.enabled": true,
    "python.linting.lintOnSave": true,
    "python.linting.pylintEnabled": false,
    "python.linting.flake8Enabled": true,
    "extensions.ignoreRecommendations": true
}

ちなみに上記の拡張を一度インストールしてみたけど、よく分からなかった。設定がややこしくなりそうなので、やはり無視すべきだと思う。

でLinterはどうやらファイルの自動修正まで流行ってくれない様子。自動修正はFormatterのほうで行う。

kun432kun432

Formatter

コード規約にあわせたコードの見た目の修正。いろいろあるけど今回は「black」を使うことにする。こちらもMS公式Pythonイメージだとデフォルトで入っていた。

vscode ➜ /workspaces/test $ which black
/usr/local/py-utils/bin/black

ということでこちらも設定を追加するだけでいいはず。

(snip)
    "python.formatting.provider": "black",
    "[python]": {
        "editor.formatOnSave": true
    }

先ほどのサンプルファイルを保存してみる。とコードが修正されると同時に、以下が表示される。

恐らくこれも無視していいと思うんだけど、blackを選択してみた。するとsettings.jsonはこうなる。

(snip)
    "python.formatting.provider": "none",
    "[python]": {
        "editor.formatOnSave": true,
        "editor.defaultFormatter": "ms-python.black-formatter"
    }

ms-python.black-formatterはこれ。

https://marketplace.visualstudio.com/items?itemName=ms-python.black-formatter

この手の推奨機能ホント余計なお世話だと思うのだけど、上の拡張のところをよく見ると、

This extension is experimental. The plan is that it will eventually replace the black formatting functionality of the Python extension.

とあるので、こちらについては今後はむしろ使うべきということになりそう。

ということで、この拡張を使うように設定に入れる。

.devcontainer/.devcontainer.json
{
	"name": "Python 3",
	"image": "mcr.microsoft.com/devcontainers/python:1-3.10-bookworm",
	"customizations": {
		"vscode": {
			"extensions": [
				"ms-python.black-formatter"
			]
		}
	}
}

コンテナをリビルドする。

でテスト用のpythonコードをターミナルからviで開いて修正が必要な形式に変更。VS Codeのエディタから保存してみる。これで修正されるはずだけど、修正されなければ一度VS Codeを開き直してみると良い。(コンテナリビルドで反映されるかと思いきや反映されなかったりして、再起動したら反映された・・・原因よくわからない)

で、flake8とblackがかち合うようなケースがあったりして、flake8の設定を書き換えタイケースがある。そういう場合は以下のように設定ファイルを使うようにすれば良いらしい。

.vscode/settings.json
{
    "python.linting.enabled": true,
    "python.linting.lintOnSave": true,
    "python.linting.pylintEnabled": false,
    "python.linting.flake8Enabled": true,
    "python.linting.flake8Args": [
        "--config=${workspaceFolder}/.flake8"
    ],
    "extensions.ignoreRecommendations": true,
    "python.formatting.provider": "none",
    "[python]": {
        "editor.formatOnSave": true,
        "editor.defaultFormatter": "ms-python.black-formatter",
    },
}

でflake8の設定は以下とする。

.flake8
[flake8]
max-line-length = 88
extend-ignore = E203
kun432kun432

isort

パッケージのインポートの記載順を修正してくれる。

https://pep8-ja.readthedocs.io/ja/latest/#import

import文 は次の順番でグループ化すべきです:

  1. 標準ライブラリ
  2. サードパーティに関連するもの
  3. ローカルな アプリケーション/ライブラリ に特有のもの

元々はデフォルトで対応していたみたいだけどどうやらこれも別の拡張で切り出される様子。

https://marketplace.visualstudio.com/items?itemName=ms-python.isort

.devcontainer.jsonで拡張を有効化。

.devcontainer/.devcontainer.json
        (snip)
	"customizations": {
		"vscode": {
			"extensions": [
				"ms-python.black-formatter",
				"ms-python.isort"
			]
		}
	}
        (snip)

.vscode/settings.json は公式にあるとおりに記載。エディタの設定は"[python]"の下に書いて、isortのオプションは一番外に書くのがポイント。

.vscode/settings.json
{
    "python.linting.enabled": true,
    "python.linting.lintOnSave": true,
    "python.linting.pylintEnabled": false,
    "python.linting.flake8Enabled": true,
    "python.linting.flake8Args": [
        "--config=${workspaceFolder}/.flake8"
    ],
    "extensions.ignoreRecommendations": true,
    "python.formatting.provider": "none",
    "[python]": {
        "editor.formatOnSave": true,
        "editor.defaultFormatter": "ms-python.black-formatter",
        "editor.codeActionsOnSave": {
            "source.organizeImports": true
        },
    },
    "isort.args": ["--profile","black"]
}

コンテナを再ビルド。VS Code本体も必要なら再起動(というぐらいに再起動しないと反映されない気がしてる。というかコンテナ再ビルドじゃだめなのかよ・・・)

以下のような順序で書いて保存してみると、

from langchain.llms import OpenAI

import sys

import os

こうなる。

import os
import sys

from langchain.llms import OpenAI
kun432kun432

後はこの辺をまとめたい。

  • Pylanceを使った型ヒントとか諸々
  • autoDocStringを使ったdocstring自動生成