Русские Блоги
PyCharm выборочно игнорирует предупреждающие сообщения в стиле кода PEP8
Персональная классификация:Инструменты разработки
Заявление об авторском праве: эта статья является оригинальной статьей блоггеров и не может быть воспроизведена без разрешения блоггеров. https://blog.csdn.net/zgljl2012/article/details/51907663
После использования PyCharm в течение нескольких дней я обнаружил, что он действительно очень полезен при написании кода Python, но один опыт не очень хорош, то есть код должен быть написан в соответствии со стилем кода PEP8, в противном случае появится волнообразное предупреждающее сообщение. Решение заключается в следующем:
Способ первый:
Подведите мышь к подсказке и нажмитеalt+Enter, Выберите, чтобы игнорировать (игнорировать) эту ошибку хорошо.
Способ второй
Найдено под питономPEP8 coding style violation, Игнорировать предупреждающее сообщение ID можно добавить в Игнорировать ошибки справа ниже, как показано ниже:
Например, E302 игнорирует предупреждение «ожидается 2 пустых строки, найдено 0» (появляется, когда я хочу добавить комментарий к методу).
Идентификатор, соответствующий предупреждению, находится по адресуhttp://pep8.readthedocs.io/en/latest/intro.html#configurationМожно найти в.
Приложение выглядит следующим образом:
| code | sample message |
|---|---|
| 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 |
| E305 | expected 2 blank lines after end of function or class |
| 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 |
| 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’ |
| 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()’ |
Интеллектуальная рекомендация
Многослойная презентацияViewController Jap
Распечатать список с конца до головы
В случае, когда таблица цепи не может изменять дисплей, данные хранения стека могут рассматриваться с рекурсивным методом. Разрешить модификацию структуры ссылки.
Типы данных и переменные
тип данных Компьютерная программа может обрабатывать различные значения. Однако компьютеры могут обрабатывать гораздо больше, чем числовые значения. Они также могут обрабатывать различные данные, таки.
оглавление 1. Одно место 2. Случайное расположение 3. Добавьте баллы для оценки 4. Получение файла 5. Установите уровень сложности. 6. Срок завершения 7. Выберите заполнение пропусков. 1. Одно место Н.
Русские Блоги
Summary Python Pep8, вызванный методом, может быть статичным
Преступность
Недавно я столкнусь с этой проблемой, когда разработан Python: Pycharm: Метод может быть статичным, проблем нет, но он всегда повлиял на код, как показано ниже
Это потому, что методы, которые мы объявили в классе, не используют переменные в классе. Это говорит нам, что это статический метод и может быть надежно объявлен как статический тип.
Решение следующее: удалить себя в статический метод, тогда вы можете объявить его в этом методе. Как показано ниже:
Спецификация Pep8
Так что опять же, сделайте больше записей о спецификации кода Python Pep8
Если вы хотите выборочно игнорировать стиль кода PEP8, вы можете использовать следующие методы:
1 сделал мышь на предупреждающее сообщение, нажмите alt+Enter Выберите игнорировать (игнорировать) эту ошибку
Приложение: все предупреждающие данные и соответствующий идентификатор,Официальный адрес: https://pep8.readthedocs.io/en/latest/intro.html# Коды ошибок
Я вообще ленивый, поэтому я рекомендую вам ярлык здесь. Ctrl + alt + L, Спецификация форматирования одной кнопки используется, используется вор, я надеюсь помочь друзьям
E261 at least two spaces before inline comment что это
indentation contains mixed spaces and tabs
indentation is not a multiple of four
expected an indented block
indentation is not a multiple of four (comment)
expected an indented block (comment)
unexpected indentation (comment)
continuation line under-indented for hanging indent
continuation line missing indentation or outdented
closing bracket does not match indentation of opening bracket’s line
closing bracket does not match visual indentation
continuation line with same indent as next logical line
continuation line over-indented for hanging indent
continuation line over-indented for visual indent
continuation line under-indented for visual indent
visually indented line with same indent as next logical line
continuation line unaligned for hanging indent
closing bracket is missing indentation
multiple spaces before operator
multiple spaces after operator
tab before operator
tab after operator
missing whitespace around operator
missing whitespace around arithmetic operator
missing whitespace around bitwise or shift operator
missing whitespace around modulo operator
missing whitespace after ‘,’, ‘;’, or ‘:’
multiple spaces after ‘,’
unexpected spaces around keyword / parameter equals
at least two spaces before inline comment
inline comment should start with ‘# ‘
block comment should start with ‘# ‘
too many leading ‘#’ for block comment
multiple spaces after keyword
multiple spaces before keyword
tab before keyword
missing whitespace after keyword E3 Blank line*
expected 1 blank line, found 0
expected 2 blank lines, found 0
too many blank lines (3)
blank lines found after function decorator E4 Import*
multiple imports on one line
module level import not at top of file E5 Line length*
line too long (82 > 79 characters)
the backslash is redundant between brackets E7 Statement*
multiple statements on one line (colon)
multiple statements on one line (semicolon)
statement ends with a semicolon
multiple statements on one line (def)
comparison to None should be ‘if cond is None:’
comparison to True should be ‘if cond is True:’ or ‘if cond:’
test for membership should be ‘not in’
test for object identity should be ‘is not’
do not compare types, use ‘isinstance()’
do not assign a lambda expression, use a def
SyntaxError or IndentationError
indentation contains tabs
no newline at end of file
blank line contains whitespace W3 Blank line warning*
blank line at end of file W5 Line break warning*
line break occurred before a binary operator
.has_key() is deprecated, use ‘in’
deprecated form of raising exception
backticks are deprecated, use ‘repr()’
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Review Flake8 configuration, remove rules from ignore that would improve our code quality #55
Comments
brylie commented Sep 4, 2017 •
While auditing the project code quality (#33), I noticed that several Flake8 rules were being ignored:
| [flake8] |
| ignore = E128,E265,E261,E126,E501,E302,E262,E127,E303,E226,E231,E201,E202,E121,E203,E123,W293,W391,E122,W292,F403,E401,E131,W503,E731,E266 |
While it may be desirable to ignore some Flake8 rules, there are likely rules being ignored that would encourage good coding practices. For example, we are lacking a lot of docstrings in CiviWiki modules and classes.
Rules we currently ignore
Continuation lines
Comments
Whitespace
Other
Refine the Flake8 configuration. Ignore fewer Flake8 rules. Improve our code quality/practices.
The text was updated successfully, but these errors were encountered:
brylie commented Sep 4, 2017
After a brief search, I found out that we should be able to exclude our migrations from Flake8:
brylie commented Sep 4, 2017 •
At the least, I think we can stop ignoring the whitespace rules. I see that we are overriding the line length rule, but would defer to Two Scoops of Django authors regarding their opinion about line length:
On open source projects, there should be a hard 79-character limit. Our experience has shown
that contributors or visitors to these projects will grumble about line length issues; however, it
has not kept contributors away and we feel the value isn’t lost.
JOO33 commented Apr 25, 2018
@brylie I believe these were personal flake8 configs from a previous developer to the project that was never revisited. I’m not opposed to removing all of these rules for now, and opening the floodgate for the changes that it will require
brylie commented Apr 27, 2018
Haha OK. Sounds like it’s worth a try!
gorkemarslan commented Oct 13, 2021
I am assigning myself to this issue. I think I’ll remove most of the rules. (maybe all of them). I’m searching for which rules are appropriate for the Django projects.
brylie commented Oct 14, 2021
Sounds good. We should also harmonize the flake8 and black rules, as described in the black documentation.
Please see the related pull request to add a flake8 step to our CI process: #1119
gorkemarslan commented Oct 16, 2021
In our linting workflow:
| — name : Lint |
| uses : py-actions/flake8@v1 |
| with : |
| ignore : » E203,W503 « |
| max-line-length : » 88 « |
| exclude : » **/migrations/*.py « |
@brylie, according to the link you sent I will set up flake8 to be compatible with black :
So I only apply these changes and remove others.
One thing worth mentioning is that recommended max-line-length by Django is 120.
An exception to PEP 8 is our rules on line lengths. Don’t limit lines of code to 79 characters if it means the code looks significantly uglier or is harder to read. We allow up to 119 characters as this is the width of GitHub code review; anything longer requires horizontal scrolling which makes review more difficult.
But black default is 88 so I’ll set up flake8 to be 88. Let’s do not listen to what Django says here. 🙂
E261 at least two spaces before inline comment что это
Проверка стиля и требований к используемому синтаксису в python коде для ejudge
Данный модуль реализует проверку синтаксиса python кода в ejudge с русификацией комментариев. Проверка прогнана на
190000 файлах, сданных в тестирующую систему 179-й школы г.Москва. Русифицированы все тексты ошибок, которые возникли при этой проверке. Вот примеры наиболее популярных «ошибок»:
Кроме того, модуль возволяет выполнить проверку используемого синтаксиса. Настройка выполняется в serve.cfg путём указания переменных окружения для style-checker’а. Добавляются примерно такие настройки:
И наконец, в переменной chk_err_msg_i необходимо указать сообщение, которое выдаст валидатор стиля на ошибку.
Да, кстати. Про регулярное выражение, которое проверяет наличие рекурсивной функции. Вот картинка.
Эти настройки можно выполнять на уровне каждой задачи, а также на уровне языкового процессора. При необходимости можно добавить игнорирование отдельных ошибок такой настройкой:
Кроме того, имеются следующие настройки:
Ещё можно вообще отключить запуск flake8, если указать параметр
Для установки пакета необходимо из под юзера ejudge или ejcompile выполнить команду
Затем скопировать скрипт в удобное место (заменить ejcompile на ejudge, если проверка происходит из-под ejudge):
cp /home/ejcompile/.local/bin/flake8ejudge /home/ejcompile/bin/flake8ejudge
После этого нужно добавить в serve.cfg в часть с описанием языкового процессора команду запуска:
Либо можно прописать все эти параметры через GUI. В настройках контеста необходимо перейти на вкладку «Language settings», выбрать Python. вставить flake8ejudge в поле «Style checker command:».
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means.
Популярные ошибки (именно они русифицированы)
Игнорируются по умолчанию:
Проверяются по умолчанию:
About
Русификация и фичи flake8 для проверки стиля в ejudge






