Skip to content

Instantly share code, notes, and snippets.

Last active Jan 21, 2020
What would you like to do?
automatically ignore lines from flake8
Add `# noqa: FXXX` comments to all lines with violations from flake8
import sys
import argparse
import fileinput
from itertools import groupby
from collections import defaultdict
parser = argparse.ArgumentParser(
usage="flake8 $(git ls-files **/*.py) | - [--dry-run]",
Intended to be used once in lieu of manually fixing all flake8 violatios so
flake8 passes 100% and can be added to a build.""",
parser.add_argument("errors", type=argparse.FileType("r"), help="errors from flake8")
parser.add_argument("--dry-run", action="store_true")
args = parser.parse_args()
def parse_flake8_errors(error_lines):
for error_line in error_lines:
filename, line_number, col, message = error_line.strip().split(":", 3)
error_code, message = message.strip().split(" ", 1)
yield filename, int(line_number), error_code
for filename, error_tuples in groupby(
parse_flake8_errors(args.errors), key=lambda error_tuple: error_tuple[0]
errors = defaultdict(set)
for _, line_number, code in error_tuples:
with fileinput.input(files=[filename], inplace=not args.dry_run) as fp:
for line_number, line in enumerate(fp, start=1):
if line_number not in errors:
# line already has a newline, so don't add an extra
print(line, end="")
elif "noqa" in line or line.strip().endswith("\\"):
print("skipping {}:{}".format(filename, line_number), file=sys.stderr)
print(line, end="")
# note the fileinput inplace captures output and writes back to the file
print(line.rstrip("\n") + " # noqa: " + ", ".join(errors[line_number]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment