LoginSignup
31
29

More than 3 years have passed since last update.

【初心者向け】Visual Studio Code へ autopep8 を導入する

Last updated at Posted at 2021-01-07

autopep8 は、PEP8 コーディングスタイルに準拠した Python のコードフォーマッタです。
これを Visual Studio Code に導入することで、PythonのソースコードをPEP8に準拠したスタイルに自動成形することができるため開発環境に組み込みました。

導入環境

  • Windows 10 64bit
  • Visual Studio Code (VS Code)
  • Python3.8 (※ pip へのパスが通っていることを前提とします。)
  • Windows コマンドプロンプト (cmd.exe) をある程度使えることを前提とします

導入の流れ

  1. autopep8 のインストール
  2. VS Code に autopep8 を設定する
  3. autopep8 の設定値を変更する

1. flake8 のインストール

コマンドプロンプトで次のコマンドを実行します

pip install autopep8

インストールが完了したら、次のコマンドでインストールされたことを確認できます

C:\>pip show autopep8
Name: autopep8
Version: 1.5.4
Summary: A tool that automatically formats Python code to conform to the PEP 8 style guide
Home-page: https://github.com/hhatto/autopep8
Author: Hideo Hattori
Author-email: hhatto.jp@gmail.com
License: Expat License
Location: c:\python\lib\site-packages
Requires: pycodestyle, toml
Required-by:

2. VS Code に autopep8 を設定する

VS Code の設定画面からpython.formatting.autopep8Pathを検索し、Python > Formatting: Autopep8 Path項目にautopep8を設定します。
0.PNG
続けて、VS Code の設定画面からpython.formatting.providerを検索し、Python > Formatting: Provider項目でautopep8を選択設定します。
1.PNG
尚、VS Code の設定は、ユーザー設定、ワークスペース設定、フォルダー設定と分けることが出来ますが、筆者はユーザー設定を選択しています。

3. autopep8 の設定値を変更する

PEP8 スタイルに準拠すると一行の文字数制限が79文字までとなります。
これを現在の開発環境に合わせて、文字数制限を150文字までに設定します。
VS Code の設定画面からpython.formatting.autopep8Argsを検索し、Python > Formatting: Autopep8 Args項目に設定を追加します。
2.PNG
この設定により、VS Code の設定ファイル (settings.json) に次のコードが追加されます。

settings.json
{
    "python.formatting.autopep8Args": [
        "--max-line-length",
        "150"
    ]
}

4. 完了

以上で、Python コードのエディタ上でコンテキストメニューからドキュメントのフォーマットを選択するとソースコードがPEP8に準拠するよう自動成形されます。

参考にしたサイト

31
29
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
31
29