Coding Convention [7]: flake8
flake8
https://dev.to/bowmanjd/some-flake8-plugins-for-python-linting-107h
flake8
is a command-line utility for enforcing style consistency across Python projects.
It is a Python code linter tool that checks for errors, styling issue and complexity. It is the wrapper which verifies pep8, pyflakes, and circular complexity. The Flake8 library is built upon 3 tools:
- pycodestyle - checks your Python codebase for styling issues against PEP8.
- PyFlakes - checks your Python codebase for errors
- McCabe - checks your Python codebase for complexity
It has a low rate of false positives.
Getting start with flake8
1. Install
1
2
3
pip install flake8
# or
python -m pip install flake8
2. Run
1
2
flake8 {path_to_code}# check the whole repository
flake8 example.py # check for particular file
3. Inclusion and exclusion
You also have the option to select specific errors or warnings to focus on, allowing you to filter and view only the instances of a particular warning or error, which can help streamline the debugging process and make it easier to identify and address specific issues.
1
flake8 --select E123,W503 {path_to_code}
Alternatively, if you prefer to exclude certain warnings or errors from your view, you can add specific warnings or errors to an ignore list. This enables you to streamline the information presented to you and focus solely on the messages that are relevant to your current task.
1
flake8 --extend-ignore E203,W234 {path_to_code}
\You can simply let the shell in your terminal automatically locate Flake8. However, if you have installed Flake8 for multiple versions of Python (e.g., Python 3.8 and Python 3.9) and need to call a specific version, you’ll get better results by specifying the version you want to use. In such cases, you can use a command like this to ensure the correct version of Flake8 is invoked:
1
python<version> -m pip install flake8
Or you also can choose what to include or exclude from configuration file. By creating a .flake8
file and entering the following information, you can exclude folders and files to be excluded and also set error messages to be ignored.
1
2
3
4
5
6
7
8
9
10
11
12
[flake8]
exclude =
.git,
.gitignore,
*.pot,
*.py[co],
__pycache__,
venv,
.env
ignore =
E128, E203, E501, W234, W291
Create a configuration file in the path below, if you want to set the configuration file globally.
1
2
3
4
5
# Linux, OS X
~/.config/flake8
# Windows
~\.flake8
Using with VSCode
Assuming you have installed flake8, you can use flake8 in VSCode by following the steps below.
Python: Select Linter
- Command Palette
⌘+shift+P
> Type and select ”Python: Select Linter” > Type and select “flake8” > Type and select “Python: Run Linting” will activate linting
Configuration
- Command Palette
⌘+shift+P
> Select “setting.json” >.vscode/setting.json
1
2
3
4
5
6
7
8
9
// lint
"python.linting.flake8Args": [
"--max-line-length=200",
"--ignore=E501", // too many line error
"--ignore=E402", // module level import not at top of file error
"..." ],
"editor.rulers": [
200
],
Settings
There are several settings you can configure to customize the behavior of this extension.
1. flake8.args
- Default : []
- Description
- Arguments passed to Flake8 for linting Python files.
- Each argument is a separate string in the array.
- e.g “flake8.args”: [”–config=”]
2. flake8.cwd
- Default : ${workspaceFolder}
- Description
- Sets the current working directory used to lint.
- By default, it uses the root directory of the workspace
${workspaceFolder}
. - You can use the parent folder as the working directory by setting it to
${fileDirname}
.
3. flake8.severity
- Default
- { “convention”: “Information”, “error”: “Error”, “fatal”: “Error”, “refactor”: “Hint”, “warning”: “Warning”, “info”: “Information” }
- Description
- Mapping message types to diagnostic severity levels. You can also override specific Flake8 error codes.
- e.g { “convention”: “Information”, “error”: “Error”, “fatal”: “Error”, “refactor”: “Hint”, “warning”: “Warning”, “W0611”: “Error”, “undefined-variable”: “Warning” }
4. flake8.path
- Default : []
- Description
- Path or command to be used by the extension to lint. Single or multiple string arrays.
- Each argument is a separate string in the array.
- If set to [“flake8”], it will use the version of Flake8 available in the PATH environment variable.
- Note: Using this option may slowdown linting.
- This also supports the
${interpreter}
variable as one of the entries of the array. This variable is substituted based on the value of theflake8.interpreter
setting. - e.g. - ”flake8.path” : [”~/global_env/flake8”]- ”flake8.path” : [“conda”, “run”, “-n”, “lint_env”, “python”, “-m”, “flake8”]- ”flake8.path” : [“flake8”]- ”flake8.path” : [”${interpreter}”, “-m”, “flake8”]
6. flake8.interpreter
- Default : []
- Description
- Path to the Python executable or command used to start the Flake8 server and child processes.
- Array of single or multiple strings. Each argument is provided as a separate string in the array.
- If set to
[]
, the path of the selected Python interpreter is used.
7. flake8.importStrategy
- Default : useBundled
- Description
- Define the Flake8 binary to use for linting.
- If set to
useBundled
, the included Flake8 binary will be used. - When set to
fromEnvironment
, attempts to use the Flake8 binary and all dependencies available in the currently selected environment. - Note: If the extension can’t find a valid Flake8 binary in the selected environment, it will fallback to using the Flake8 binary that is shipped with the extension.
- This setting will be overridden if
flake8.path
is set.
7. flake8.showNotification
- Default : off
- Description
- Controls when notifications are shown by this extension.
- Accepted values are
onError
,onWarning
,always
andoff
.
8. flake8.ignorePatterns
- Default : []
- Description
- Configure glob patterns as supported by the fnmatch Python library to exclude files or folders from being linted with Flake8.
9. flake8.enabled
- Default : true
- Description
- Specifies whether to enable or disable linting Python files.
- This setting can be applied globally or at the workspace level.
- When disabled, the linting server itself remains active and monitors read and write events, but does not perform linting or expose code operations.
The following variables are supported for substitution in the flake8.args
, flake8.cwd
, flake8.path
, flake8.interpreter
and flake8.ignorePatterns
settings:
${workspaceFolder}
${workspaceFolder:FolderName}
${userHome}
${env:EnvVarName}
Git hook for flake8
A Git hook is a function in Git that executes a specific script at an event. A pre-commit is a hook that runs before committing. Lint can be performed automatically through pre-commit.
1. Create configuration file for Git hook
The .git/hooks/pre-commit
file will be created with the command below.
1
flake8 --install-hook git
You can set the strict option or lazy option.
1
git config --bool flake8.strict true
* If lint fails using the strict option, the commit will not be made and you can see the lint results instead.
1
git config --bool flake8.lazy true
* Only staged files can be inspected using the lazy option. If the lazy option is false, all tracked files are checked.