Descriptions and examples for each of the rules in Flake8 (pyflakes, pycodestyle, and mccabe).
pycodestyle
E101 | Indentation contains mixed spaces and tabs |
E111 | Indentation is not a multiple of four |
E112 | Expected an indented block |
E113 | Unexpected indentation |
E114 | Indentation is not a multiple of four (comment) |
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 |
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 |
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 |
E301 | Expected 1 blank line, found 0 |
E302 | Expected 2 blank lines, found 0 |
E303 | Too many blank lines (3) |
E304 | Blank lines found after function decorator |
E305 | Expected 2 blank lines after end of function or class |
E401 | Multiple imports on one line |
E402 | Module level import not at top of file |
E501 | Line too long (82 > 79 characters) |
E502 | The backslash is redundant between brackets |
E701 | Multiple statements on one line (colon) |
E702 | Multiple statements on one line (semicolon) |
E703 | Statement ends with a semicolon |
E704 | Multiple statements on one line (def) |
E711 | Comparison to none should be ‘if cond is none:’ |
E712 | Comparison to true should be ‘if cond is true:’ or ‘if cond:’ |
E713 | Test for membership should be ‘not in’ |
E714 | Test for object identity should be ‘is not’ |
E721 | Do not compare types, use ‘isinstance()’ |
E731 | Do not assign a lambda expression, use a def |
E741 | Do not use variables named ‘l’, ‘o’, or ‘i’ |
E742 | Do not define classes named ‘l’, ‘o’, or ‘i’ |
E743 | Do not define functions named ‘l’, ‘o’, or ‘i’ |
W191 | Indentation contains tabs |
W291 | Trailing whitespace |
W292 | No newline at end of file |
W293 | Blank line contains whitespace |
W391 | Blank line at end of file |
W503 | Line break occurred before a binary operator |
W504 | Line break occurred after a binary operator |
W601 | .has_key() is deprecated, use ‘in’ |
W602 | Deprecated form of raising exception |
W603 | ‘<>’ is deprecated, use ‘!=’ |
W604 | Backticks are deprecated, use ‘repr()’ |
W605 | invalid escape sequence ‘x’ |
pyflakes
F401 | Module imported but unused |
F402 | Import module from line n shadowed by loop variable |
F403 | ‘from module import *’ used; unable to detect undefined names |
F404 | Future import(s) name after other statements |
F405 | Name may be undefined, or defined from star imports: module |
F811 | Redefinition of unused name from line n |
F812 | List comprehension redefines name from line n |
F821 | Undefined name name |
F822 | Undefined name name in __all__ |
F823 | Local variable name … referenced before assignment |
F831 | Duplicate argument name in function definition |
F841 | Local variable name is assigned to but never used |
mccabe
pep8
Reference: Pep8 Error Codes
E1
Indentation
E101
indentation contains mixed spaces and tabs
E111
indentation is not a multiple of four
E112
expected an indented block
E113
unexpected indentation
E114
indentation is not a multiple of four (comment)
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
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
E302
expected 2 blank lines, found 0
E303
too many blank lines (3)
E304
blank lines found after function decorator
E4 Import*
E401
multiple imports on one line
E402
module level import not at top of file
E5 Line length*
E501
line too long (82 > 79 characters)
E502
the backslash is redundant between brackets
E7 Statement*
E701
multiple statements on one line (colon)
E702
multiple statements on one line (semicolon)
E703
statement ends with a semicolon
E704
multiple statements on one line (def)
E711
comparison to None should be ‘if cond is None:’
E712
comparison to True should be ‘if cond is True:’ or ‘if cond:’
E713
test for membership should be ‘not in’
E714
test for object identity should be ‘is not’
E721
do not compare types, use ‘isinstance()’
E731
do not assign a lambda expression, use a def
E9
Runtime
E901
SyntaxError or IndentationError
E902
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 occurred before a binary operator
W6
Deprecation warning*
W601
.has_key() is deprecated, use ‘in’
W602
deprecated form of raising exception
W603
‘<>’ is deprecated, use ‘!=’
W604
backticks are deprecated, use ‘repr()’
Учитывая большую унаследованную кодовую базу Python в GitLab, неразумно отказываться от конвейера CI/CD из-за нарушений flake8, потому что решение проблем в таком объеме унаследованного кода полностью затормозит разработку. Существует ли вместо этого способ настроить конвейер CI/CD «качества кода» так, чтобы он не срабатывал при добавленных нарушениях flake8 (или другого бесплатного статического анализатора кода), чтобы гарантировать, что непрерывная разработка улучшает код, а не унижает его? Спасибо!
1 ответ
Тем важнее количество нарушений в новом кодексе.
Если ваш отчет flake8 похож на
flake8
.main.py:4:1: E302 expected 2 blank lines, found 1
.main.py:4:4: E271 multiple spaces after keyword
.main.py:4:14: E203 whitespace before ':'
.main.py:5:3: E111 indentation is not a multiple of 4
.main.py:7:1: E302 expected 2 blank lines, found 1
.main.py:7:4: E271 multiple spaces after keyword
.main.py:7:20: E203 whitespace before ':'
.main.py:8:3: E111 indentation is not a multiple of 4
.main.py:8:11: W291 trailing whitespace
.main.py:8:13: W292 no newline at end of file
Анализ только различий с унаследованным кодом. Добавьте тег git «устаревший» на устаревшую базу.
git diff -U0 legacy
diff --git a/main.py b/main.py
index 39722c7..aeff3ad 100755
--- a/main.py
+++ b/main.py
@@ -5 +5,4 @@ def Test11() :
- return 5
No newline at end of file
+ return 5
+
+def TestNewCode() :
+ return 5
No newline at end of file
И вычислять нарушения только на различиях с этим тегом.
git diff -U0 legacy | flake8 --diff -
main.py:5:3: E111 indentation is not a multiple of 4
main.py:7:1: E302 expected 2 blank lines, found 1
main.py:7:4: E271 multiple spaces after keyword
main.py:7:20: E203 whitespace before ':'
main.py:8:3: E111 indentation is not a multiple of 4
main.py:8:11: W291 trailing whitespace
main.py:8:13: W292 no newline at end of file
0
Youen
18 Окт 2022 в 23:55
Вопрос №78639 от пользователя Денис в уроке «Операции над множествами», курс «Python: словари и множества»
Денис
Добрый вечер! Никак не пойму — где он пробел все хочет? /usr/src/app/src/solution.py:7:13: E271 multiple spaces after keyword
https://ru.hexlet.io/code_reviews/786353
Вижу что 13 строка — где уже не ставил, все равно ругается…
2
0
Artyom Kropp
Привет! В выводе линтера указывается 7:13, а это значит 7 строка 13 символ.
0
Денис
Artyom Kropp, вон оно что)
0
Используйте Хекслет по-максимуму!
-
Задавайте вопросы по уроку -
Проверяйте знания в квизах -
Проходите практику прямо в браузере -
Отслеживайте свой прогресс
Зарегистрируйтесь или
войдите в свой аккаунт
Рекомендуемые программы
С нуля до разработчика. Возвращаем деньги, если не удалось найти работу.
Разработка фронтенд-компонентов для веб-приложений
9 февраля
10 месяцев
Интенсивное обучение профессии в режиме полного дня
9 февраля
4 месяца
Разработка веб-приложений на Django
9 февраля
10 месяцев
Разработка приложений на языке Java
9 февраля
10 месяцев
Разработка веб-приложений на Laravel
9 февраля
10 месяцев
Ручное тестирование веб-приложений
9 февраля
4 месяца
Разработка бэкенд-компонентов для веб-приложений
9 февраля
10 месяцев
Разработка фронтенд- и бэкенд-компонентов для веб-приложений
9 февраля
16 месяцев
Создание веб-приложений со скоростью света
9 февраля
5 месяцев
Верстка с использованием последних стандартов CSS
в любое время
5 месяцев
Профессия
В разработке
с нуля
Сбор, анализ и интерпретация данных
16 марта
8 месяцев
I reduced the issue to the following minimal example:
"""Example"""
def answer():
"""Answer"""
return 42
Pylint doesn’t give any «bad whitespace» warning:
Your code has been rated at 10.00/10 (previous run: 10.00/10, +0.00)
Pylint does give warnings for spaces in front of brackets and trailing whitespace or newlines and so on. Why are there no warnings in this case?
asked Jun 17, 2019 at 21:16
2
Whitespaces can be used to:
- separate tokens (and you can have as many as you want)
- indentation, important for blocks
In case of return
, you would have an error if its indentation was incoherent with other elements in its block:
for x in p:
r.append(l[i:i+1] + x)
return r # error: inconsistent dedent
But in your case, it is alone in its def
block.
And none of the Pylint C0326 would apply here.
answered Aug 2, 2019 at 16:04
VonCVonC
1.2m508 gold badges4248 silver badges5069 bronze badges
2
I recomend you to use Flake8 in your case
Multiple spaces after keyword (E271)
If you are interesting in Flake8, this is the page of all the code error that Flake8 has
answered Aug 2, 2019 at 16:30