やってみる

アウトプットすべく己を導くためのブログ。その試行錯誤すらたれ流す。

flake8でPythonコードを静的チェックする(Lint)

 flake8はLintツール。いわゆるコードの静的チェッカー。

情報源

Flake8

 Lintツール。Pythonソースコードを静的チェックする。

  • PEP8によるコードの静的チェック
  • pyflakesによる論理エラーチェック
  • 循環的複雑度をチェック

インストール

pip3 install flake8

使ってみる

コードを用意する

a.py

#!/usr/bin/env python3
# coding: utf8
def my_Method(p):
    print('Hello Python!!')
if __name__ == '__main__':
    my_Method('value')

チェックする

flake8 a.py

 問題点が出た。

a.py:5:1: E305 expected 2 blank lines after class or function definition, found 0
a.py:7:1: W391 blank line at end of file

 チッ、英語かよ。しかもぜんぶ改行関係。べつにそのくらいいいじゃん。心の狭い表れですな。

 ていうか、メソッド名に大文字が入っちゃってんですけど。アウトでしょこれ。ダメだ、ぜんぜんチェックしてくれてないやん。

コードも表示する

flake8 --show-source .
./a.py:5:1: E305 expected 2 blank lines after class or function definition, found 0
if __name__ == '__main__':
^
./a.py:7:1: W391 blank line at end of file

^

 とにかく、こんな感じでチェックしてくれる。

 こいつを手作業で修正してもいいのだが、自動的に修正してくれるツールがある。次回紹介する。

ヘルプ

flake8 --help
usage: flake8 [options] file file ...

positional arguments:
  filename

optional arguments:
  -h, --help            show this help message and exit
  -v, --verbose         Print more information about what is happening in
                        flake8. This option is repeatable and will increase
                        verbosity each time it is repeated.
  --output-file OUTPUT_FILE
                        Redirect report to a file.
  --append-config APPEND_CONFIG
                        Provide extra config files to parse in addition to the
                        files found by Flake8 by default. These files are the
                        last ones read and so they take the highest precedence
                        when multiple files provide the same option.
  --config CONFIG       Path to the config file that will be the authoritative
                        config source. This will cause Flake8 to ignore all
                        other configuration files.
  --isolated            Ignore all configuration files.
  --version             show program's version number and exit
  -q, --quiet           Report only file names, or nothing. This option is
                        repeatable.
  --count               Print total number of errors and warnings to standard
                        error and set the exit code to 1 if total is not
                        empty.
  --diff                Report changes only within line number ranges in the
                        unified diff provided on standard in by the user.
  --exclude patterns    Comma-separated list of files or directories to
                        exclude. (Default: ['.svn', 'CVS', '.bzr', '.hg',
                        '.git', '__pycache__', '.tox', '.eggs', '*.egg'])
  --extend-exclude patterns
                        Comma-separated list of files or directories to add to
                        the list of excluded ones.
  --filename patterns   Only check for filenames matching the patterns in this
                        comma-separated list. (Default: ['*.py'])
  --stdin-display-name STDIN_DISPLAY_NAME
                        The name used when reporting errors from code passed
                        via stdin. This is useful for editors piping the file
                        contents to flake8. (Default: stdin)
  --format format       Format errors according to the chosen formatter.
  --hang-closing        Hang closing bracket instead of matching indentation
                        of opening bracket's line.
  --ignore errors       Comma-separated list of errors and warnings to ignore
                        (or skip). For example, ``--ignore=E4,E51,W234``.
                        (Default: ['E704', 'E126', 'E226', 'E123', 'W503',
                        'E121', 'E24', 'W504'])
  --extend-ignore errors
                        Comma-separated list of errors and warnings to add to
                        the list of ignored ones. For example, ``--extend-
                        ignore=E4,E51,W234``.
  --per-file-ignores PER_FILE_IGNORES
                        A pairing of filenames and violation codes that
                        defines which violations to ignore in a particular
                        file. The filenames can be specified in a manner
                        similar to the ``--exclude`` option and the violations
                        work similarly to the ``--ignore`` and ``--select``
                        options.
  --max-line-length n   Maximum allowed line length for the entirety of this
                        run. (Default: 79)
  --max-doc-length n    Maximum allowed doc line length for the entirety of
                        this run. (Default: None)
  --indent-size n       Number of spaces used for indentation (Default: 4)
  --select errors       Comma-separated list of errors and warnings to enable.
                        For example, ``--select=E4,E51,W234``. (Default: ['E',
                        'F', 'W', 'C90'])
  --extend-select errors
                        Comma-separated list of errors and warnings to add to
                        the list of selected ones. For example, ``--extend-
                        select=E4,E51,W234``.
  --disable-noqa        Disable the effect of "# noqa". This will report
                        errors on lines with "# noqa" at the end.
  --show-source         Show the source generate each error or warning.
  --no-show-source      Negate --show-source
  --statistics          Count errors and warnings.
  --enable-extensions ENABLE_EXTENSIONS
                        Enable plugins and extensions that are otherwise
                        disabled by default
  --exit-zero           Exit with status code "0" even if there are errors.
  -j JOBS, --jobs JOBS  Number of subprocesses to use to run checks in
                        parallel. This is ignored on Windows. The default,
                        "auto", will auto-detect the number of processors
                        available to use. (Default: auto)
  --tee                 Write to stdout and output-file.
  --benchmark           Print benchmark information about this run of Flake8
  --bug-report          Print information necessary when preparing a bug
                        report

mccabe:
  --max-complexity MAX_COMPLEXITY
                        McCabe complexity threshold

pyflakes:
  --builtins BUILTINS   define more built-ins, comma separated
  --doctests            also check syntax of the doctests
  --include-in-doctest INCLUDE_IN_DOCTEST
                        Run doctests only on these files
  --exclude-from-doctest EXCLUDE_FROM_DOCTEST
                        Skip these files when running doctests

Installed plugins: mccabe: 0.6.1, pycodestyle: 2.8.0, pyflakes: 2.4.0

対象環境

$ uname -a
Linux raspberrypi 5.10.52-v7l+ #1441 SMP Tue Aug 3 18:11:56 BST 2021 armv7l GNU/Linux