nikkie-ftnextの日記

イベントレポートや読書メモを発信

VS CodeのPython拡張(ms-python.python)の「Select Interpreter」をのぞく

Python拡張によるコマンド「Select Interpreter」と、設定のpython.defaultInterpreterPathに繋がりがあることに気づきました。

目次

VS CodePython拡張

いつもお世話になっております。

改めてこのページを見ると

  • PylanceとPython Debuggerの拡張を一緒にインストール
  • フォーマッターとリンターはプラガブル

とこの拡張がだいぶ成熟してきた印象を受けます。

今回は「Useful commands」にある「Python: Select Interpreter」を掘り下げます1

Switch between Python interpreters, versions, and environments.

「Working with Python interpreters」(Python environments in VS Code

Python環境について扱ったVS Codeのドキュメントがあります。
Using Python Environments in Visual Studio Code

今回取り上げるのは「Working with Python interpreters」。
コマンドパレットから「Python: Select Interpreter」を使ってインタプリタを選択する手順が解説されています。

例として、こんな環境を用意してみました。
VS Code 1.90.0)

.
├── .venv/
├── .vscode/
│   └── settings.json
└── .python-version

Python: Select Interpreter

  • pyenvでPythonを管理しており、pyenvのglobalのバージョンは3.11.8
  • .python-versionでこのプロジェクトは3.10.9
  • 仮想環境を作っており、.vscode/settings.jsonには仮想環境のPythonを指定した
{
    "python.defaultInterpreterPath": ".venv/bin/python"
}

「Select Interpreter」では、settingsのdefaultInterpreterPathから選べるんです!
Use Python from python.defaultInterpreterPath setting

If you want to manually specify a default interpreter that will be used when you first open your workspace, you can create or modify an entry for the python.defaultInterpreterPath setting. (Manually specify an interpreter より)

.vscode/settings.jsonpython.defaultInterpreterPathを設定してコミットしておくと、チーム開発の環境構築が簡単になりそうだな〜と思いました。

python.defaultInterpreterPath

Python settings referenceより
https://code.visualstudio.com/docs/python/settings-reference#_general-python-settings

Default "python"

Path to the default Python interpreter (略), or the path to a folder containing the Python interpreter.

The Python extension doesn't automatically add or change this setting.

ソースコードに挑む

TypeScriptは分からないなりにもたどってみました(誤っているかも)

package.jsonのcontributes > commandsに「python.setInterpreter」があります2
https://github.com/microsoft/vscode-python/blob/v2024.8.1/package.json#L337-L341

"python.setInterpreter"」という文字列はCommands.Set_Interpreterと定数化
https://github.com/microsoft/vscode-python/blob/v2024.8.1/src/client/common/constants.ts#L62

コマンドの実体と思しきSetInterpreterCommandクラス。
activate()setInterpreterメソッドをregisterCommand
https://github.com/microsoft/vscode-python/blob/v2024.8.1/src/client/interpreter/configuration/interpreterSelector/commands/setInterpreter.ts#L137-L141

setInterpreterメソッド
https://github.com/microsoft/vscode-python/blob/v2024.8.1/src/client/interpreter/configuration/interpreterSelector/commands/setInterpreter.ts#L565-L585

@injectSpring Frameworkのように、インターフェースを実装したクラスが1つだけならそれをインスタンス化して注入するような動きっぽそうと雰囲気でたどりました。精緻化の余地は大いにあります)

終わりに

VS CodePython拡張による「Select Interpreter」コマンドは、設定ファイルのpython.defaultInterpreterPathと関係があることを知りました。
defaultInterpreterPathを明示することで簡単にSelect Interpreterできますね。

TypeScriptからPythonインタプリタを取得する実装は、理解にまだまだ時間を要しそうですが、なかなかに興味深いです。


  1. このコマンドを利用した過去記事
  2. 拡張開発経験から