Open3

python with VSCode

えんぶんえんぶん

pytestとlaunch.json

  • pytest-covでカバレッジ計測しているとブレークポイント止まってくれないので、デバッグ実行中はカバレッジ計測をしないようにしたい
  • settings.jsonに書いちゃうとデバッグ実行時以外も設定が効いちゃうのでlaunch.jsonに書く
  • 前はPYTEST_ADDOPTSで--no-covつけとけばブレークポイントで止まってた気がするけどpurposeを設定しないと止まってくれなかった

https://docs.pytest.org/en/7.1.x/example/simple.html
https://pytest-cov.readthedocs.io/en/latest/config.html#reference
https://code.visualstudio.com/docs/python/testing#_debug-tests

launch.json
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: 現在のファイル",
            "type": "debugpy",  // 前は"python"だった
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "justMyCode": true,
            "purpose": ["debug-test"],
            "env": {"PYTEST_ADDOPTS": "--no-cov"}
        }
    ]
}
えんぶんえんぶん

結構前にPylint, BlackFormatterなどは個別に拡張機能を入れるのが必須になった

https://github.com/microsoft/vscode-python/wiki/Migration-to-Python-Tools-Extensions

(プロジェクトごとに拡張機能無効化したりするのがめんどくさい)

ファイル保存後にフォーマッタ・リンターが自動実行される際に、選択されているインタープリターから参照されるライブラリ(例えば.venv/Lib内にインストールされてるやつ)ではなく、拡張機能に組み込まれているバージョンのライブラリが実行されてしまっていたようなので、明示的にインタープリターに紐つくLibを参照する設定

{
  "[python]": {
    "editor.codeActionsOnSave": {
      "source.organizeImports": "explicit"
    },
    "editor.defaultFormatter": "ms-python.black-formatter"
  },
  # インタプリタのlibを参照する設定
  "pylint.path": ["${interpreter}", "-m", "pylint"],
  "black-formatter.path": ["${interpreter}", "-m", "black"],
}

${interpreter}としているので、チームでsettings.jsonを共有する場合でも各々のinterpreterの場所に左右されることがない

えんぶんえんぶん

2025/04/11 メモ

${interpreter}についてこうやって設定しろと見たのでこのように書いてたと思うが改めてググっても情報が出てこない・・・この設定要らないかも

multi rootのプロジェクトでBlackフォーマッタのサーバがうまく起動しない場合、一旦interpreterの設定をクリアするとうまくいくことがあった

  • コマンドパレット開く
  • "Python: Clear Workspace Interpreter Settings."を選択