SE_BOKUのまとめノート的ブログ

SE_BOKUが知ってること・勉強したこと・考えたことetc

2023年10月版/Anaconda Python3+VsCodeの構文チェックとフォーマット

f:id:arakan_no_boku:20190223210405j:plain

目次

Anaconda Python3+VsCodeの構文チェックとフォーマット

Windows11+Anaconda python+Visual studio code(VsCode) で開発環境を作ったら、ファイルを保存時に、構文チェックや自動フォーマットをできるようにします。

この記事の続きです。

arakan-pgm-ai.hatenablog.com

構文チェックの世界標準スタイル(’PEP8)

pythonには世界標準のスタイル規約があります。

PEP8(Python Enhancement Proposal #8)です。

f:id:arakan_no_boku:20181110234101j:plain

pep8規約をチェックするツールには「pycodestyle」がありますが、現在は「flake8」がデファクトスタンダードなので、それを使います。

lake8は内部で「pycodestyle」を使っているので、エラーコードは同じです。

コードチェッカー(flake8)拡張機能インストール

flake8は、Pythonのコードチェッカーです。

flake8はPEP8というスタイル規約に基づき、コードチェックします。

Ctrl+Shift+Xなどで拡張機能を開き「ms-python.flake8」で検索し、表示された「flake8」拡張機能をインストールします。

以前は「flake8」のバイナリを「pip」などでインストールしないといけなかったのですが、今は拡張機能をインストールするだけでいけます。

構文チェックするだけなら、特に設定はいりません。

flake8の古い設定がある場合は全部消す

ただ、以前に古い設定でFlake8を使っていた場合は、それらの設定を全部消す必要があります。

例えば、「settings.json」に以下のような設定を書いていたりする場合は全て消さないとだめです。(古いほうを使おうとするので・・)。

  "python.linting.lintOnSave": true,
  "python.linting.pylintEnabled": false,
  "python.linting.pep8Enabled": false,
  "python.linting.flake8Enabled": true, 

このような設定を書いているとVsCodeで「This setting will soon be deprecated. Learn more here: https://aka.ms/AAlgvkb.(この設定はまもなく廃止される予定です。 詳細については、こちらをご覧ください: https://aka.ms/AAlgvkb)」みたいな警告がでますが「https://aka.ms/AAlgvkb」の情報を見て修正するより、バッサリ全部消して、拡張機能を入れなおしたほうが早いです。

あと、Flake8の設定で「flake8バイナリへのパス」などを設定している場合もすべて消す必要があります。

flake8(pycodestyle)のエラーコード一覧

flake8の出力するエラーコードです。

エラーチェックを除外するなどの設定をする場合はこのコードが必要です。

訳は自分がGoogle翻訳してつけたものなので、誤訳もあるかもしれません。

code sample message
E1 Indentation インデント
E101 indentation contains mixed spaces and tabs インデントにはスペースとタブが混在しています
E111 indentation is not a multiple of four インデントは4の倍数ではありません
E112 expected an indented block インデントブロックが予想される
E113 unexpected indentation 予想外の圧痕
E114 indentation is not a multiple of four (comment) インデントは4の倍数ではありません(コメント)
E115 expected an indented block (comment) インデントされたブロック(コメント)
E116 unexpected indentation (comment) 予期しないインデント(コメント)
E121 (*^) continuation line under-indented for hanging indent インデントを挟むために下線でインデントされた継続行
E122 (^) continuation line missing indentation or outdented 継続行がインデントされていないか、またはアウトデントされている
E123 (*) closing bracket does not match indentation of opening bracket’s line 開閉ブラケットが開きブラケットのラインの押し込みと一致しない
E124 (^) closing bracket does not match visual indentation 閉じ括弧が視覚的な刻み目と一致しない
E125 (^) continuation line with same indent as next logical line 次の論理行と同じインデントの継続行
E126 (*^) continuation line over-indented for hanging indent インデントを挟むために余分にインデントされた継続行
E127 (^) continuation line over-indented for visual indent 視覚インデントのために余分にインデントされた継続行
E128 (^) continuation line under-indented for visual indent 視覚インデントのためにインデントされた継続行
E129 (^) visually indented line with same indent as next logical line 次の論理行と同じインデントを持つ視覚的にインデントされた行
E131 (^) continuation line unaligned for hanging indent インデントをぶら下げるために並んでいない連続線
E133 (*) closing bracket is missing indentation 閉じ括弧にはインデントがありません
E2 Whitespace 空白
E201 whitespace after ‘(‘ 空白の後に '('
E202 whitespace before ‘)’ 空白の前に ')'
E203 whitespace before ‘:’ 空白の前に ':'
E211 whitespace before ‘(‘ 空白の前に '('
E221 multiple spaces before operator オペレータの前に複数のスペース
E222 multiple spaces after operator オペレータの後の複数のスペース
E223 tab before operator 操作前のタブ
E224 tab after operator 操作後のタブ
E225 missing whitespace around operator オペレータの周囲に空白がない
E226 (*) missing whitespace around arithmetic operator 算術演算子の周りに空白がない
E227 missing whitespace around bitwise or shift operator ビット単位またはシフト演算子の周囲に空白がない
E228 missing whitespace around modulo operator モジュロ演算子の周囲に空白がない
E231 missing whitespace after ‘,’, ‘;’, or ‘:’ '、'、 ';'、または ':'の後に空白がない
E241 (*) multiple spaces after ‘,’ '、'
E242 (*) tab after ‘,’ タブの後に '、'
E251 unexpected spaces around keyword / parameter equals キーワード/パラメータの前後の予期しないスペース
E261 at least two spaces before inline comment インラインコメントの前に少なくとも2つのスペース
E262 inline comment should start with ‘# ‘ インラインコメントは '#'で始まります
E265 block comment should start with ‘# ‘ ブロックコメントは '#'で始まります
E266 too many leading ‘#’ for block comment ブロックコメントの先頭に「#」が多すぎます
E271 multiple spaces after keyword キーワードの後の複数のスペース
E272 multiple spaces before keyword キーワードの前に複数のスペース
E273 tab after keyword キーワードの後のタブ
E274 tab before keyword キーワードの前のタブ
E275 missing whitespace after keyword キーワードの後に​​空白がない
E3 Blank line 空白行
E301 expected 1 blank line, found 0 期待される1空白行、見つかった0
E302 expected 2 blank lines, found 0 期待される2つの空白行、見つかった0
E303 too many blank lines (3) あまりにも多くの空白行(3)
E304 blank lines found after function decorator 関数デコレータの後に空白行が見つかりました
E305 expected 2 blank lines after end of function or class 関数またはクラスの終了後に2つの空白行が必要です
E306 expected 1 blank line before a nested definition ネストされた定義の前に空白行が1つ必要です
E4 Import インポート
E401 multiple imports on one line 1行に複数のインポート
E402 module level import not at top of file モジュールレベルのインポートがファイルの先頭にない
E5 Line length 行の長さ
E501 (^) line too long (82 > 79 characters) 行が長すぎる(82> 79文字)
E502 the backslash is redundant between brackets ブラケットの間にバックスラッシュは冗長です
E7 Statement ステートメント
E701 multiple statements on one line (colon) 1行の複数のステートメント(コロン)
E702 multiple statements on one line (semicolon) 1行に複数のステートメントセミコロン)
E703 statement ends with a semicolon ステートメントセミコロンで終わります
E704 (*) multiple statements on one line (def) 1行に複数のステートメント(def)
E711 (^) comparison to None should be ‘if cond is None:’ Noneとの比較は 'condがNoneの場合'にする必要があります: '
E712 (^) comparison to True should be ‘if cond is True:’ or ‘if cond:’ Trueとの比較は 'condがTrueの場合:'または 'if cond:'とする必要があります。
E713 test for membership should be ‘not in’ メンバーシップのテストは 'not in'でなければなりません
E714 test for object identity should be ‘is not’ オブジェクトアイデンティティーのテストは 'is not'
E721 (^) do not compare types, use ‘isinstance()’ 型を比較しないでください。 'isinstance()'を使用してください。
E722 do not use bare except, specify exception instead 裸のものを使用しないでください。代わりに例外を指定してください
E731 do not assign a lambda expression, use a def ラムダ式を代入しないでください。def
E741 do not use variables named ‘l’, ‘O’, or ‘I’ 'l'、 'O'、または 'I'という名前の変数は使用しないでください
E742 do not define classes named ‘l’, ‘O’, or ‘I’ 'l'、 'O'、または 'I'というクラスを定義しないでください。
E743 do not define functions named ‘l’, ‘O’, or ‘I’ 'l'、 'O'、または 'I'という名前の関数を定義しないでください
E9 Runtime ランタイム
E901 SyntaxError or IndentationError SyntaxErrorまたはIndentationError
E902 IOError IOError
W1 Indentation warning インデント警告
W191 indentation contains tabs インデントにはタブが含まれています
W2 Whitespace warning 空白の警告
W291 trailing whitespace 末尾の空白
W292 no newline at end of file ファイルの最後に改行がありません
W293 blank line contains whitespace 空行には空白が含まれます
W3 Blank line warning 空白行の警告
W391 blank line at end of file ファイルの最後に空白行
W5 Line break warning 改行警告
W503 (*) line break before binary operator

バイナリ演算子の前の改行

例えば「+」の前で改行したらダメとか

W504 (*) line break after binary operator

バイナリ演算子後の改行

例えば「+」の後で改行したらダメとか

W505 (*^) doc line too long (82 > 79 characters) doc行が長すぎます(82文字> 79文字)
W6 Deprecation warning 廃止予定の警告
W601 .has_key() is deprecated, use ‘in’ .has_key()は非推奨です。 'in'を使用してください。
W602 deprecated form of raising exception 非難される形式の募集例外
W603 ‘<>’ is deprecated, use ‘!=’ '<>'は非推奨です。 '!='
W604 backticks are deprecated, use ‘repr()’ バッククォートは非難され、 'repr()'を使う
W605 invalid escape sequence ‘x’ 無効なエスケープシーケンス 'x'
W606 ‘async’ and ‘await’ are reserved keywords starting with Python 3.7 'async'と 'await'はPython 3.7以降の予約キーワードです
blackフォーマッタのインストール

「フォーマッタは「black」を使います。

以前は「autopep8」でしたが、今はこちらが主流です。

実際、autopep8を使うための以下のような設定

 "python.formatting.provider": "autopep8",
 "python.formatting.autopep8Args": [
      "--aggressive",
      "--aggressive",
 ], 

これらも「This setting will soon be deprecated. Learn more here: https://aka.ms/AAlgvkb.(この設定はまもなく廃止される予定です。 詳細については、こちらをご覧ください: https://aka.ms/AAlgvkb)」と表示されますので、すっぱり消してしまって、black拡張機能を導入します。

拡張機能で「ms-python.black-formatter」と検索し「..Black-Formatter」をインストールします。

blackフォーマッタで保存時にフォーマットするように設定

Black-Formatterをデフォルトにして、保存時に自動フォーマットするように「settings.json」に以下を追記します。

 "[python]": {
        "editor.defaultFormatter": "ms-python.black-formatter",
        "editor.formatOnSave": true
  }   

これで、flake8で構文チェックし、ソース保存時にフォーマットを自動修正してくれるようになります。